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/action/base/AddEntryAction.java
|
package edu.ncsu.csc.itrust.action.base;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.old.beans.EntryBean;
/**
* AddEntryAction.java
* Version 1
* 4/2/2015
* Copyright notice: none
* General behavior for adding entries to a Wellness Diary subcategory.
* Food Diary.
*
*/
public interface AddEntryAction {
/**
* Adds a new entry to its associated diary in the database.
*
* @param entry
* the Bean to add.
* @return Success/error message.
* @throws FormValidationException
*/
public String addEntry(EntryBean entry) throws FormValidationException;
}
| 638
| 24.56
| 72
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/base/DeleteEntryAction.java
|
package edu.ncsu.csc.itrust.action.base;
import edu.ncsu.csc.itrust.exception.ITrustException;
public interface DeleteEntryAction {
/**
* Deletes a diary entry from the db
*
* @param entryID
* the entry to delete
* @return the number of rows deleted (should never exceed 1)
* @throws ITrustException
*/
public int deleteEntry(long entryID) throws ITrustException;
}
| 396
| 23.8125
| 62
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/base/EditEntryAction.java
|
package edu.ncsu.csc.itrust.action.base;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.exception.ITrustException;
import edu.ncsu.csc.itrust.model.old.beans.EntryBean;
public interface EditEntryAction {
/**
* Communicates changes between a JSP page and the server for a given
* Wellness Diary entry.
*
* @param entry
* the bean to be updated
* @return the number of rows updated (0 means nothing happened, -1 means
* the logged in user cannot edit this entry, and anything else is
* the number of rows updated which should never exceed 1)
* @throws ITrustException
*/
public int editEntry(EntryBean entry) throws ITrustException,
FormValidationException;
}
| 755
| 33.363636
| 75
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/base/PatientBaseAction.java
|
package edu.ncsu.csc.itrust.action.base;
import edu.ncsu.csc.itrust.HtmlEncoder;
import edu.ncsu.csc.itrust.exception.ITrustException;
import edu.ncsu.csc.itrust.model.old.dao.DAOFactory;
/**
* An abstract class for dealing with actions that require an associated patient. The concrete functionality
* provided by this class allows for asserting the correctness and existence of patients' MIDs.
*
* Use this class whenever your JSP requires a patient ID when it loads (e.g. editPatient.jsp). The patient
* string is passed to the constructor of this class and is checked for both format and existence. If the
* patient ID is wrong in any way, an exception is thrown, resulting in the user getting kicked out to the
* home page.
*
* Very similar to {@link PersonnelBaseAction} and {@link OfficeVisitBaseAction}
*
* Subclasses need not rewrite this functionality, and they are not held to any strict contract to extend this
* class.
*/
public class PatientBaseAction {
/**
* The database access object factory to associate this with a runtime context.
*/
private DAOFactory factory;
/**
* Stores the MID of the patient associated with this action.
*/
protected long pid;
/**
* The default constructor.
*
* @param factory
* A factory to create a database access object.
* @param pidString
* The patient's ID to associate with this action.
* @throws ITrustException
* If the patient's ID is incorrect or there is a DB problem.
*/
public PatientBaseAction(DAOFactory factory, String pidString) throws ITrustException {
this.factory = factory;
this.pid = checkPatientID(pidString);
}
/**
* Asserts whether the input is a valid, existing patient's MID.
*
* @param input
* The presumed MID
* @return The existing patient's ID as a long.
* @throws ITrustException
* If the patient does not exist or there is a DB Problem.
*/
private long checkPatientID(String input) throws ITrustException {
try {
long pid = Long.valueOf(input);
if (factory.getPatientDAO().checkPatientExists(pid))
return pid;
else
throw new ITrustException("Patient does not exist");
} catch (NumberFormatException e) {
throw new ITrustException("Patient ID is not a number: " + HtmlEncoder.encode(input));
}
}
protected DAOFactory getFactory() {
return factory;
}
/**
* Retrieves the identifier of the patient as a long.
*
* @return The patient's MID.
*/
public long getPid() {
return pid;
}
}
| 2,539
| 29.97561
| 110
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/base/PersonnelBaseAction.java
|
package edu.ncsu.csc.itrust.action.base;
import edu.ncsu.csc.itrust.exception.ITrustException;
import edu.ncsu.csc.itrust.model.old.dao.DAOFactory;
/**
* An abstract class for dealing with actions that require an associated personnel. The concrete functionality
* provided by this class allows for asserting the correctness and existence of personnel' MIDs.
*
* Use this class whenever your JSP requires a personnel ID when it loads (e.g. editPatient.jsp). The patient
* string is passed to the constructor of this class and is checked for both format and existence. If the
* patient ID is wrong in any way, an exception is thrown, resulting in the user getting kicked out to the
* home page.
*
* Subclasses need not rewrite this functionality, and they are not held to any strict contract to extend this
* class.
*
* Very similar to {@link PatientBaseAction}
*/
public class PersonnelBaseAction {
/**
* The database access object factory to associate this with a runtime context.
*/
private DAOFactory factory;
/**
* Stores the MID of the personnel associated with this action.
*/
protected long pid;
/**
* The default constructor.
*
* @param factory
* A factory to create a database access object.
* @param pidString
* The personnel's ID to associate with this action.
* @throws ITrustException
* If the personnel's ID is incorrect or there is a DB problem.
*/
public PersonnelBaseAction(DAOFactory factory, String pidString) throws ITrustException {
this.factory = factory;
this.pid = checkPersonnelID(pidString);
}
/**
* Asserts whether the input is a valid, existing personnel's MID.
*
* @param input
* The presumed MID
* @return The existing personnel's ID as a long.
* @throws ITrustException
* If the personnel does not exist or there is a DB Problem.
*/
private long checkPersonnelID(String input) throws ITrustException {
try {
long pid = Long.valueOf(input);
if (factory.getPersonnelDAO().checkPersonnelExists(pid))
return pid;
else
throw new ITrustException("Personnel does not exist");
} catch (NumberFormatException e) {
throw new ITrustException("Personnel ID is not a number: " + e.getMessage());
}
}
/**
* Retrieves the identifier of the patient as a long.
*
* @return The patient's MID.
*/
public long getPid() {
return pid;
}
}
| 2,425
| 30.506494
| 110
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/base/ViewEntryAction.java
|
package edu.ncsu.csc.itrust.action.base;
import java.util.List;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.exception.ITrustException;
/**
* ViewEntryAction.java
* Version 1
* 4/2/2015
* Copyright notice: none
* General behavior for viewing entries in the Wellness Diary.
* Food Diary.
*
*/
public interface ViewEntryAction {
/**
* Gets all entries in the diary for a given patient.
*
* @param patientMID
* the id of the patient whose diary we want
* @return a list of the patient's diary entries
*/
public List<?> getDiary(long patientMID) throws ITrustException;
/**
* Gets the totals relevant to the specific Wellness
* Diary page, sorted by day.
*
* @param patientMID
* the patient we are looking at
* @return an entry that contains the totals for each day that
* a user has an entry in his diary
* @throws ITrustException
*/
public List<?> getDiaryTotals(long patientMID) throws ITrustException;
/**
* Returns a list of diary entries between two dates.
*
* @param lowerDate
* the first date
* @param upperDate
* the second date
* @return list of TransactionBeans
* @throws DBException
* @throws FormValidationException
*/
public List<?> getBoundedDiary(String lowerDate, String upperDate, long patientMID)
throws ITrustException, FormValidationException;
/**
* Gets the totals relevant to the specific Wellness Diary
* page, bound between two dates, sorted by entry date.
*
* @param lowerDate
* the first date
* @param upperDate
* the second date
* @param patientMID
* the patient we are looking at
* @return an entry that contains the totals for each
* day in the bounded range.
* @throws ITrustException
*/
public List<?> getBoundedDiaryTotals(String lowerDate, String upperDate, long patientMID)
throws ITrustException, FormValidationException;
}
| 2,056
| 27.569444
| 90
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/NavigationController.java
|
package edu.ncsu.csc.itrust.controller;
import java.io.IOException;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import edu.ncsu.csc.itrust.controller.user.patient.PatientController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.webutils.SessionUtils;
@ManagedBean(name = "navigation_controller")
@RequestScoped
public class NavigationController {
private PatientController patientController;
public NavigationController() throws DBException {
patientController = new PatientController();
}
/**
* Navigate to the getPatientID page if the current patientID stored in the
* session variable is null
*
* @throws DBException
* @throws IOException
*/
public void redirectIfInvalidPatient() throws DBException, IOException {
ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
long pid = 0;
Map<String, Object> session = ctx.getSessionMap();
Object pidObj = session.get("pid");
if (pidObj instanceof Long) {
pid = (long) pidObj;
}
if ((pidObj == null) || (!(patientController.doesPatientExistWithID(Long.toString(pid))))) {
updatePatient();
}
}
/**
* Navigate to getPatientID from current URL
*
* @throws DBException
* @throws IOException
*/
public void updatePatient() throws DBException, IOException {
ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
Object req = ctx.getRequest();
String url = "";
if (req instanceof HttpServletRequest) {
HttpServletRequest req2 = (HttpServletRequest) req;
url = req2.getRequestURI();
}
ctx.redirect("/iTrust/auth/getPatientID.jsp?forward=" + url);
}
public static void baseOfficeVisit() throws IOException {
ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
if (ctx != null) {
ctx.redirect("/iTrust/auth/hcp-uap/viewOfficeVisit.xhtml");
}
}
public static void editOfficeVisit() throws IOException {
ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
if (ctx != null) {
ctx.redirect("/iTrust/auth/hcp-uap/viewOfficeVisit.xhtml");
}
}
public static void officeVisitInfo(Long visitId) throws IOException {
ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
if (ctx != null) {
ctx.redirect("/iTrust/auth/hcp-uap/officeVisitInfo.xhtml?visitID=" + visitId);
}
}
public static void officeVisitInfo() throws IOException {
Long officeVisitId = SessionUtils.getInstance().getCurrentOfficeVisitId();
officeVisitInfo(officeVisitId);
}
public void redirectToOfficeVisitInfoIfNeeded(boolean shouldRedirect) throws DBException, IOException {
if (shouldRedirect) {
baseOfficeVisit();
}
}
public static void patientViewOfficeVisit() throws IOException {
ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
if (ctx != null) {
ctx.redirect("/iTrust/auth/patient/viewOfficeVisit.xhtml");
}
}
}
| 3,133
| 30.029703
| 104
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/iTrustController.java
|
package edu.ncsu.csc.itrust.controller;
import javax.faces.application.FacesMessage.Severity;
import edu.ncsu.csc.itrust.logger.TransactionLogger;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
import edu.ncsu.csc.itrust.webutils.SessionUtils;
/**
* Base class for all controllers in iTrust containing functionality universally
* applicable to controllers.
*
* @author mwreesjo
*/
public class iTrustController {
private SessionUtils sessionUtils;
private TransactionLogger logger;
/**
* A fallback error message to be displayed when something goes unexpectedly
* wrong (for example, an Exception from an unknown source is thrown).
*/
protected static final String GENERIC_ERROR = "Something went wrong and the action couldn't be completed.";
public iTrustController() {
this(null, null);
}
/**
* Initializes iTrustController with SessionUtils and TransactionLogger
* instances. Initializes sessionUtils and logger if they are null.
*
* @param sessionUtils
* @param logger
*/
public iTrustController(SessionUtils sessionUtils, TransactionLogger logger) {
if (sessionUtils == null) {
sessionUtils = SessionUtils.getInstance();
}
if (logger == null) {
logger = TransactionLogger.getInstance();
}
setSessionUtils(sessionUtils);
setTransactionLogger(logger);
}
protected TransactionLogger getTransactionLogger() {
return logger;
}
public void setTransactionLogger(TransactionLogger logger) {
this.logger = logger;
}
protected SessionUtils getSessionUtils() {
return sessionUtils;
}
public void setSessionUtils(SessionUtils sessionUtils) {
this.sessionUtils = sessionUtils;
}
/**
* @see {@link SessionUtils#printFacesMessage(Severity, String, String, String)}
*/
public void printFacesMessage(Severity severity, String summary, String detail, String clientId) {
sessionUtils.printFacesMessage(severity, summary, detail, clientId);
}
/**
* @see {@link TransactionLogger#logTransaction(TransactionType, long, long, String)}
*/
public void logTransaction(TransactionType type, Long loggedInMID, Long secondaryMID, String addedInfo) {
TransactionLogger.getInstance().logTransaction(type, loggedInMID, secondaryMID, addedInfo);
}
/**
* Logs the TransactionType and added info with current loggedInMID and
* current patientMID.
*/
public void logTransaction(TransactionType type, String addedInfo) {
Long loggedInMID = sessionUtils.getSessionLoggedInMIDLong();
Long patientMID = sessionUtils.getCurrentPatientMIDLong();
logTransaction(type, loggedInMID, patientMID, addedInfo);
}
}
| 2,601
| 28.568182
| 108
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/apptType/ApptTypeController.java
|
package edu.ncsu.csc.itrust.controller.apptType;
import java.util.List;
import javax.faces.bean.ManagedBean;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.apptType.*;
@ManagedBean(name="appt_type_controller")
public class ApptTypeController {
private static ApptTypeData apptTypeData;
public ApptTypeController() throws DBException{
if(apptTypeData == null){
ApptTypeController.apptTypeData = new ApptTypeMySQLConverter();
}
}
public List<ApptType> getApptTypelList() throws DBException{
return apptTypeData.getAll();
}
}
| 585
| 22.44
| 66
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/cptcode/CPTCodeController.java
|
package edu.ncsu.csc.itrust.controller.cptcode;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.cptcode.CPTCode;
import edu.ncsu.csc.itrust.model.cptcode.CPTCodeMySQL;
@ManagedBean(name = "cptcode_controller")
@SessionScoped
public class CPTCodeController extends iTrustController {
private static final String INVALID_CODE = "Invalid CPT Code";
private static final String UNKNOWN_ERROR = "Unknown error";
private static final String NONEXISTENT_CODE = "Code does not exist";
private static final String DUPLICATE_CODE = "Cannot add duplicate code";
private CPTCodeMySQL sql;
//private SessionUtils sessionUtils;
public CPTCodeController() {
try {
sql = new CPTCodeMySQL();
} catch (DBException e) {
sql = null;
}
}
/**
* Constructor injection, intended only for unit testing purposes.
*
* @param ds
* The injected DataSource dependency
*/
public CPTCodeController(DataSource ds) {
sql = new CPTCodeMySQL(ds);
}
/**
* Setter injection for lab procedure data. ONLY use for unit testing
* purposes.
*/
public void setMySQL(CPTCodeMySQL data) {
this.sql = data;
}
/**
* Adds a cptCode.
*
* @param code
* The code to add
*/
public void add(CPTCode code) {
try {
if (!sql.add(code)){
printFacesMessage(FacesMessage.SEVERITY_ERROR, DUPLICATE_CODE, DUPLICATE_CODE, null);
}
} catch (FormValidationException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_CODE, e.getErrorList().toString(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
/**
* Updates a cptCode. Prints FacesContext info message when
* successfully updated, error message when the update fails.
*
* @param code
* The code to add
*/
public void edit(CPTCode code) {
try {
if (!sql.update(code)){
printFacesMessage(FacesMessage.SEVERITY_ERROR, NONEXISTENT_CODE, NONEXISTENT_CODE, null);
}
} catch (FormValidationException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_CODE, e.getErrorList().toString(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public void remove(String cptCodeID) {
try {
if (!sql.delete(new CPTCode(cptCodeID, null))){
printFacesMessage(FacesMessage.SEVERITY_ERROR, NONEXISTENT_CODE, NONEXISTENT_CODE, null);
}
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public CPTCode getCodeByID(String cptCodeID) {
try {
return sql.getByCode(cptCodeID);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
return null;
}
public List<CPTCode> getCodesWithFilter(String filterString){
try {
return sql.getCodesWithFilter(filterString);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
return new ArrayList<>();
}
}
| 3,679
| 29.666667
| 108
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/cptcode/CPTCodeForm.java
|
package edu.ncsu.csc.itrust.controller.cptcode;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import edu.ncsu.csc.itrust.model.cptcode.CPTCode;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name = "cpt_code_form")
@ViewScoped
public class CPTCodeForm {
private CPTCodeController controller;
private CPTCode cptCode;
private String code;
private String description;
private String search;
private boolean displayCodes;
public CPTCodeForm() {
this(null);
}
public CPTCodeForm(CPTCodeController cptCodeController) {
controller = (cptCodeController == null) ? new CPTCodeController() : cptCodeController;
search = "";
setDisplayCodes(false);
}
public void add() {
setCptCode(new CPTCode(code, description));
controller.add(cptCode);
controller.logTransaction(TransactionType.MEDICAL_PROCEDURE_CODE_ADD, code);
controller.logTransaction(TransactionType.IMMUNIZATION_CODE_ADD, code);
code = "";
description = "";
}
public void update() {
setCptCode(new CPTCode(code, description));
controller.edit(cptCode);
controller.logTransaction(TransactionType.MEDICAL_PROCEDURE_CODE_EDIT, code);
controller.logTransaction(TransactionType.IMMUNIZATION_CODE_EDIT, code);
code = "";
description = "";
}
public void delete() {
setCptCode(new CPTCode(code, description));
controller.remove(code);
code = "";
description = "";
}
public List<CPTCode> getCodesWithFilter() {
return controller.getCodesWithFilter(search);
}
public void fillInput(String code, String description) {
this.code = code;
this.description = description;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
public CPTCode getCptCode() {
return cptCode;
}
public void setCptCode(CPTCode cptCode) {
this.cptCode = cptCode;
}
public boolean getDisplayCodes() {
return displayCodes;
}
/**
* Sets whether or not search results matching the given search string
* should be rendered. If displayCodes is true, this logs the view action
* for all codes matching the search filter.
*
* @param displayCodes
*/
public void setDisplayCodes(boolean displayCodes) {
this.displayCodes = displayCodes;
// Log if displaying search results
if(this.displayCodes) {
logViewCPTCodes();
}
}
/**
* Logs a view action for each CPT code matching the current search query.
* Only logs if search query is non-empty.
*/
private void logViewCPTCodes() {
if(!"".equals(search)) {
for(CPTCode code : controller.getCodesWithFilter(search)) {
controller.logTransaction(TransactionType.MEDICAL_PROCEDURE_CODE_VIEW, code.getCode());
controller.logTransaction(TransactionType.IMMUNIZATION_CODE_VIEW, code.getCode());
}
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 3,446
| 25.113636
| 95
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/diagnosis/DiagnosisController.java
|
package edu.ncsu.csc.itrust.controller.diagnosis;
import java.util.Collections;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.diagnosis.Diagnosis;
import edu.ncsu.csc.itrust.model.diagnosis.DiagnosisData;
import edu.ncsu.csc.itrust.model.diagnosis.DiagnosisMySQL;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name="diagnosis_controller")
@SessionScoped
public class DiagnosisController extends iTrustController {
private DiagnosisData sql;
private static final String INVALID_DIAGNOSIS = "Invalid diagnosis";
/**
* Default constructor for DiagnosisController
* @throws DBException
*/
public DiagnosisController() throws DBException {
super();
sql = new DiagnosisMySQL();
}
/**
* Constructor injection, intended only for unit testing purposes.
*
* @param ds
* The injected DataSource dependency
*/
public DiagnosisController(DataSource ds) throws DBException {
super();
this.sql = new DiagnosisMySQL(ds);
}
/**
* Set the MySQL instance for testing purposes
* @param sql
*/
public void setSql(DiagnosisMySQL sql){
this.sql = sql;
}
public void add(Diagnosis diagnosis) {
try {
if (sql.add(diagnosis)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Diagnosis is successfully created",
"Diagnosis is successfully created", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.DIAGNOSIS_ADD, ovid == null ? null : ovid.toString());
} else {
throw new Exception();
}
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_DIAGNOSIS, e.getExtendedMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_DIAGNOSIS, INVALID_DIAGNOSIS, null);
}
}
public void edit(Diagnosis diagnosis) {
try {
if (sql.update(diagnosis)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Prescription is successfully updated",
"Prescription is successfully updated", null);
} else {
throw new Exception();
}
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_DIAGNOSIS, e.getExtendedMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_DIAGNOSIS, INVALID_DIAGNOSIS, null);
}
}
public void remove(long diagnosisID) {
try {
if (sql.remove(diagnosisID)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Diagnosis is successfully deleted",
"Diagnosis is successfully deleted", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.DIAGNOSIS_REMOVE, ovid == null ? null : ovid.toString());
} else {
throw new Exception();
}
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_DIAGNOSIS, e.getExtendedMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_DIAGNOSIS, INVALID_DIAGNOSIS, null);
}
}
public List<Diagnosis> getDiagnosesByOfficeVisit(long officeVisitID) {
List<Diagnosis> result = Collections.emptyList();
try {
result = sql.getAllDiagnosisByOfficeVisit(officeVisitID);
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_DIAGNOSIS, e.getExtendedMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_DIAGNOSIS, INVALID_DIAGNOSIS, null);
}
return result;
}
}
| 3,764
| 32.318584
| 99
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/diagnosis/DiagnosisForm.java
|
package edu.ncsu.csc.itrust.controller.diagnosis;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.diagnosis.Diagnosis;
import edu.ncsu.csc.itrust.model.icdcode.ICDCode;
import edu.ncsu.csc.itrust.model.icdcode.ICDCodeMySQL;
import edu.ncsu.csc.itrust.webutils.SessionUtils;
@ManagedBean(name = "diagnosis_form")
@ViewScoped
public class DiagnosisForm {
private Diagnosis diagnosis;
private DiagnosisController controller;
private SessionUtils sessionUtils;
private ICDCodeMySQL icdData;
public DiagnosisForm() {
this(null, null, null, null);
}
public DiagnosisForm(DiagnosisController dc, ICDCodeMySQL icdData, SessionUtils sessionUtils, DataSource ds) {
this.sessionUtils = (sessionUtils == null) ? SessionUtils.getInstance() : sessionUtils;
try {
if (ds == null) {
this.controller = (dc == null) ? new DiagnosisController() : dc;
this.icdData = (icdData == null) ? new ICDCodeMySQL() : icdData;
} else {
this.icdData = (icdData == null) ? new ICDCodeMySQL(ds) : icdData;
controller = (dc == null) ? new DiagnosisController(ds) : dc;
}
} catch (DBException e) {
this.sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Diagnosis Controller Error",
"Diagnosis Procedure Controller Error", null);
}
clearFields();
}
/**
* @return list of diagnosis from the current office visit
*/
public List<Diagnosis> getDiagnosesByOfficeVisit() {
return controller.getDiagnosesByOfficeVisit(sessionUtils.getCurrentOfficeVisitId());
}
public Diagnosis getDiagnosis(){
return diagnosis;
}
public void setDiagnosis(Diagnosis dia){
diagnosis = dia;
}
public void add() {
controller.add(diagnosis);
}
public void edit() {
controller.edit(diagnosis);
}
public void remove(String diagnosisId) {
controller.remove(Long.parseLong(diagnosisId));
}
public List<ICDCode> getICDCodes(){
try {
return icdData.getAll();
} catch (SQLException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "ICD Code retrival error", "ICD Code retrival error",
null);
}
return Collections.emptyList();
}
public void clearFields() {
diagnosis = new Diagnosis();
diagnosis.setVisitId(sessionUtils.getCurrentOfficeVisitId());
}
}
| 2,607
| 28.303371
| 125
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/emergencyRecord/EmergencyRecordController.java
|
package edu.ncsu.csc.itrust.controller.emergencyRecord;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.emergencyRecord.EmergencyRecord;
import edu.ncsu.csc.itrust.model.emergencyRecord.EmergencyRecordMySQL;
import edu.ncsu.csc.itrust.model.old.dao.mysql.AllergyDAO;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
/**
* A controller class for EmergencyRecord
* @author nmiles
*
*/
@ManagedBean(name="emergency_record_controller")
@SessionScoped
public class EmergencyRecordController extends iTrustController {
private EmergencyRecordMySQL sql;
/**
* Constructs a new EmergencyRecordController
* @throws DBException
*/
public EmergencyRecordController() throws DBException{
sql = new EmergencyRecordMySQL();
}
/**
* Constructor for testing purposes.
*
* @param ds The DataSource to use
* @param allergyData the AllergyDAO to use
*/
public EmergencyRecordController(DataSource ds, AllergyDAO allergyData) throws DBException{
EmergencyRecordMySQL sql;
sql = new EmergencyRecordMySQL(ds, allergyData);
this.sql = sql;
}
/**
* Loads the appropriate data for an EmergencyRecord for the given MID.
* The loaded record is returned, but it is also stored for later retrieval
* with getRecord(). This method MUST be called before calling getRecord().
*
* @param mid The mid of the patient to load the record for
* @return The loaded EmergencyRecord if loaded successfully, null if
* loading failed
*/
public EmergencyRecord loadRecord(String midString){
long mid;
EmergencyRecord record;
try {
mid = Long.parseLong(midString);
record = sql.getEmergencyRecordForPatient(mid);
} catch (Exception e) {
return null;
}
return record;
}
/**
* Logs that the emergency record has been viewed by the logged in MID for
* the current patient MID. This method should be invoked once per page
* view.
*/
public void logViewEmergencyRecord() {
// If the current patient MID is null, then no patient has been
// selected, and there's no ER to display.
if (getSessionUtils().getCurrentPatientMID() != null) {
logTransaction(TransactionType.EMERGENCY_REPORT_VIEW, null);
}
}
}
| 2,533
| 31.909091
| 95
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/hospital/HospitalController.java
|
package edu.ncsu.csc.itrust.controller.hospital;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.hospital.Hospital;
import edu.ncsu.csc.itrust.model.hospital.HospitalData;
import edu.ncsu.csc.itrust.model.hospital.HospitalMySQLConverter;
@ManagedBean(name="hospital_controller")
public class HospitalController {
private static HospitalData hospitalData;
public HospitalController() throws DBException{
if(hospitalData == null){
HospitalController.hospitalData = new HospitalMySQLConverter();
}
}
//Test Constructor
public HospitalController(DataSource ds) throws DBException{
if(hospitalData == null){
HospitalController.hospitalData = new HospitalMySQLConverter(ds);
}
}
public List<Hospital> getHospitalList() throws DBException{
return hospitalData.getAll();
}
public String HospitalNameForID(String hospitalID){
try {
return hospitalData.getHospitalName(hospitalID);
} catch (Exception e) {
FacesMessage throwMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Location Information", "Invalid Location Information");
FacesContext.getCurrentInstance().addMessage(null,throwMsg);
return "";
}
}
}
| 1,400
| 26.470588
| 137
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/icdcode/ICDCodeController.java
|
package edu.ncsu.csc.itrust.controller.icdcode;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.icdcode.ICDCode;
import edu.ncsu.csc.itrust.model.icdcode.ICDCodeMySQL;
@ManagedBean(name = "icdcode_controller")
@SessionScoped
public class ICDCodeController extends iTrustController {
private static final String INVALID_CODE = "Invalid ICD Code";
private static final String UNKNOWN_ERROR = "Unknown error";
private static final String NONEXISTENT_CODE = "Code does not exist";
private static final String DUPLICATE_CODE = "Cannot add duplicate code";
private ICDCodeMySQL sql;
//private SessionUtils sessionUtils;
public ICDCodeController() {
try {
sql = new ICDCodeMySQL();
} catch (DBException e) {
sql = null;
}
}
/**
* Constructor injection, intended only for unit testing purposes.
*
* @param ds
* The injected DataSource dependency
*/
public ICDCodeController(DataSource ds) {
sql = new ICDCodeMySQL(ds);
}
/**
* Setter injection for lab procedure data. ONLY use for unit testing
* purposes.
*/
public void setSQLData(ICDCodeMySQL data) {
this.sql = data;
}
public void add(ICDCode code) {
try {
if (!sql.add(code)){
printFacesMessage(FacesMessage.SEVERITY_ERROR, DUPLICATE_CODE, DUPLICATE_CODE, null);
}
} catch (FormValidationException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_CODE, e.getErrorList().toString(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public void edit(ICDCode code) {
try {
if (!sql.update(code)){
printFacesMessage(FacesMessage.SEVERITY_ERROR, NONEXISTENT_CODE, NONEXISTENT_CODE, null);
}
} catch (FormValidationException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_CODE, e.getErrorList().toString(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public void remove(String icdCodeID) {
try {
if (!sql.delete(new ICDCode(icdCodeID, null, false))){
printFacesMessage(FacesMessage.SEVERITY_ERROR, NONEXISTENT_CODE, NONEXISTENT_CODE, null);
}
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public ICDCode getCodeByID(String icdCodeID) {
try {
return sql.getByCode(icdCodeID);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
return null;
}
public List<ICDCode> getCodesWithFilter(String filterString){
try {
return sql.getCodesWithFilter(filterString);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
return new ArrayList<>();
}
}
| 3,443
| 31.186916
| 108
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/icdcode/ICDCodeForm.java
|
package edu.ncsu.csc.itrust.controller.icdcode;
import java.util.Collections;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import edu.ncsu.csc.itrust.model.icdcode.ICDCode;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name = "icd_code_form")
@ViewScoped
public class ICDCodeForm {
private ICDCodeController controller;
private ICDCode icdCode;
private String code;
private String description;
private boolean isChronic;
private String search;
private boolean displayCodes;
public ICDCodeForm() {
this(null);
}
public ICDCodeForm(ICDCodeController icdCodeController) {
controller = (icdCodeController == null) ? new ICDCodeController() : icdCodeController;
search = "";
setDisplayCodes(false);
}
public void add() {
setIcdCode(new ICDCode(code, description, isChronic));
controller.add(icdCode);
controller.logTransaction(TransactionType.DIAGNOSIS_CODE_ADD, code);
code = "";
description = "";
isChronic = false;
}
public void update() {
setIcdCode(new ICDCode(code, description, isChronic));
controller.edit(icdCode);
controller.logTransaction(TransactionType.DIAGNOSIS_CODE_EDIT, code);
code = "";
description = "";
isChronic = false;
}
public void delete() {
setIcdCode(new ICDCode(code, description, isChronic));
controller.remove(code);
code = "";
description = "";
isChronic = false;
}
public void fillInput(String code, String description, boolean isChronic) {
this.code = code;
this.description = description;
this.isChronic = isChronic;
}
public List<ICDCode> getCodesWithFilter() {
List<ICDCode> codes = Collections.emptyList();
if (!"".equals(search)) { // Only search if there's a search query
codes = controller.getCodesWithFilter(search);
}
return codes;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
public boolean getDisplayCodes() {
return displayCodes;
}
/**
* Sets whether or not search results matching the given search string
* should be rendered. If displayCodes is true, this logs the view action
* for all codes matching the search filter.
*
* @param displayCodes
*/
public void setDisplayCodes(boolean displayCodes) {
this.displayCodes = displayCodes;
// Log if displaying search results
if (this.displayCodes) {
logViewDiagnosisCodes();
}
}
/**
* Logs a view action for each diagnosis code matching the current search query.
* Only logs if search query is non-empty.
*/
private void logViewDiagnosisCodes() {
if (!"".equals(search)) {
for (ICDCode code : controller.getCodesWithFilter(search)) {
controller.logTransaction(TransactionType.DIAGNOSIS_CODE_VIEW, code.getCode());
}
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ICDCode getIcdCode() {
return icdCode;
}
public void setIcdCode(ICDCode icdCode) {
this.icdCode = icdCode;
}
public boolean getIsChronic() {
return isChronic;
}
public void setIsChronic(boolean isChronic) {
this.isChronic = isChronic;
}
}
| 3,729
| 24.37415
| 95
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/immunization/ImmunizationController.java
|
package edu.ncsu.csc.itrust.controller.immunization;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.immunization.Immunization;
import edu.ncsu.csc.itrust.model.immunization.ImmunizationMySQL;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name = "immunization_controller")
@SessionScoped
public class ImmunizationController extends iTrustController {
private static final String INVALID_IMMUNIZATION = "Invalid Immmunization";
ImmunizationMySQL sql;
public ImmunizationController() throws DBException {
super();
sql = new ImmunizationMySQL();
}
public ImmunizationController(DataSource ds) {
super();
sql = new ImmunizationMySQL(ds);
}
/**
* This is for setting the MySQL instance for testing purposes. Never use
* this except for testing.
* @param newSQL The new SQL instance
*/
public void setSQL(ImmunizationMySQL newSQL){
sql = newSQL;
}
public void add(Immunization immunization) {
try {
if (sql.add(immunization)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Immunization successfully created",
"Immunization successfully created", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.IMMUNIZATION_ADD, ovid == null ? null : ovid.toString());
} else {
throw new Exception();
}
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_IMMUNIZATION, INVALID_IMMUNIZATION, null);
}
}
public void edit(Immunization immunization) {
try {
if (sql.update(immunization)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Immunization successfully updated",
"Immunization successfully updated", null);
} else {
throw new Exception();
}
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_IMMUNIZATION, INVALID_IMMUNIZATION, null);
}
}
public void remove(long immunizationID) {
try {
if (sql.remove(immunizationID)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Immunization successfully deleted",
"Immunization successfully deleted", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.IMMUNIZATION_REMOVE, ovid == null ? null : ovid.toString());
} else {
throw new Exception();
}
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_IMMUNIZATION, e.getMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_IMMUNIZATION, INVALID_IMMUNIZATION, null);
}
}
public List<Immunization> getImmunizationsByOfficeVisit(String officeVisitID) throws DBException {
List<Immunization> immunizations = Collections.emptyList();
long ovID = -1;
if ( officeVisitID != null ) {
ovID = Long.parseLong(officeVisitID);
try {
immunizations = sql.getImmunizationsForOfficeVisit(ovID);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Immunizations", "Unable to Retrieve Immunizations", null);
}
}
return immunizations;
}
public String getCodeName(String codeString){
String codeName = "";
try {
codeName = sql.getCodeName(codeString);
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Immunization", e.getMessage(), null);
}
return codeName;
}
}
| 4,315
| 36.206897
| 141
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/immunization/ImmunizationForm.java
|
package edu.ncsu.csc.itrust.controller.immunization;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.cptcode.CPTCode;
import edu.ncsu.csc.itrust.model.cptcode.CPTCodeMySQL;
import edu.ncsu.csc.itrust.model.immunization.Immunization;
import edu.ncsu.csc.itrust.webutils.SessionUtils;
@ManagedBean(name = "immunization_form")
@ViewScoped
public class ImmunizationForm {
private Immunization immunization;
private ImmunizationController controller;
private SessionUtils sessionUtils;
private CPTCodeMySQL cptData;
public ImmunizationForm() {
this(null, null, SessionUtils.getInstance(), null);
}
public ImmunizationForm(ImmunizationController ic, CPTCodeMySQL cptData, SessionUtils sessionUtils, DataSource ds) {
this.sessionUtils = (sessionUtils == null) ? SessionUtils.getInstance() : sessionUtils;
try {
if (ds == null) {
this.cptData = (cptData == null) ? new CPTCodeMySQL() : cptData;
controller = (ic == null) ? new ImmunizationController() : ic;
} else {
this.cptData = (cptData == null) ? new CPTCodeMySQL(ds) : cptData;
controller = (ic == null) ? new ImmunizationController(ds) : ic;
}
clearFields();
} catch (Exception e) {
this.sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Immunization Controller Error",
"Immunization Controller Error", null);
}
}
public void add(){
controller.add(immunization);
clearFields();
}
public void edit(){
controller.edit(immunization);
clearFields();
}
public void remove(String id){
controller.remove(Long.parseLong(id));
clearFields();
}
public List<Immunization> getImmunizationsByOfficeVisit(String ovID){
List<Immunization> immunizations = Collections.emptyList();
try {
immunizations = controller.getImmunizationsByOfficeVisit(ovID);
} catch (DBException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Immunization Controller Error", "Immunization Controller Error",
null);
}
return immunizations;
}
public Immunization getImmunization(){
return immunization;
}
public void setImmunization(Immunization i){
immunization = i;
}
public String getCodeName(String codeString){
return controller.getCodeName(codeString);
}
public List<CPTCode> getCPTCodes(){
try {
return cptData.getAll();
} catch (SQLException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "CPT Code retrival error", "CPT Code retrival error",
null);
}
return Collections.emptyList();
}
public void fillInput(String immunizationID, CPTCode code){
immunization.setCptCode(code);
immunization.setId(Long.parseLong(immunizationID));
}
private void clearFields() {
immunization = new Immunization(0, sessionUtils.getCurrentOfficeVisitId(), new CPTCode());
}
}
| 3,508
| 32.419048
| 137
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/labProcedure/LabProcedureController.java
|
package edu.ncsu.csc.itrust.controller.labProcedure;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.ValidationFormat;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedure;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedure.LabProcedureStatus;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedureData;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedureMySQL;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name = "lab_procedure_controller")
@SessionScoped
public class LabProcedureController extends iTrustController {
private static final String INVALID_LAB_PROCEDURE = "Invalid lab procedure";
private LabProcedureData labProcedureData;
public LabProcedureController() {
super();
try {
labProcedureData = new LabProcedureMySQL();
} catch (DBException e) {
e.printStackTrace();
}
}
/**
* Constructor injection, intended only for unit testing purposes.
*
* @param ds
* The injected DataSource dependency
*/
public LabProcedureController(DataSource ds) {
super();
labProcedureData = new LabProcedureMySQL(ds);
}
/**
* Setter injection for lab procedure data. ONLY use for unit testing
* purposes.
*/
public void setLabProcedureData(LabProcedureData data) {
this.labProcedureData = data;
}
/**
* Adds a lab procedure.
*
* @param procedure
* The lab procedure to add
*/
public void add(LabProcedure procedure) {
boolean successfullyAdded = false;
// Only the HCP role can add LabProcedures
String role = getSessionUtils().getSessionUserRole();
if (role == null || !role.equals("hcp")) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid user authentication",
"Only HCPs can add Lab Procedures", null);
return;
}
try {
procedure.setHcpMID(Long.parseLong(getSessionUtils().getSessionLoggedInMID()));
successfullyAdded = labProcedureData.add(procedure);
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_LAB_PROCEDURE, e.getExtendedMessage(), null);
} catch (NumberFormatException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Couldn't add lab procedure", "Couldn't parse HCP MID",
null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_LAB_PROCEDURE, INVALID_LAB_PROCEDURE, null);
}
if (successfullyAdded) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Lab Procedure Successfully Updated",
"Lab Procedure Successfully Updated", null);
if (procedure != null) {
logTransaction(TransactionType.LAB_RESULTS_CREATE, procedure.getLabProcedureCode());
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.LAB_PROCEDURE_ADD, ovid == null ? null : ovid.toString());
}
}
}
/**
* Updates a lab procedure. Prints FacesContext info message when
* successfully updated, error message when the update fails.
*
* @param procedure
* The lab procedure to update
*/
public void edit(LabProcedure procedure) {
boolean successfullyUpdated = false;
try {
successfullyUpdated = labProcedureData.update(procedure);
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_LAB_PROCEDURE, e.getExtendedMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_LAB_PROCEDURE, INVALID_LAB_PROCEDURE, null);
}
if (successfullyUpdated) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Lab Procedure Successfully Updated",
"Lab Procedure Successfully Updated", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.LAB_PROCEDURE_EDIT, ovid == null ? null : ovid.toString());
}
}
/**
* Removes lab procedure from the system. Prints FacesContext info message
* when successfully removed, error message when the removal fails.
*
* @param labProcedureID
* The ID of the lab procedure to remove.
*/
public void remove(String labProcedureID) {
boolean successfullyRemoved = false;
long id = -1;
if (labProcedureID != null) {
try {
id = Long.parseLong(labProcedureID);
successfullyRemoved = labProcedureData.removeLabProcedure(id);
} catch (NumberFormatException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Could not remove lab procedure",
"Failed to parse lab procedure ID", null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Could not remove lab procedure",
"Could not remove lab procedure", null);
}
}
if (successfullyRemoved) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Lab procedure successfully removed",
"Lab procedure successfully removed", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.LAB_PROCEDURE_REMOVE, ovid == null ? null : ovid.toString());
}
}
public LabProcedure getLabProcedureByID(String labProcedureID) {
long id = -1;
try {
id = Long.parseLong(labProcedureID);
return labProcedureData.getByID(id);
} catch (NumberFormatException ne) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Lab Procedure",
"Unable to Retrieve Lab Procedure", null);
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Lab Procedure",
"Unable to Retrieve Lab Procedure", null);
}
return null;
}
/**
* Returns lab procedures with given office visit ID, or empty list if no
* such procedures exist.
*/
public List<LabProcedure> getLabProceduresByOfficeVisit(String officeVisitID) throws DBException {
List<LabProcedure> procedures = Collections.emptyList();
long mid = -1;
if ((officeVisitID != null) && ValidationFormat.NPMID.getRegex().matcher(officeVisitID).matches()) {
mid = Long.parseLong(officeVisitID);
try {
procedures = labProcedureData.getLabProceduresByOfficeVisit(mid).stream().sorted((o1, o2) -> {
return (o1.getPriority() == o2.getPriority()) ? o1.getUpdatedDate().compareTo(o2.getUpdatedDate())
: o1.getPriority() - o2.getPriority();
}).collect(Collectors.toList());
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Lab Procedures",
"Unable to Retrieve Lab Procedures", null);
}
}
return procedures;
}
public List<LabProcedure> getLabProceduresByLabTechnician(String technicianID) throws DBException {
List<LabProcedure> procedures = Collections.emptyList();
long mid = -1;
if ((technicianID != null) && ValidationFormat.NPMID.getRegex().matcher(technicianID).matches()) {
mid = Long.parseLong(technicianID);
try {
procedures = labProcedureData.getLabProceduresForLabTechnician(mid).stream().sorted((o1, o2) -> {
return (o1.getPriority() == o2.getPriority()) ? o1.getUpdatedDate().compareTo(o2.getUpdatedDate())
: o1.getPriority() - o2.getPriority();
}).collect(Collectors.toList());
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Lab Procedures",
"Unable to Retrieve Lab Procedures", null);
}
}
return procedures;
}
public List<LabProcedure> getPendingLabProceduresByTechnician(String technicianID) throws DBException {
return getLabProceduresByLabTechnician(technicianID).stream().filter((o) -> {
return o.getStatus().name().equals(LabProcedureStatus.PENDING.name());
}).collect(Collectors.toList());
}
public List<LabProcedure> getInTransitLabProceduresByTechnician(String technicianID) throws DBException {
return getLabProceduresByLabTechnician(technicianID).stream().filter((o) -> {
return o.getStatus().name().equals(LabProcedureStatus.IN_TRANSIT.name());
}).collect(Collectors.toList());
}
public List<LabProcedure> getReceivedLabProceduresByTechnician(String technicianID) throws DBException {
return getReceivedLabProceduresStreamByTechnician(technicianID).collect(Collectors.toList());
}
public Stream<LabProcedure> getReceivedLabProceduresStreamByTechnician(String technicianID) throws DBException {
return getLabProceduresByLabTechnician(technicianID).stream().filter((o) -> {
return o.getStatus().name().equals(LabProcedureStatus.RECEIVED.name());
});
}
public List<LabProcedure> getTestingLabProceduresByTechnician(String technicianID) throws DBException {
return getTestingLabProceduresStreamsByTechnician(technicianID).collect(Collectors.toList());
}
public Stream<LabProcedure> getTestingLabProceduresStreamsByTechnician(String technicianID) throws DBException {
return getLabProceduresByLabTechnician(technicianID).stream().filter((o) -> {
return o.getStatus().name().equals(LabProcedureStatus.TESTING.name());
});
}
public List<LabProcedure> getCompletedLabProceduresByTechnician(String technicianID) throws DBException {
return getLabProceduresByLabTechnician(technicianID).stream().filter((o) -> {
return o.getStatus().name().equals(LabProcedureStatus.COMPLETED.name());
}).collect(Collectors.toList());
}
public List<LabProcedure> getCompletedLabProceduresByOfficeVisit(String officeVisitID) throws DBException {
return getLabProceduresByOfficeVisit(officeVisitID).stream().filter((o) -> {
return o.getStatus().name().equals(LabProcedureStatus.COMPLETED.name());
}).collect(Collectors.toList());
}
public List<LabProcedure> getTestingAndReceivedLabProceduresByTechnician(String technicianID) throws DBException {
// TODO
Stream<LabProcedure> testing = getTestingLabProceduresStreamsByTechnician(technicianID);
Stream<LabProcedure> received = getReceivedLabProceduresStreamByTechnician(technicianID);
return Stream.concat(testing, received).collect(Collectors.toList());
}
/**
* Returns all lab procedures for the given office visit that are not in
* completed state.
*
* @param officeVisitID
* ID of the office visit to query by
* @return Lab procedures with the given office visit ID that aren't in
* completed state
* @throws DBException
*/
public List<LabProcedure> getNonCompletedLabProceduresByOfficeVisit(String officeVisitID) throws DBException {
return getLabProceduresByOfficeVisit(officeVisitID).stream().filter((o) -> {
return !o.getStatus().name().equals(LabProcedureStatus.COMPLETED.name());
}).collect(Collectors.toList());
}
public void setLabProcedureToReceivedStatus(String labProcedureID) {
boolean successfullyUpdated = false;
try {
Long id = Long.parseLong(labProcedureID);
LabProcedure proc = labProcedureData.getByID(id);
proc.setStatus(LabProcedureStatus.RECEIVED.getID());
successfullyUpdated = labProcedureData.update(proc);
updateStatusForReceivedList(proc.getLabTechnicianID().toString());
if (successfullyUpdated) {
logTransaction(TransactionType.LAB_RESULTS_RECEIVED, proc.getLabProcedureCode());
printFacesMessage(FacesMessage.SEVERITY_INFO, "Lab Procedure Successfully Updated to Received Status",
"Lab Procedure Successfully Updated to Received Status", null);
}
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_LAB_PROCEDURE, e.getExtendedMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, GENERIC_ERROR, GENERIC_ERROR, null);
}
}
/**
*
* @param technicianID
* @throws DBException
*/
public void updateStatusForReceivedList(String technicianID) throws DBException {
List<LabProcedure> received = getReceivedLabProceduresByTechnician(technicianID);
List<LabProcedure> testing = getTestingLabProceduresByTechnician(technicianID);
if (testing.size() == 0 && received.size() > 0) {
received.get(0).setStatus(LabProcedureStatus.TESTING.getID());
edit(received.get(0));
}
}
public void updateReceivedQueue(){
}
/**
* Updates the status of the given lab procedure to pending and sets the
* next received lab procedure to testing status.
*
* @param labProcedure
* The lab procedure to update to pending
* @throws DBException
*/
public void recordResults(LabProcedure labProcedure) throws DBException {
labProcedure.setStatus(LabProcedureStatus.PENDING.getID());
edit(labProcedure);
updateStatusForReceivedList(labProcedure.getLabTechnicianID().toString());
}
/**
* Logs that each lab procedure for the given office visit was viewed by the
* logged in MID.
*/
public void logViewLabProcedure() {
try {
Long ovID = getSessionUtils().getCurrentOfficeVisitId();
if (ovID == null) { // Only log if an office visit has been selected
return;
}
List<LabProcedure> procsByOfficeVisit = getLabProceduresByOfficeVisit(ovID.toString());
for (LabProcedure proc : procsByOfficeVisit) {
logTransaction(TransactionType.LAB_RESULTS_VIEW, proc.getLabProcedureCode());
}
} catch (DBException e) {
}
}
public void logLabTechnicianViewLabProcedureQueue() {
logTransaction(TransactionType.LAB_RESULTS_VIEW_QUEUE, getSessionUtils().getSessionLoggedInMIDLong(), null,
null);
}
}
| 13,410
| 37.537356
| 115
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/labProcedure/LabProcedureForm.java
|
package edu.ncsu.csc.itrust.controller.labProcedure;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.NavigationController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedure;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedure.LabProcedureStatus;
import edu.ncsu.csc.itrust.model.loinccode.LOINCCode;
import edu.ncsu.csc.itrust.model.loinccode.LOINCCodeData;
import edu.ncsu.csc.itrust.model.loinccode.LOINCCodeMySQL;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
import edu.ncsu.csc.itrust.webutils.SessionUtils;
@ManagedBean(name = "lab_procedure_form")
@ViewScoped
public class LabProcedureForm {
private LabProcedureController controller;
private LabProcedure labProcedure;
private LOINCCodeData loincData;
private SessionUtils sessionUtils;
public LabProcedureForm() {
this(null, null, SessionUtils.getInstance(), null);
}
public LabProcedureForm(LabProcedureController ovc, LOINCCodeData ldata, SessionUtils sessionUtils, DataSource ds) {
this.sessionUtils = (sessionUtils == null) ? SessionUtils.getInstance() : sessionUtils;
try {
if (ds == null) {
loincData = (ldata == null) ? new LOINCCodeMySQL() : ldata;
controller = (ovc == null) ? new LabProcedureController() : ovc;
} else {
loincData = (ldata == null) ? new LOINCCodeMySQL(ds) : ldata;
controller = (ovc == null) ? new LabProcedureController(ds) : ovc;
}
labProcedure = getSelectedLabProcedure();
if (labProcedure == null) {
labProcedure = new LabProcedure();
Long ovid = sessionUtils.getCurrentOfficeVisitId();
labProcedure.setOfficeVisitID(ovid);
labProcedure.setStatus(LabProcedureStatus.IN_TRANSIT.getID());
}
} catch (Exception e) {
this.sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Lab Procedure Controller Error",
"Lab Procedure Controller Error", null);
}
}
public LabProcedure getSelectedLabProcedure() {
String id = sessionUtils.getRequestParameter("id");
if (id == null) {
return null;
}
return controller.getLabProcedureByID(id);
}
public void submitNewLabProcedure() {
controller.add(labProcedure);
try {
NavigationController.officeVisitInfo();
} catch (IOException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Couldn't redirect", "Couldn't redirect", null);
}
}
/**
* Removes lab procedure with given ID. Logs the removal transaction. Prints error message if removal fails.
* @param id ID of the lab procedure to remove
*/
public void removeLabProcedure(Long id) {
if (id == null) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Couldn't remove lab procedure",
"Invalid Lab Procedure ID specified", null);
return;
}
LabProcedure toRemove = controller.getLabProcedureByID(id.toString());
if(toRemove == null) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Couldn't remove lab procedure",
"No lab procedure for that ID", null);
return;
}
String code = toRemove.getLabProcedureCode();
controller.remove(id.toString());
controller.logTransaction(TransactionType.LAB_RESULTS_REMOVE, code);
}
/**
* Called when user clicks on the submit button in ReassignTechnician.xhtml.
* Takes data from form and sends to LabProcedureControllerLLoader.java for
* storage and validation
*/
public void submitReassignment() {
controller.edit(labProcedure);
controller.logTransaction(TransactionType.LAB_RESULTS_REASSIGN, labProcedure.getLabProcedureCode());
}
public void addCommentary(String labProcedureID) {
String commentary = "Reviewed by HCP";
if (sessionUtils.getCurrentFacesContext() != null) {
Map<String, String> map = sessionUtils.getCurrentFacesContext().getExternalContext()
.getRequestParameterMap();
List<String> key = map.keySet().stream().filter(k -> {
return k.matches("\\w+:\\w+:\\w+");
}).collect(Collectors.toList());
if (key.size() > 0) {
commentary = map.get(key.get(0));
}
}
LabProcedure proc = controller.getLabProcedureByID(labProcedureID);
proc.setCommentary(commentary);
long status = LabProcedure.LabProcedureStatus.COMPLETED.getID();
proc.setStatus(status);
controller.edit(proc);
controller.logTransaction(TransactionType.LAB_RESULTS_ADD_COMMENTARY, proc.getLabProcedureCode());
}
public boolean isLabProcedureCreated() {
Long labProcedureID = labProcedure.getLabProcedureID();
return labProcedureID != null && labProcedureID > 0;
}
public boolean isReassignable(String idStr) {
try {
Long.parseLong(idStr);
} catch (NumberFormatException e) {
return false;
}
LabProcedure proc = controller.getLabProcedureByID(idStr);
LabProcedureStatus status = proc.getStatus();
boolean isInTransit = status == LabProcedureStatus.IN_TRANSIT;
boolean isReceived = status == LabProcedureStatus.RECEIVED;
boolean result = isInTransit || isReceived;
return result;
}
public boolean isRemovable(String idStr) {
try {
Long.parseLong(idStr);
} catch (NumberFormatException e) {
return false;
}
LabProcedure proc = controller.getLabProcedureByID(idStr);
LabProcedureStatus status = proc.getStatus();
boolean isInTransit = status == LabProcedureStatus.IN_TRANSIT;
boolean isReceived = status == LabProcedureStatus.RECEIVED;
boolean result = isInTransit || isReceived;
return result;
}
public boolean isCommentable(String idStr) {
try {
Long.parseLong(idStr);
} catch (NumberFormatException e) {
return false;
}
LabProcedure proc = controller.getLabProcedureByID(idStr);
LabProcedureStatus status = proc.getStatus();
boolean result = status == LabProcedureStatus.PENDING;
return result;
}
/**
* Upon recording results the lab procedure is updated to pending and
* results are submitted
*/
public void recordResults() {
try {
controller.recordResults(labProcedure);
} catch (DBException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Lab Procedure Controller Error",
"Lab Procedure Controller Error", null);
}
controller.logTransaction(TransactionType.LAB_RESULTS_RECORD, labProcedure.getLabProcedureCode());
}
public void updateToReceived(String labProcedureID) {
controller.setLabProcedureToReceivedStatus(labProcedureID);
}
public LabProcedure getLabProcedure() {
return labProcedure;
}
public List<LOINCCode> getLOINCCodes() {
try {
return loincData.getAll();
} catch (DBException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "LOINC retrival error", "LOINC retrival error",
null);
}
return Collections.emptyList();
}
}
| 6,932
| 31.549296
| 117
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/labtechnician/LabTechnicianController.java
|
package edu.ncsu.csc.itrust.controller.labtechnician;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedure;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedureData;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedureMySQL;
import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean;
import edu.ncsu.csc.itrust.model.old.dao.DAOFactory;
import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO;
@ManagedBean(name = "lab_technician_controller")
@SessionScoped
public class LabTechnicianController {
private LabProcedureData ldata;
private PersonnelDAO pdao;
/**
* Default constructor.
*
* @throws DBException
* when error in database
*/
public LabTechnicianController() throws DBException {
ldata = new LabProcedureMySQL();
pdao = DAOFactory.getProductionInstance().getPersonnelDAO();
}
/**
* Constructor for testing purposes.
*
* @param ds
* data source
* @param personnelDAO
* personnel DAO created from testing instance DAO factory
*/
public LabTechnicianController(DataSource ds, PersonnelDAO personnelDAO) {
ldata = new LabProcedureMySQL(ds);
pdao = personnelDAO;
}
public List<PersonnelBean> getLabTechnicianList() throws DBException {
return pdao.getLabTechs();
}
public List<Pair<String, Long>> getLabTechnicianStatusMID() throws DBException {
return getLabTechnicianList().stream().map((lt) -> {
try {
List<LabProcedure> labProcedures = ldata.getLabProceduresForLabTechnician(lt.getMID());
Map<Integer, Long> priorityQueueCounter = labProcedures.stream()
.filter((proc)->{
return proc.getStatus() == LabProcedure.LabProcedureStatus.PENDING
|| proc.getStatus() == LabProcedure.LabProcedureStatus.IN_TRANSIT
|| proc.getStatus() == LabProcedure.LabProcedureStatus.TESTING;
})
.collect(Collectors.groupingBy(LabProcedure::getPriority, Collectors.counting()));
String display = String.format("%s, %s (Specialty: %s | Queue Status - High: %d, Medium: %d, Low: %d)",
lt.getLastName(), lt.getFirstName(), lt.getSpecialty(),
priorityQueueCounter.getOrDefault(LabProcedure.PRIORITY_HIGH, 0L),
priorityQueueCounter.getOrDefault(LabProcedure.PRIORITY_MEDIUM, 0L),
priorityQueueCounter.getOrDefault(LabProcedure.PRIORITY_LOW, 0L));
return new ImmutablePair<>(display, lt.getMID());
} catch (DBException e) {
return null;
}
}).filter((pair) -> {
return pair != null;
}).collect(Collectors.toList());
}
}
| 2,847
| 34.160494
| 107
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/loinccode/LoincCodeController.java
|
package edu.ncsu.csc.itrust.controller.loinccode;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.loinccode.LOINCCode;
import edu.ncsu.csc.itrust.model.loinccode.LOINCCodeMySQL;
@ManagedBean(name = "loinccode_controller")
@SessionScoped
public class LoincCodeController extends iTrustController {
private static final String INVALID_CODE = "Invalid LOINC Code";
private static final String UNKNOWN_ERROR = "Unknown error";
private static final String NONEXISTENT_CODE = "Code does not exist";
private static final String DUPLICATE_CODE = "Cannot add duplicate code";
private LOINCCodeMySQL sql;
//private SessionUtils sessionUtils;
public LoincCodeController() {
try {
sql = new LOINCCodeMySQL();
} catch (DBException e) {
sql = null;
}
}
/**
* Constructor injection, intended only for unit testing purposes.
*
* @param ds
* The injected DataSource dependency
*/
public LoincCodeController(DataSource ds) {
sql = new LOINCCodeMySQL(ds);
}
/**
* Setter injection for lab procedure data. ONLY use for unit testing
* purposes.
*/
public void setSQLData(LOINCCodeMySQL data) {
this.sql = data;
}
public void add(LOINCCode code) {
try {
if (!sql.add(code)){
printFacesMessage(FacesMessage.SEVERITY_ERROR, DUPLICATE_CODE, DUPLICATE_CODE, null);
}
} catch (FormValidationException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_CODE, e.getErrorList().toString(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public void edit(LOINCCode code) {
try {
if (!sql.update(code)){
printFacesMessage(FacesMessage.SEVERITY_ERROR, NONEXISTENT_CODE, NONEXISTENT_CODE, null);
}
} catch (FormValidationException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_CODE, e.getErrorList().toString(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public void remove(String loincCodeID) {
try {
if (!sql.delete(new LOINCCode(loincCodeID, "", ""))){
printFacesMessage(FacesMessage.SEVERITY_ERROR, NONEXISTENT_CODE, NONEXISTENT_CODE, null);
}
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public LOINCCode getCodeByID(String loincCodeID) {
try {
return sql.getByCode(loincCodeID);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
return null;
}
public List<LOINCCode> getCodesWithFilter(String filterString){
try {
return sql.getCodesWithFilter(filterString);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
return new ArrayList<>();
}
}
| 3,485
| 31.579439
| 108
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/loinccode/LoincCodeForm.java
|
package edu.ncsu.csc.itrust.controller.loinccode;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import edu.ncsu.csc.itrust.controller.loinccode.LoincCodeController;
import edu.ncsu.csc.itrust.model.loinccode.LOINCCode;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name = "loinc_code_form")
@ViewScoped
public class LoincCodeForm {
private LoincCodeController controller;
private LOINCCode loincCode;
// Input Fields
private String code;
private String component;
private String kindOfProperty;
private String timeAspect;
private String system;
private String scaleType;
private String methodType;
private String search;
private boolean displayCodes;
public LoincCodeForm() {
this(null);
}
public LoincCodeForm(LoincCodeController loincCodeController) {
controller = (loincCodeController == null) ? new LoincCodeController() : loincCodeController;
search = "";
setDisplayCodes(false);
}
public void add() {
setLoincCode(new LOINCCode(code, component, kindOfProperty, timeAspect, system, scaleType, methodType));
controller.add(loincCode);
controller.logTransaction(TransactionType.LOINC_CODE_ADD, loincCode.getCode());
code = "";
component = "";
kindOfProperty = "";
timeAspect = "";
system = "";
scaleType = "";
methodType = "";
}
public void update() {
setLoincCode(new LOINCCode(code, component, kindOfProperty, timeAspect, system, scaleType, methodType));
controller.edit(loincCode);
controller.logTransaction(TransactionType.LOINC_CODE_EDIT, loincCode.getCode());
code = "";
component = "";
kindOfProperty = "";
timeAspect = "";
system = "";
scaleType = "";
methodType = "";
}
public void delete() {
setLoincCode(new LOINCCode(code, component, kindOfProperty, timeAspect, system, scaleType, methodType));
controller.remove(code);
code = "";
component = "";
kindOfProperty = "";
timeAspect = "";
system = "";
scaleType = "";
methodType = "";
}
public void fillInput(String code, String component, String kindOfProperty, String timeAspect, String system,
String scaleType, String methodType) {
this.code = code;
this.component = component;
this.kindOfProperty = kindOfProperty;
this.timeAspect = timeAspect;
this.system = system;
this.scaleType = scaleType;
this.methodType = methodType;
}
public List<LOINCCode> getCodesWithFilter() {
return controller.getCodesWithFilter(search);
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
public boolean getDisplayCodes() {
return displayCodes;
}
/**
* Sets whether or not search results matching the given search string
* should be rendered. If displayCodes is true, this logs the view action
* for all codes matching the search filter.
*
* @param displayCodes
*/
public void setDisplayCodes(boolean displayCodes) {
this.displayCodes = displayCodes;
if (this.displayCodes) {
logViewLoincCodes();
}
}
/**
* Logs a view action for each LOINC code matching the current search query.
* Only logs if search query is non-empty.
*/
private void logViewLoincCodes() {
if (search != null && !search.equals("")) {
for (LOINCCode code : controller.getCodesWithFilter(search)) {
controller.logTransaction(TransactionType.LOINC_CODE_VIEW, code.getCode());
}
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public LOINCCode getLoincCode() {
return loincCode;
}
public void setLoincCode(LOINCCode loincCode) {
this.loincCode = loincCode;
}
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getTimeAspect() {
return timeAspect;
}
public void setTimeAspect(String timeAspect) {
this.timeAspect = timeAspect;
}
public String getKindOfProperty() {
return kindOfProperty;
}
public void setKindOfProperty(String kindOfProperty) {
this.kindOfProperty = kindOfProperty;
}
public String getSystem() {
return system;
}
public void setSystem(String system) {
this.system = system;
}
public String getScaleType() {
return scaleType;
}
public void setScaleType(String scaleType) {
this.scaleType = scaleType;
}
public String getMethodType() {
return methodType;
}
public void setMethodType(String methodType) {
this.methodType = methodType;
}
}
| 4,513
| 22.030612
| 110
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/medicalProcedure/MedicalProcedureController.java
|
package edu.ncsu.csc.itrust.controller.medicalProcedure;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.medicalProcedure.MedicalProcedure;
import edu.ncsu.csc.itrust.model.medicalProcedure.MedicalProcedureMySQL;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name = "medical_procedure_controller")
@SessionScoped
public class MedicalProcedureController extends iTrustController {
private static final String INVALID_MEDICAL_PROCEDURE = "Invalid Medical Procedure";
MedicalProcedureMySQL sql;
public MedicalProcedureController() throws DBException{
super();
sql = new MedicalProcedureMySQL();
}
public MedicalProcedureController(DataSource ds){
super();
sql = new MedicalProcedureMySQL(ds);
}
public void add(MedicalProcedure mp){
try {
if (sql.add(mp)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Medical Procedure successfully created",
"Medical Procedure successfully created", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.PROCEDURE_ADD, ovid == null ? null : ovid.toString());
} else {
throw new Exception();
}
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_MEDICAL_PROCEDURE, e.getMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_MEDICAL_PROCEDURE, INVALID_MEDICAL_PROCEDURE, null);
}
}
public void edit(MedicalProcedure mp){
try {
if (sql.update(mp)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Medical Procedure successfully updated",
"Medical Procedure successfully updated", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.PROCEDURE_EDIT, ovid == null ? null : ovid.toString());
} else {
throw new Exception();
}
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_MEDICAL_PROCEDURE, e.getMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_MEDICAL_PROCEDURE, INVALID_MEDICAL_PROCEDURE, null);
}
}
public void remove(long mpID) {
try {
if (sql.remove(mpID)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Medical Procedure successfully deleted",
"Medical Procedure successfully deleted", null);
Long ovid = getSessionUtils().getCurrentOfficeVisitId();
logTransaction(TransactionType.PROCEDURE_REMOVE, ovid == null ? null : ovid.toString());
} else {
throw new Exception();
}
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_MEDICAL_PROCEDURE, e.getMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_MEDICAL_PROCEDURE, INVALID_MEDICAL_PROCEDURE, null);
}
}
public List<MedicalProcedure> getMedicalProceduresByOfficeVisit(String officeVisitID){
List<MedicalProcedure> medicalProcedures = Collections.emptyList();
long ovID = -1;
if ( officeVisitID != null ) {
ovID = Long.parseLong(officeVisitID);
try {
medicalProcedures = sql.getMedicalProceduresForOfficeVisit(ovID);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Medical Procedures", "Unable to Retrieve Medical Procedures", null);
}
}
return medicalProcedures;
}
public String getCodeName(String codeString){
String codeName = "";
try {
codeName = sql.getCodeName(codeString);
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Medical Procedure", e.getMessage(), null);
}
return codeName;
}
public void setSQL(MedicalProcedureMySQL newsql) {
sql = newsql;
}
}
| 4,690
| 39.791304
| 151
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/medicalProcedure/MedicalProcedureForm.java
|
package edu.ncsu.csc.itrust.controller.medicalProcedure;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.model.cptcode.CPTCode;
import edu.ncsu.csc.itrust.model.cptcode.CPTCodeMySQL;
import edu.ncsu.csc.itrust.model.medicalProcedure.MedicalProcedure;
import edu.ncsu.csc.itrust.webutils.SessionUtils;
@ManagedBean(name = "medical_procedure_form")
@ViewScoped
public class MedicalProcedureForm {
private MedicalProcedure medicalProcedure;
private MedicalProcedureController controller;
private SessionUtils sessionUtils;
private CPTCodeMySQL cptData;
public MedicalProcedureForm(){
this(null, null, SessionUtils.getInstance(), null);
}
public MedicalProcedureForm(MedicalProcedureController mpc, CPTCodeMySQL cptData, SessionUtils sessionUtils, DataSource ds){
this.sessionUtils = (sessionUtils == null) ? SessionUtils.getInstance() : sessionUtils;
try {
if (ds == null) {
this.cptData = (cptData == null) ? new CPTCodeMySQL() : cptData;
controller = (mpc == null) ? new MedicalProcedureController() : mpc;
} else {
this.cptData = (cptData == null) ? new CPTCodeMySQL(ds) : cptData;
controller = (mpc == null) ? new MedicalProcedureController(ds) : mpc;
}
clearFields();
} catch (Exception e) {
this.sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Medical Procedure Controller Error",
"Medical Procedure Controller Error", null);
}
}
public void add(){
controller.add(medicalProcedure);
clearFields();
}
public void edit(){
controller.edit(medicalProcedure);
clearFields();
}
public void remove(String id){
controller.remove(Long.parseLong(id));
clearFields();
}
public List<MedicalProcedure> getMedicalProceduresByOfficeVisit(String ovID){
List<MedicalProcedure> medicalProcedures = Collections.emptyList();
medicalProcedures = controller.getMedicalProceduresByOfficeVisit(ovID);
return medicalProcedures;
}
public MedicalProcedure getMedicalProcedure(){
return medicalProcedure;
}
public void setMedicalProcedure(MedicalProcedure mp){
medicalProcedure = mp;
}
public String getCodeName(String codeString){
return controller.getCodeName(codeString);
}
public List<CPTCode> getCPTCodes(){
try {
return cptData.getAll();
} catch (SQLException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "CPT Code retrival error", "CPT Code retrival error",
null);
}
return Collections.emptyList();
}
public void fillInput(String medicalProcedureID, CPTCode code){
medicalProcedure.setCptCode(code);
medicalProcedure.setId(Long.parseLong(medicalProcedureID));
}
private void clearFields() {
medicalProcedure = new MedicalProcedure();
medicalProcedure.setOfficeVisitId(sessionUtils.getCurrentOfficeVisitId());
}
}
| 3,410
| 33.11
| 128
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/ndcode/NDCCodeController.java
|
package edu.ncsu.csc.itrust.controller.ndcode;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.ndcode.NDCCode;
import edu.ncsu.csc.itrust.model.ndcode.NDCCodeMySQL;
@ManagedBean(name = "ndccode_controller")
@SessionScoped
public class NDCCodeController extends iTrustController {
private static final String INVALID_CODE = "Invalid NDC Code";
private static final String UNKNOWN_ERROR = "Unknown error";
private static final String NONEXISTENT_CODE = "Code does not exist";
private static final String DUPLICATE_CODE = "Cannot add duplicate code";
private NDCCodeMySQL sql;
public NDCCodeController() {
try {
sql = new NDCCodeMySQL();
} catch (DBException e) {
sql = null;
}
}
/**
* Constructor injection, intended only for unit testing purposes.
*
* @param ds
* The injected DataSource dependency
*/
public NDCCodeController(DataSource ds) {
sql = new NDCCodeMySQL(ds);
}
/**
* Setter injection for lab procedure data. ONLY use for unit testing
* purposes.
*/
public void setSQLData(NDCCodeMySQL data) {
this.sql = data;
}
/**
* Adds an ndcCode.
*
* @param code
* The code to add
*/
public void add(NDCCode code) {
try {
if (!sql.add(code)){
printFacesMessage(FacesMessage.SEVERITY_ERROR, DUPLICATE_CODE, DUPLICATE_CODE, null);
}
} catch (FormValidationException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_CODE, e.getErrorList().toString(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
/**
* Updates an NDCCode. Prints FacesContext info message when
* successfully updated, error message when the update fails.
*
* @param code
* The code to add
*/
public void edit(NDCCode code) {
try {
if (!sql.update(code)){
printFacesMessage(FacesMessage.SEVERITY_ERROR, NONEXISTENT_CODE, NONEXISTENT_CODE, null);
}
} catch (FormValidationException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_CODE, e.getErrorList().toString(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public void remove(String ndcCodeID) {
try {
if (!sql.delete(new NDCCode(ndcCodeID, ""))){
printFacesMessage(FacesMessage.SEVERITY_ERROR, NONEXISTENT_CODE, NONEXISTENT_CODE, null);
}
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
}
public NDCCode getCodeByID(String ndcCodeID) {
try {
return sql.getByCode(ndcCodeID);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
return null;
}
public List<NDCCode> getCodesWithFilter(String filterString){
try {
return sql.getCodesWithFilter(filterString);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, UNKNOWN_ERROR, UNKNOWN_ERROR, null);
}
return new ArrayList<>();
}
}
| 3,664
| 29.798319
| 108
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/ndcode/NDCCodeForm.java
|
package edu.ncsu.csc.itrust.controller.ndcode;
import java.util.Collections;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import edu.ncsu.csc.itrust.model.ndcode.NDCCode;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name = "ndc_code_form")
@ViewScoped
public class NDCCodeForm {
private NDCCodeController controller;
private NDCCode ndcCode;
private String code;
private String description;
private String search;
private boolean displayCodes;
public NDCCodeForm() {
this(null);
}
public NDCCodeForm(NDCCodeController cptCodeController) {
controller = (cptCodeController == null) ? new NDCCodeController() : cptCodeController;
search = "";
setDisplayCodes(false);
}
public void add() {
setNDCCode(new NDCCode(code, description));
controller.add(ndcCode);
controller.logTransaction(TransactionType.DRUG_CODE_ADD, code);
code = "";
description = "";
}
public void update() {
setNDCCode(new NDCCode(code, description));
controller.edit(ndcCode);
controller.logTransaction(TransactionType.DRUG_CODE_EDIT, code);
code = "";
description = "";
}
public void delete() {
setNDCCode(new NDCCode(code, description));
controller.remove(code);
code = "";
description = "";
}
public List<NDCCode> getCodesWithFilter() {
List<NDCCode> codes = Collections.emptyList();
if(!"".equals(search)) { // Only search if there's a search query
codes = controller.getCodesWithFilter(search);
}
return codes;
}
public void fillInput(String code, String description) {
this.code = code;
this.description = description;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
public NDCCode getNDCCode() {
return ndcCode;
}
public void setNDCCode(NDCCode ndcCode) {
this.ndcCode = ndcCode;
}
public boolean getDisplayCodes() {
return displayCodes;
}
/**
* Sets whether or not search results matching the given search string
* should be rendered. If displayCodes is true, this logs the view action
* for all codes matching the search filter.
*
* @param displayCodes
*/
public void setDisplayCodes(boolean displayCodes) {
this.displayCodes = displayCodes;
// Log if displaying search results
if (this.displayCodes) {
logViewDrugCodes();
}
}
/**
* Logs a view action for each drug code matching the current search query.
* Only logs if search query is non-empty.
*/
private void logViewDrugCodes() {
if(!"".equals(search)) {
for (NDCCode code : controller.getCodesWithFilter(search)) {
controller.logTransaction(TransactionType.DRUG_CODE_VIEW, code.getCode());
}
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 3,344
| 23.595588
| 95
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/officeVisit/OfficeVisitController.java
|
package edu.ncsu.csc.itrust.controller.officeVisit;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.NavigationController;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.ValidationFormat;
import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit;
import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitData;
import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitMySQL;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
import edu.ncsu.csc.itrust.webutils.SessionUtils;
@ManagedBean(name = "office_visit_controller")
@SessionScoped
public class OfficeVisitController extends iTrustController {
/**
* The cut off age for being considered a baby.
*/
private static final int PATIENT_BABY_AGE = 3;
/**
* The cut off age for being considered a child.
*/
private static final int PATIENT_CHILD_AGE = 12;
/**
* Constant for the error message to be displayed if the Office Visit is
* invalid.
*/
private static final String OFFICE_VISIT_CANNOT_BE_UPDATED = "Invalid Office Visit";
/**
* Constant for the message to be displayed if the office visit was
* unsuccessfully updated
*/
private static final String OFFICE_VISIT_CANNOT_BE_CREATED = "Office Visit Cannot Be Updated";
/**
* Constant for the message to be displayed if the office visit was
* successfully created
*/
private static final String OFFICE_VISIT_SUCCESSFULLY_CREATED = "Office Visit Successfully Created";
/**
* Constant for the message to be displayed if the office visit was
* successfully updated
*/
private static final String OFFICE_VISIT_SUCCESSFULLY_UPDATED = "Office Visit Successfully Updated";
private OfficeVisitData officeVisitData;
private SessionUtils sessionUtils;
public OfficeVisitController() throws DBException {
officeVisitData = new OfficeVisitMySQL();
sessionUtils = SessionUtils.getInstance();
}
/**
* For testing purposes
*
* @param ds
* DataSource
* @param sessionUtils
* SessionUtils instance
*/
public OfficeVisitController(DataSource ds, SessionUtils sessionUtils) {
officeVisitData = new OfficeVisitMySQL(ds);
this.sessionUtils = sessionUtils;
}
/**
* For testing purposes
*
* @param ds
* DataSource
*/
public OfficeVisitController(DataSource ds) {
officeVisitData = new OfficeVisitMySQL(ds);
sessionUtils = SessionUtils.getInstance();
}
/**
* Adding office visit used in testing.
*
* @param ov
* Office visit
* @return true if successfully added, false if otherwise
*/
public boolean addReturnResult(OfficeVisit ov) {
boolean res = false;
try {
res = officeVisitData.add(ov);
} catch (Exception e) {
// do nothing
}
if (res) {
logEditBasicHealthInformation();
}
return res;
}
/**
* Add office visit to the database and return the generated VisitID.
*
* @param ov
* Office visit to add to the database
* @return VisitID generated from the database insertion, -1 if nothing was
* generated
* @throws DBException
* if error occurred in inserting office visit
*/
public long addReturnGeneratedId(OfficeVisit ov) {
long generatedId = -1;
try {
generatedId = officeVisitData.addReturnGeneratedId(ov);
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_INFO, OFFICE_VISIT_CANNOT_BE_CREATED, e.getExtendedMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_INFO, OFFICE_VISIT_CANNOT_BE_CREATED,
OFFICE_VISIT_CANNOT_BE_CREATED, null);
}
if (generatedId >= 0) {
printFacesMessage(FacesMessage.SEVERITY_INFO, OFFICE_VISIT_SUCCESSFULLY_CREATED,
OFFICE_VISIT_SUCCESSFULLY_CREATED, null);
logEditBasicHealthInformation();
}
return generatedId;
}
/**
* Sends a FacesMessage for FacesContext to display.
*
* @param severity
* severity of the message
* @param summary
* localized summary message text
* @param detail
* localized detail message text
* @param clientId
* The client identifier with which this message is associated
* (if any)
*/
public void printFacesMessage(Severity severity, String summary, String detail, String clientId) {
FacesContext ctx = FacesContext.getCurrentInstance();
if (ctx == null) {
return;
}
ctx.getExternalContext().getFlash().setKeepMessages(true);
ctx.addMessage(clientId, new FacesMessage(severity, summary, detail));
}
public void redirectToBaseOfficeVisit() throws IOException {
if (FacesContext.getCurrentInstance() != null) {
NavigationController.baseOfficeVisit();
}
}
public void add(OfficeVisit ov) {
boolean res = false;
try {
res = officeVisitData.add(ov);
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, OFFICE_VISIT_CANNOT_BE_CREATED, e.getExtendedMessage(),
null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, OFFICE_VISIT_CANNOT_BE_CREATED,
OFFICE_VISIT_CANNOT_BE_CREATED, null);
}
if (res) {
printFacesMessage(FacesMessage.SEVERITY_INFO, OFFICE_VISIT_SUCCESSFULLY_CREATED,
OFFICE_VISIT_SUCCESSFULLY_CREATED, null);
logEditBasicHealthInformation();
}
}
/**
* @param pid
* patient mid
* @return sorted list of office visit for the given patient
*/
public List<OfficeVisit> getOfficeVisitsForPatient(String pid) {
List<OfficeVisit> ret = Collections.emptyList();
long mid = -1;
if ((pid != null) && ValidationFormat.NPMID.getRegex().matcher(pid).matches()) {
mid = Long.parseLong(pid);
try {
ret = officeVisitData.getVisitsForPatient(mid).stream().sorted((o1, o2) -> {
return o2.getDate().compareTo(o1.getDate());
}).collect(Collectors.toList());
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Office Visits",
"Unable to Retrieve Office Visits", null);
}
}
return ret;
}
/**
* @return list of office visit sorted by date, empty list if no office
* visit exists
*/
public List<OfficeVisit> getOfficeVisitsForCurrentPatient() {
return getOfficeVisitsForPatient(sessionUtils.getCurrentPatientMID());
}
/**
* @param pid
* patient mid
* @return list of office visits when given patient was a baby, empty list
* if no office visit exists during that age range
*/
public List<OfficeVisit> getBabyOfficeVisitsForPatient(String pid) {
return getOfficeVisitsForPatient(pid).stream().filter((o) -> {
return isPatientABaby(o.getPatientMID(), o.getDate());
}).collect(Collectors.toList());
}
/**
* @return list of office visits when current patient was a baby, empty list
* if no office visit exists during that age range
*/
public List<OfficeVisit> getBabyOfficeVisitsForCurrentPatient() {
return getBabyOfficeVisitsForPatient(sessionUtils.getCurrentPatientMID());
}
/**
* @param pid
* patient mid
* @return list of office visits when given patient was a child, empty list
* if no office visit exists during that age range
*/
public List<OfficeVisit> getChildOfficeVisitsForPatient(String pid) {
return getOfficeVisitsForPatient(pid).stream().filter((o) -> {
return isPatientAChild(o.getPatientMID(), o.getDate());
}).collect(Collectors.toList());
}
/**
* @return list of office visits when current patient was a child, empty
* list if no office visit exists during that age range
*/
public List<OfficeVisit> getChildOfficeVisitsForCurrentPatient() {
return getChildOfficeVisitsForPatient(sessionUtils.getCurrentPatientMID());
}
/**
* @param pid
* patient mid
* @return list of office visits when given patient was an adult, empty list
* if no office visit exists during that age range
*/
public List<OfficeVisit> getAdultOfficeVisitsForPatient(String pid) {
return getOfficeVisitsForPatient(pid).stream().filter((o) -> {
return isPatientAnAdult(o.getPatientMID(), o.getDate());
}).collect(Collectors.toList());
}
/**
* @return list of office visits when current patient was an adult, empty
* list if no office visit exists during that age range
*/
public List<OfficeVisit> getAdultOfficeVisitsForCurrentPatient() {
return getAdultOfficeVisitsForPatient(sessionUtils.getCurrentPatientMID());
}
public OfficeVisit getVisitByID(String VisitID) {
long id = -1;
try {
id = Long.parseLong(VisitID);
} catch (NumberFormatException ne) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Office Visit",
"Unable to Retrieve Office Visit", null);
return null;
}
try {
return officeVisitData.getByID(id);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Office Visit",
"Unable to Retrieve Office Visit", null);
return null;
}
}
/**
* @return Office Visit of the selected patient in the HCP session
*/
public OfficeVisit getSelectedVisit() {
String visitID = sessionUtils.getRequestParameter("visitID");
if (visitID == null || visitID.isEmpty()) {
return null;
}
return getVisitByID(visitID);
}
/**
* @param patientID
* Patient MID
* @return true if selected patient MID has at least 1 office visit, false
* otherwise
*/
public boolean hasPatientVisited(String patientID) {
boolean ret = false;
if ((patientID != null) && (ValidationFormat.NPMID.getRegex().matcher(patientID).matches())) {
if (getOfficeVisitsForPatient(patientID).size() > 0) {
ret = true;
}
}
return ret;
}
/**
* @return true if patient selected in HCP session has at least 1 office
* visit, false if otherwise
*/
public boolean CurrentPatientHasVisited() {
return hasPatientVisited(sessionUtils.getCurrentPatientMID());
}
public void edit(OfficeVisit ov) {
boolean res = false;
try {
res = officeVisitData.update(ov);
} catch (DBException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, OFFICE_VISIT_CANNOT_BE_UPDATED, e.getExtendedMessage(),
null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, OFFICE_VISIT_CANNOT_BE_UPDATED,
OFFICE_VISIT_CANNOT_BE_UPDATED, null);
}
if (res) {
printFacesMessage(FacesMessage.SEVERITY_INFO, OFFICE_VISIT_SUCCESSFULLY_UPDATED,
OFFICE_VISIT_SUCCESSFULLY_UPDATED, null);
logEditBasicHealthInformation();
}
}
/**
* Calculate given patient's age given a day in the future.
*
* @param patientMID
* MID of the patient
* @param futureDate
* Date in the future
* @return patient's age in calendar year, or -1 if error occurred
*/
public Long calculatePatientAge(final Long patientMID, final LocalDateTime futureDate) {
Long ret = -1L;
if (futureDate == null || patientMID == null) {
return ret;
}
LocalDate patientDOB = getPatientDOB(patientMID);
if (patientDOB == null) {
return ret;
}
if (futureDate.toLocalDate().isBefore(patientDOB)) {
return ret;
}
return ChronoUnit.YEARS.between(patientDOB, futureDate);
}
/**
* Check whether patient is under 3 years of age.
*
* @param patientMID
* MID of the patient
* @param officeVisitDate
* date of the office visit
* @return true if patient is under 3 years old at the time of the office
* visit, false if otherwise
*/
public boolean isPatientABaby(final Long patientMID, final LocalDateTime officeVisitDate) {
Long age = calculatePatientAge(patientMID, officeVisitDate);
return age < PATIENT_BABY_AGE && age >= 0;
}
/**
* Check whether patient is between 3 years (inclusive) and 12 years
* (exclusive) old.
*
* @param patientMID
* MID of the patient
* @param officeVisitDate
* date of the office visit
* @return true if patient is is between 3 years (inclusive) and 12 years
* (exclusive) old, false if otherwise
*/
public boolean isPatientAChild(final Long patientMID, final LocalDateTime officeVisitDate) {
Long age = calculatePatientAge(patientMID, officeVisitDate);
return age < PATIENT_CHILD_AGE && age >= PATIENT_BABY_AGE;
}
/**
* Check whether patient is between 12 years old or older.
*
* @param patientMID
* MID of the patient
* @param officeVisitDate
* date of the office visit
* @return true if patient is is 12 years old or older, false if otherwise
*/
public boolean isPatientAnAdult(final Long patientMID, final LocalDateTime officeVisitDate) {
Long age = calculatePatientAge(patientMID, officeVisitDate);
return age >= PATIENT_CHILD_AGE;
}
/**
* @param patientMID
* The patient's MID
* @return the patient's date of birth
*/
public LocalDate getPatientDOB(final Long patientMID) {
return officeVisitData.getPatientDOB(patientMID);
}
/**
* Logs that the currently selected office visit has been viewed (if any
* office visit is selected)
*/
public void logViewOfficeVisit() {
Long id = getSessionUtils().getCurrentOfficeVisitId();
if (id != null) {
logTransaction(TransactionType.OFFICE_VISIT_VIEW, id.toString());
OfficeVisit ov = getVisitByID(Long.toString(id));
long patientMID = ov.getPatientMID();
LocalDateTime d = ov.getDate();
logTransaction(TransactionType.VIEW_BASIC_HEALTH_METRICS, "Age: " + calculatePatientAge(patientMID, d));
}
}
/**
* Logs that the current user viewed a patient's health metrics page
*/
public void logViewHealthMetrics(){
String role = sessionUtils.getSessionUserRole();
if ("hcp".equals(role)){
logTransaction(TransactionType.HCP_VIEW_BASIC_HEALTH_METRICS, "");
} else if ("patient".equals(role)){
logTransaction(TransactionType.PATIENT_VIEW_BASIC_HEALTH_METRICS, Long.parseLong(sessionUtils.getSessionLoggedInMID()), null, "");
}
}
public void logViewBasicHealthInformation() {
logTransaction(TransactionType.PATIENT_HEALTH_INFORMATION_VIEW, "");
}
/**
* Editing basic health information is synonymous with editing or adding an
* office visit, so this method should be called whenever an OV is
* added/edited.
*/
private void logEditBasicHealthInformation() {
logTransaction(TransactionType.PATIENT_HEALTH_INFORMATION_EDIT, "");
}
}
| 14,857
| 29.889813
| 139
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/officeVisit/OfficeVisitForm.java
|
package edu.ncsu.csc.itrust.controller.officeVisit;
import java.time.LocalDateTime;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import edu.ncsu.csc.itrust.model.ValidationFormat;
import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
@ManagedBean(name = "office_visit_form")
@ViewScoped
public class OfficeVisitForm {
private OfficeVisitController controller;
private OfficeVisit ov;
private Long visitID;
private Long patientMID;
private LocalDateTime date;
private String locationID;
private Long apptTypeID;
private String notes;
private Boolean sendBill;
private Float height;
private Float length;
private Float weight;
private Float headCircumference;
private String bloodPressure;
private Integer hdl;
private Integer triglyceride;
private Integer ldl;
private Integer householdSmokingStatus;
private Integer patientSmokingStatus;
public Long getVisitID() {
return visitID;
}
public void setVisitID(Long visitID) {
this.visitID = visitID;
}
public Long getPatientMID() {
return patientMID;
}
public void setPatientMID(Long patientMID) {
this.patientMID = patientMID;
}
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public String getLocationID() {
return locationID;
}
public void setLocationID(String locationID) {
this.locationID = locationID;
}
public Long getApptTypeID() {
return apptTypeID;
}
public void setApptTypeID(Long apptTypeID) {
this.apptTypeID = apptTypeID;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Boolean getSendBill() {
return sendBill;
}
public void setSendBill(Boolean sendBill) {
this.sendBill = sendBill;
}
/**
* Returns the Height recorded at the office visit.
*
* @return the Height recorded at the office visit.
*/
public Float getHeight() {
return height;
}
/**
* Sets the height recorded at the office visit.
*
* @param height
* The height recorded at the office visit
*/
public void setHeight(Float height) {
this.height = height;
}
/**
* Gets the length recorded at the office visit.
*
* @param length
* The height recorded at the office visit
*/
public Float getLength() {
return length;
}
/**
* Sets the length recorded at the office visit.
*
* @param length
* The height recorded at the office visit
*/
public void setLength(Float length) {
this.length = length;
}
/**
* Returns the weight recorded at the office visit.
*
* @return the weight recorded at the office visit.
*/
public Float getWeight() {
return weight;
}
/**
* @param weight
* the weight to set
*/
public void setWeight(Float weight) {
this.weight = weight;
}
/**
* Returns the head circumference measured at the office visit.
*
* @return the headCircumference
*/
public Float getHeadCircumference() {
return headCircumference;
}
/**
* @param headCircumference
* the headCircumference to set
*/
public void setHeadCircumference(Float headCircumference) {
this.headCircumference = headCircumference;
}
/**
* Returns the blood pressure measured at the office visit.
*
* @return the bloodPressure
*/
public String getBloodPressure() {
return bloodPressure;
}
/**
* @param bloodPressure
* the bloodPressure to set
*/
public void setBloodPressure(String bloodPressure) {
this.bloodPressure = bloodPressure;
}
/**
* Returns the HDL cholesterol level measured at the office visit.
*
* @return the hdl
*/
public Integer getHDL() {
return hdl;
}
/**
* @param hdl
* the hdl to set
*/
public void setHDL(Integer hdl) {
this.hdl = hdl;
}
/**
* Returns the triglyceride cholesterol level measured at the office visit.
*
* @return the triglyceride
*/
public Integer getTriglyceride() {
return triglyceride;
}
/**
* @param triglyceride
* the triglyceride to set
*/
public void setTriglyceride(Integer triglyceride) {
this.triglyceride = triglyceride;
}
/**
* Returns the LDL cholesterol level measured at the office visit.
*
* @return the ldl
*/
public Integer getLDL() {
return ldl;
}
/**
* @param ldl
* the ldl to set
*/
public void setLDL(Integer ldl) {
this.ldl = ldl;
}
/**
* Returns the household smoking status indicated at the office visit.
*
* @return the householdSmokingStatus
*/
public Integer getHouseholdSmokingStatus() {
return householdSmokingStatus;
}
/**
* @param householdSmokingStatus
* the householdSmokingStatus to set
*/
public void setHouseholdSmokingStatus(Integer householdSmokingStatus) {
this.householdSmokingStatus = householdSmokingStatus;
}
/**
* Returns the patient smoking status indicated at the office visit.
*
* @return the patientSmokingStatus
*/
public Integer getPatientSmokingStatus() {
return patientSmokingStatus;
}
/**
* @param patientSmokingStatus
* the patientSmokingStatus to set
*/
public void setPatientSmokingStatus(Integer patientSmokingStatus) {
this.patientSmokingStatus = patientSmokingStatus;
}
/**
* Default constructor for OfficeVisitForm.
*/
public OfficeVisitForm() {
this(null);
}
/**
* Constructor for OfficeVisitForm for testing purpses.
*/
public OfficeVisitForm(OfficeVisitController ovc) {
try {
controller = (ovc == null) ? new OfficeVisitController() : ovc;
ov = controller.getSelectedVisit();
if (ov == null) {
ov = new OfficeVisit();
}
try {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("officeVisitId", ov.getVisitID());
} catch (NullPointerException e) {
// Do nothing
}
visitID = ov.getVisitID();
patientMID = ov.getPatientMID();
if (patientMID == null) {
patientMID = Long.parseLong(
(String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("pid"));
}
date = ov.getDate();
locationID = ov.getLocationID();
apptTypeID = ov.getApptTypeID();
sendBill = ov.getSendBill();
notes = ov.getNotes();
height = ov.getHeight();
length = ov.getLength();
weight = ov.getWeight();
headCircumference = ov.getHeadCircumference();
bloodPressure = ov.getBloodPressure();
hdl = ov.getHDL();
triglyceride = ov.getTriglyceride();
ldl = ov.getLDL();
householdSmokingStatus = ov.getHouseholdSmokingStatus();
patientSmokingStatus = ov.getPatientSmokingStatus();
} catch (Exception e) {
FacesMessage throwMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Office Visit Controller Error",
"Office Visit Controller Error");
FacesContext.getCurrentInstance().addMessage(null, throwMsg);
}
}
/**
* Called when user clicks on the submit button in officeVisitInfo.xhtml. Takes data from form
* and sends to OfficeVisitMySQLLoader.java for storage and validation
*/
public void submit() {
ov.setApptTypeID(apptTypeID);
ov.setDate(date);
ov.setLocationID(locationID);
ov.setNotes(notes);
ov.setSendBill(sendBill);
ov.setPatientMID(patientMID);
if (isOfficeVisitCreated()) {
controller.edit(ov);
controller.logTransaction(TransactionType.OFFICE_VISIT_EDIT, ov.getVisitID().toString());
} else {
long pid = -1;
FacesContext ctx = FacesContext.getCurrentInstance();
String patientID = "";
if (ctx.getExternalContext().getRequest() instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest) ctx.getExternalContext().getRequest();
HttpSession httpSession = req.getSession(false);
patientID = (String) httpSession.getAttribute("pid");
}
if (ValidationFormat.NPMID.getRegex().matcher(patientID).matches()) {
pid = Long.parseLong(patientID);
}
ov.setPatientMID(pid);
ov.setVisitID(null);
long generatedVisitId = controller.addReturnGeneratedId(ov);
setVisitID(generatedVisitId);
ov.setVisitID(generatedVisitId);
controller.logTransaction(TransactionType.OFFICE_VISIT_CREATE, ov.getVisitID().toString());
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("officeVisitId", generatedVisitId);
}
}
/**
* Called when user updates health metrics on officeVisitInfo.xhtml.
*/
public void submitHealthMetrics() {
boolean isNew = ov.getHouseholdSmokingStatus() == null || ov.getHouseholdSmokingStatus() == 0;
// Some error checking here?
ov.setHeight(height);
ov.setLength(length);
ov.setWeight(weight);
ov.setHeadCircumference(headCircumference);
ov.setBloodPressure(bloodPressure);
ov.setHDL(hdl);
ov.setTriglyceride(triglyceride);
ov.setLDL(ldl);
ov.setHouseholdSmokingStatus(householdSmokingStatus);
ov.setPatientSmokingStatus(patientSmokingStatus);
controller.edit(ov);
if (isNew){
controller.logTransaction(TransactionType.CREATE_BASIC_HEALTH_METRICS, "Age: " + controller.calculatePatientAge(patientMID, date).toString());
} else {
controller.logTransaction(TransactionType.EDIT_BASIC_HEALTH_METRICS, "Age: " + controller.calculatePatientAge(patientMID, date));
}
}
/**
* @return true if the Patient is a baby
*/
public boolean isPatientABaby() {
return controller.isPatientABaby(getPatientMID(), getDate());
}
/**
* @return true if the Patient is a child
*/
public boolean isPatientAChild() {
return controller.isPatientAChild(getPatientMID(), getDate());
}
/**
* @return true if the Patient is an adult
*/
public boolean isPatientAnAdult() {
return controller.isPatientAnAdult(getPatientMID(), getDate());
}
public boolean isOfficeVisitCreated() {
return (visitID != null) && (visitID > 0);
}
}
| 10,059
| 23.417476
| 148
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/prescription/PrescriptionController.java
|
package edu.ncsu.csc.itrust.controller.prescription;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.iTrustController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.old.beans.PatientBean;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
import edu.ncsu.csc.itrust.model.prescription.Prescription;
import edu.ncsu.csc.itrust.model.prescription.PrescriptionMySQL;
@ManagedBean(name = "prescription_controller")
@SessionScoped
public class PrescriptionController extends iTrustController {
private static final String INVALID_PRESCRIPTION = "Invalid Prescription";
private PrescriptionMySQL sql;
public PrescriptionController() throws DBException {
super();
sql = new PrescriptionMySQL();
}
/**
* Constructor injection, intended only for unit testing purposes.
*
* @param ds
* The injected DataSource dependency
*/
public PrescriptionController(DataSource ds) throws DBException {
super();
this.sql = new PrescriptionMySQL(ds);
}
public void setSql(PrescriptionMySQL sql){
this.sql = sql;
}
public void add(Prescription prescription) {
try {
if (sql.add(prescription)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Prescription is successfully created",
"Prescription is successfully created", null);
logTransaction(TransactionType.PRESCRIPTION_ADD, getSessionUtils().getCurrentOfficeVisitId().toString());
} else {
throw new Exception();
}
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_PRESCRIPTION, e.getMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_PRESCRIPTION, INVALID_PRESCRIPTION, null);
}
}
public void edit(Prescription prescription) {
try {
if (sql.update(prescription)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Prescription is successfully updated",
"Prescription is successfully updated", null);
logTransaction(TransactionType.PRESCRIPTION_EDIT, getSessionUtils().getCurrentOfficeVisitId().toString());
} else {
throw new Exception();
}
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_PRESCRIPTION, e.getMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_PRESCRIPTION, INVALID_PRESCRIPTION, null);
}
}
public void remove(long prescriptionID) {
try {
if (sql.remove(prescriptionID)) {
printFacesMessage(FacesMessage.SEVERITY_INFO, "Prescription is successfully deleted",
"Prescription is successfully deleted", null);
logTransaction(TransactionType.PRESCRIPTION_REMOVE, getSessionUtils().getCurrentOfficeVisitId().toString());
} else {
throw new Exception();
}
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_PRESCRIPTION, e.getMessage(), null);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, INVALID_PRESCRIPTION, INVALID_PRESCRIPTION, null);
}
}
public List<Prescription> getPrescriptionsByOfficeVisit(String officeVisitID) throws DBException {
List<Prescription> prescriptions = Collections.emptyList();
long ovID = -1;
if ( officeVisitID != null ) {
ovID = Long.parseLong(officeVisitID);
try {
prescriptions = sql.getPrescriptionsForOfficeVisit(ovID);
} catch (Exception e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to Retrieve Prescriptions", "Unable to Retrieve Prescriptions", null);
}
}
return prescriptions;
}
public Prescription getPrescriptionByID(String prescriptionID) throws SQLException {
Long id = null;
try {
id = Long.parseLong(prescriptionID);
} catch (NumberFormatException e) {
// Do nothing
}
if (id == null) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Cannot get prescription", "Invalid prescription ID", null);
return null;
} else {
return sql.get(id);
}
}
public List<Prescription> getPrescriptionsForCurrentPatient() {
String pid = getSessionUtils().getCurrentPatientMID();
return getPrescriptionsByPatientID(pid);
}
public List<Prescription> getPrescriptionsByPatientID(String patientMID) {
Long mid = null;
List<Prescription> prescriptions = Collections.emptyList();
try {
mid = Long.parseLong(patientMID);
} catch (NumberFormatException e) {
// Do nothing
}
if (mid == null) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Cannot get patient's prescriptions", "Invalid patient MID", null);
return prescriptions;
}
try {
prescriptions = sql.getPrescriptionsByMID(mid);
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Cannot get patient's prescriptions", e.getMessage(), null);
}
return prescriptions;
}
public String getCodeName(String codeString){
String codeName = "";
try {
codeName = sql.getCodeName(codeString);
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Prescription", e.getMessage(), null);
}
return codeName;
}
/**
* This should return to the logging in user a list of patients that they
* represent
*
* @param loggedInID
* mid of the person logged in
*/
public List<PatientBean> getListOfRepresentees() {
List<PatientBean> representees = getSessionUtils().getRepresenteeList();
// If there wasn't already a cached list make it and cache it for future use
if( representees == null ){
try {
Long userMID = this.getSessionUtils().getSessionLoggedInMIDLong();
representees = sql.getListOfRepresentees(userMID);
getSessionUtils().setRepresenteeList(representees);
} catch (SQLException e) {
printFacesMessage(FacesMessage.SEVERITY_ERROR, "Cannot get representees", e.getMessage(), null);
}
}
return representees;
}
public String getRepParameter(){
return this.getSessionUtils().getRequestParameter("rep");
}
public void logViewPrescriptionReport() {
// Only log if a patient has been selected to view the report for
if(getSessionUtils().getCurrentPatientMID() != null) {
logTransaction(TransactionType.PRESCRIPTION_REPORT_VIEW, null);
}
}
}
| 6,441
| 31.21
| 129
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/prescription/PrescriptionForm.java
|
package edu.ncsu.csc.itrust.controller.prescription;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.ndcode.NDCCode;
import edu.ncsu.csc.itrust.model.ndcode.NDCCodeMySQL;
import edu.ncsu.csc.itrust.model.old.beans.MedicationBean;
import edu.ncsu.csc.itrust.model.old.beans.PatientBean;
import edu.ncsu.csc.itrust.model.prescription.Prescription;
import edu.ncsu.csc.itrust.webutils.SessionUtils;
@ManagedBean(name = "prescription_form")
@ViewScoped
public class PrescriptionForm {
private Prescription prescription;
private PrescriptionController controller;
private SessionUtils sessionUtils;
private NDCCodeMySQL ndcData;
public PrescriptionForm() {
this(null, null, SessionUtils.getInstance(), null);
}
public PrescriptionForm(PrescriptionController pc, NDCCodeMySQL nData, SessionUtils sessionUtils, DataSource ds) {
this.sessionUtils = (sessionUtils == null) ? SessionUtils.getInstance() : sessionUtils;
try {
if (ds == null) {
ndcData = (nData == null) ? new NDCCodeMySQL() : nData;
controller = (pc == null) ? new PrescriptionController() : pc;
} else {
ndcData = (nData == null) ? new NDCCodeMySQL(ds) : nData;
controller = (pc == null) ? new PrescriptionController(ds) : pc;
}
clearFields();
} catch (Exception e) {
this.sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Prescription Controller Error",
"Prescription Procedure Controller Error", null);
}
}
public void add(){
controller.add(prescription);
clearFields();
}
public void edit(){
controller.edit(prescription);
clearFields();
}
public void remove(String prescriptionID){
controller.remove( Long.parseLong(prescriptionID) );
clearFields();
}
public List<Prescription> getPrescriptionsByOfficeVisit(String visitID){
List<Prescription> prescriptions = Collections.emptyList();
try {
prescriptions = controller.getPrescriptionsByOfficeVisit(visitID);
} catch (DBException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "Prescription Controller Error", "Prescription Controller Error",
null);
}
return prescriptions;
}
public List<Prescription> getPrescriptionsForCurrentPatient() {
return controller.getPrescriptionsForCurrentPatient();
}
public List<Prescription> getPrescriptionsByPatientID(String patientID) {
return controller.getPrescriptionsByPatientID(patientID);
}
public List<PatientBean> getListOfRepresentees() {
return controller.getListOfRepresentees();
}
public Prescription getPrescription() {
return prescription;
}
public void setPrescription(Prescription prescription) {
this.prescription = prescription;
}
public String getCodeName(String codeString){
return controller.getCodeName(codeString);
}
public List<NDCCode> getNDCCodes() {
try {
return ndcData.getAll();
} catch (SQLException e) {
sessionUtils.printFacesMessage(FacesMessage.SEVERITY_ERROR, "NDC Code retrival error", "NDC Code retrival error",
null);
}
return Collections.emptyList();
}
public void fillInput(String prescriptionID, MedicationBean drug, long dosage, LocalDate startDate, LocalDate endDate, String instructions){
prescription.setDrugCode(drug);
prescription.setDosage(dosage);
prescription.setStartDate(startDate);
prescription.setEndDate(endDate);
prescription.setInstructions(instructions);
prescription.setId( Long.parseLong(prescriptionID) );
}
public void clearFields(){
this.prescription = new Prescription();
prescription.setPatientMID(sessionUtils.getCurrentPatientMIDLong());
prescription.setOfficeVisitId(sessionUtils.getCurrentOfficeVisitId());
prescription.setHcpMID(sessionUtils.getSessionLoggedInMIDLong());
prescription.setStartDate(LocalDate.now());
}
}
| 4,061
| 30.488372
| 141
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/user/UserController.java
|
package edu.ncsu.csc.itrust.controller.user;
import javax.faces.bean.ManagedBean;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
import edu.ncsu.csc.itrust.model.old.enums.Role;
import edu.ncsu.csc.itrust.model.user.User;
import edu.ncsu.csc.itrust.model.user.UserMySQLConverter;
@ManagedBean(name="user")
public class UserController {
private DataBean<User> userData;
public UserController() throws DBException{
userData = new UserMySQLConverter();
}
public String getUserNameForID(String mid) throws DBException{
User user = null;
if( mid == null) return "";
if(mid.isEmpty()) return "";
long id = -1;
try{
id = Long.parseLong(mid);
}
catch(NumberFormatException ne){
return "";
}
//if(id<1) return "";
user = userData.getByID(id);
if(user != null){
if(user.getRole().equals(Role.TESTER)){
return Long.toString(user.getMID());
}
else{
return user.getLastName().concat(", "+user.getFirstName());
}
}
else{
return "";
}
}
public String getUserRoleForID(String mid) throws DBException{
User user = null;
if( mid == null) return "";
if(mid.isEmpty()) return "";
long id = -1;
try{
id = Long.parseLong(mid);
}
catch(NumberFormatException ne){
return "";
}
if(id<1) return "";
user = userData.getByID(id);
return user.getRole().getUserRolesString().toLowerCase();
}
public boolean doesUserExistWithID(String mid) throws DBException{
User user = null;
if( mid == null) return false;
long id = -1;
try{
id = Long.parseLong(mid);
}
catch(NumberFormatException ne){
return false;
}
user = userData.getByID(id);
if(!(user == null)){
return true;
}
else{
return false;
}
}
}
| 1,772
| 19.37931
| 67
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/controller/user/patient/PatientController.java
|
package edu.ncsu.csc.itrust.controller.user.patient;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import edu.ncsu.csc.itrust.controller.user.UserController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
import edu.ncsu.csc.itrust.model.ValidationFormat;
import edu.ncsu.csc.itrust.model.user.User;
import edu.ncsu.csc.itrust.model.user.patient.Patient;
@ManagedBean(name="patient_controller")
public class PatientController extends UserController implements Serializable{
private DataBean<Patient> patientData;
public PatientController() throws DBException {
}
/**
*
*/
private static final long serialVersionUID = -164769440967020045L;
public boolean doesPatientExistWithID(String mid) throws DBException{
User user = null;
if( mid == null) return false;
if(!(ValidationFormat.NPMID.getRegex().matcher(mid).matches())) return false;
long id = -1;
try{
id = Long.parseLong(mid);
}
catch(NumberFormatException ne){
return false;
}
if(null!=patientData)user = patientData.getByID(id);
if(!(user == null)){
return true;
}
else{
return false;
}
}
}
| 1,184
| 22.235294
| 79
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/exception/AddPatientFileException.java
|
package edu.ncsu.csc.itrust.exception;
/**
* This exception is thrown to indicate any type of error which occurs while
* parsing a CSV file.
*/
public class AddPatientFileException extends Exception {
/**
* Unique identifier for the exception
*/
private static final long serialVersionUID = -6933792430135749055L;
/**
* The error message for the exception
*/
String message;
/**
* Constructor initializing the error message string
*
* @param string The error message string
*/
public AddPatientFileException(String string) {
message=string;
}
/**
* Returns the exception's error message
*
* @return The error message from the exception
*/
@Override
public String getMessage(){
return message;
}
}
| 750
| 18.763158
| 76
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/exception/CSVFormatException.java
|
package edu.ncsu.csc.itrust.exception;
/**
* This exception is thrown to indicate any type of error which occurs while
* parsing a CSV file.
*/
public class CSVFormatException extends Exception {
/**
* Unique identifier for the exception
*/
private static final long serialVersionUID = -6933792430135749055L;
/**
* The error message for the exception
*/
String message;
/**
* Constructor initializing the error message string
*
* @param string The error message string
*/
public CSVFormatException(String string) {
message=string;
}
/**
* Returns the exception's error message
*
* @return The error message from the exception
*/
@Override
public String getMessage(){
return message;
}
}
| 740
| 18.5
| 76
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/exception/DBException.java
|
package edu.ncsu.csc.itrust.exception;
import java.sql.SQLException;
/**
* The reasoning behind this wrapper exception is security. When an SQL Exception gets thrown all the way back
* to the JSP, we begin to reveal details about our database (even knowing that it's MySQL is bad!) So, we
* make a wrapper exception with a vague description, but we also keep track of the SQL Exception for
* debugging and testing purposes.
*
*
*
*/
public class DBException extends ITrustException {
private static final long serialVersionUID = -6554118510590118376L;
private SQLException sqlException = null;
public DBException(SQLException e) {
super("A database exception has occurred. Please see the log in the console for stacktrace");
this.sqlException = e;
}
/**
* @return The SQL Exception that was responsible for this error.
*/
public SQLException getSQLException() {
return sqlException;
}
@Override
public String getExtendedMessage() {
if (sqlException != null)
return sqlException.getMessage();
else
return super.getExtendedMessage();
}
}
| 1,083
| 27.526316
| 110
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/exception/ErrorList.java
|
package edu.ncsu.csc.itrust.exception;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Used by the validators to create a list of error messages.
*
*
*
*/
public class ErrorList implements Iterable<String> {
private List<String> errorList;
public ErrorList() {
errorList = new ArrayList<String>();
}
/**
* Adds a message to the list if it's not a Java null or empty string.
*
* @param errorMessage
*/
public void addIfNotNull(String errorMessage) {
if (errorMessage != null && !"".equals(errorMessage))
errorList.add(errorMessage);
}
/**
* Returns the list of error messages
*
* @return
*/
public List<String> getMessageList() {
return errorList;
}
/**
* Returns true if the list has any errors
*
* @return
*/
public boolean hasErrors() {
return errorList.size() != 0;
}
@Override
public String toString() {
return errorList.toString();
}
@Override
public Iterator<String> iterator() {
return errorList.iterator();
}
}
| 1,032
| 16.810345
| 71
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/exception/FormValidationException.java
|
package edu.ncsu.csc.itrust.exception;
import java.io.IOException;
import java.util.List;
import javax.servlet.jsp.JspWriter;
import org.apache.commons.lang.StringEscapeUtils;
/**
* This exception is used specifically for when an action involves the correct
* and proper submission of a web form. Form Validation is handled by a series of
* other classes, but when form validation is incorrect or incomplete, this exception
* is thrown.
*/
public class FormValidationException extends Exception {
private static final long serialVersionUID = 1L;
private ErrorList errorList;
/**
* Constructor with error messages passed as a list of parameters to the method.
* @param errorMessages The list of error messages to be returned in the special form validation box.
*/
public FormValidationException(String... errorMessages) {
errorList = new ErrorList();
for (String msg : errorMessages) {
errorList.addIfNotNull(msg);
}
}
/**
* Constructor with error messages as a special ErrorList data type.
* @param errorList An ErrorList object which contains the list of error messages.
*/
public FormValidationException(ErrorList errorList) {
this.errorList = errorList;
}
/**
* Returns the error list as a java.util.List of Strings.
* @return The error list
*/
public List<String> getErrorList() {
return errorList.getMessageList();
}
/**
* The error message will be displayed at the top of the iTrust page as in other iTrust Exceptions.
*/
@Override
public String getMessage() {
return "This form has not been validated correctly. The following field are not properly filled in: "
+ errorList.toString();
}
/**
* The special formatting for error messages is then kept in one place.
* @param out The output writer (in this case a JSPWriter) where the formatted list will go.
* @throws IOException If the writer is incorrect.
*/
public void printHTML(JspWriter out) throws IOException {
out.print("<h2>Information not valid</h2><div class=\"errorList\">");
for (String errorMessage : errorList) {
out.print(StringEscapeUtils.escapeHtml(errorMessage) + "<br />");
}
out.print("</div>");
}
/** Like printHTML, except a string is returned. */
public String printHTMLasString() {
StringBuffer buf = new StringBuffer();
for (String errorMessage : errorList) {
buf.append(StringEscapeUtils.escapeHtml(errorMessage));
buf.append("<br />");
}
String r = "<h2>Information not valid</h2><div class=\"errorList\">" + buf.toString() + "</div>";
return r;
}
}
| 2,548
| 31.265823
| 103
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/exception/ITrustException.java
|
package edu.ncsu.csc.itrust.exception;
/**
* A specialized exception class for displaying iTrust error messages.
* This exception is handled by the default iTrust exception handler.
*/
public class ITrustException extends Exception {
private static final long serialVersionUID = 1L;
String message = null;
/**
* The typical constructor.
* @param message A message to be displayed to the screen.
*/
public ITrustException(String message) {
this.message = message;
}
/**
* For messages which are displayed to the user. Usually, this is a very general message for security
* reasons.
*/
@Override
public String getMessage() {
if (message == null)
return "An error has occurred. Please see log for details.";
return message;
}
/**
* For exceptions which show a lot of technical detail, usually delegated to a subclass
*
* @return
*/
public String getExtendedMessage() {
return "No extended information.";
}
}
| 958
| 22.975
| 102
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/logger/TransactionLogger.java
|
package edu.ncsu.csc.itrust.logger;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.old.dao.DAOFactory;
import edu.ncsu.csc.itrust.model.old.dao.mysql.TransactionDAO;
import edu.ncsu.csc.itrust.model.old.enums.TransactionType;
/**
* Singleton provider of the transaction logging mechanism.
*
* @author mwreesjo
*
*/
public class TransactionLogger {
/** The singleton instance of this class. */
private static TransactionLogger singleton = null;
/** The DAO which exposes logging functionality to the singleton */
TransactionDAO dao;
private TransactionLogger() {
dao = DAOFactory.getProductionInstance().getTransactionDAO();
}
/**
* @return Singleton instance of this transaction logging mechanism.
*/
public static synchronized TransactionLogger getInstance() {
if (singleton == null)
singleton = new TransactionLogger();
return singleton;
}
/**
* Logs a transaction. @see {@link TransactionDAO#logTransaction}
*/
public void logTransaction(TransactionType type, Long loggedInMID, Long secondaryMID, String addedInfo) {
try {
dao.logTransaction(type, loggedInMID, secondaryMID, addedInfo);
} catch (DBException e) {
e.printStackTrace();
}
}
}
| 1,232
| 26.4
| 106
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/ConverterDAO.java
|
package edu.ncsu.csc.itrust.model;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* This class pulls the JDBC driver information from Tomcat's context.xml file
* in WebRoot/META-INF/context.xml. This is done only for convenience - so that
* you only have to pull your JDBC info from one place (context.xml)<br />
* <br />
* The tangled mess you see here is SAX, the XML-parser and XPath, an XML
*/
public class ConverterDAO {
private static String getAttribute(Document document, String attribute) throws XPathExpressionException {
return (String) XPathFactory.newInstance().newXPath().compile("/Context/Resource/" + attribute)
.evaluate(document.getDocumentElement(), XPathConstants.STRING);
}
private static Document parseXML(BufferedReader reader) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(reader));
}
public static DataSource getDataSource() {
FileReader f = null;
BufferedReader r = null;
BasicDataSource ds = null;
try {
f = new FileReader("WebRoot/META-INF/context.xml");
r = new BufferedReader(f);
Document document = parseXML(r);
ds = new BasicDataSource();
ds.setDriverClassName(getAttribute(document, "@driverClassName"));
ds.setUsername(getAttribute(document, "@username"));
ds.setPassword(getAttribute(document, "@password"));
ds.setUrl(getAttribute(document, "@url"));
ds.setMaxTotal(15);
ds.setPoolPreparedStatements(true);
} catch (Exception e) {
e.printStackTrace();
}
finally{
try{
r.close();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ds;
}
}
| 2,265
| 28.815789
| 106
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/DataBean.java
|
package edu.ncsu.csc.itrust.model;
import java.util.List;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
public interface DataBean<T> {
public List<T> getAll() throws DBException;
public T getByID(long id) throws DBException;
public boolean add(T addObj) throws FormValidationException, DBException;
public boolean update(T updateObj) throws DBException, FormValidationException;
}
| 454
| 31.5
| 80
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/POJOValidator.java
|
package edu.ncsu.csc.itrust.model;
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 Object to be validated
* Based on the old BeanValidator class
*
*
*
* @param <T>
* The object type to be validated
*/
abstract public class POJOValidator<T> {
abstract public void validate(T obj) 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 float. 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 floatValue
* @param format
* @param isNullable
* @return
*/
protected String checkFormat(String name, Float floatValue, ValidationFormat format, boolean isNullable) {
String str = "";
if (floatValue != null)
str = String.valueOf(floatValue);
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'";
}
/**
* Check if the value is not zero
*
* @param name
* @param value
* @param format
* @param isNullable
* @return
*/
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,710
| 27.133005
| 110
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/SQLLoader.java
|
package edu.ncsu.csc.itrust.model;
import java.sql.Connection;
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 SQLLoader<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 conn The connection to the database
* @param ps The prepared statement to be loaded.
* @param insertObject The object of type T containing the data to be placed.
* @param newInstance True if a new instance of the object should be created, false if the prepared statement should update an existing instance of the object
* @return A prepared statement with the appropriately loaded parameters.
* @throws SQLException
*/
public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, T insertObject, boolean newInstance)
throws SQLException;
}
| 1,980
| 39.428571
| 159
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/ValidationFormat.java
|
package edu.ncsu.csc.itrust.model;
import java.util.regex.Pattern;
/**
* This enum contains regular expressions that match valid inputs to the iTrust
* system. For example, the NAME enum matches all name inputs, and can be "Up to
* 20 letters, space, ' and -".
*
* Each enum value has a regex and a plain-English description of what the regex
* matches. Please add new regexes in alphabetical order.
*
* Naming conventions:
* - Use ALL_CAPS_UNDERSCORE_CASE
* - Prefix related regexes with the thing that relates them. Examples: APPT_TYPE_xxx PATIENT_xxx
*/
public enum ValidationFormat {
ADDRESS("[a-zA-Z0-9.\\s]{1,30}",
"Up to 30 alphanumeric characters, and ."),
ADVERSE_EVENT_COMMENTS("[a-zA-Z0-9.\\-',!;:()?\\s]{1,2000}",
"Up to 2000 alphanumeric characters and .-',!;:()?"),
ALLERGY_DESCRIPTION("[a-zA-Z0-9\\s]{1,30}",
"Up to 30 characters, letters, numbers, and a space"),
ANSWER("[a-zA-Z0-9\\s]{1,30}",
"Up to 30 alphanumeric characters"),
APPT_COMMENT("[0-9a-zA-Z\\s'\"?!:;\\-._\n\t]{1,1000}",
"Between 0 and 1000 alphanumerics with space, and other punctuation"),
APPT_TYPE_DURATION("[0-9]{1,5}",
"Between 1 and 5 numeric digits"),
APPT_TYPE_NAME("[a-zA-Z ]{1,30}",
"Between 1 and 30 alpha characters and space"),
BLOOD_PRESSURE_OV("^[0-9]{1,3}\\/[0-9]{1,3}$",
"Up to 3-digit number / Up to 3-digit number"),
BLOODTYPE("((O)|(A)|(B)|(AB))([+-]{1})",
"Must be [O,A,B,AB]+/-"), // ^(?:O|A|B|AB)[+-]$
CITY("[a-zA-Z\\s]{1,15}",
"Up to 15 characters"),
COMMENTS("[a-zA-Z0-9'\"?!:;\\-._\n\t\\s]{1,500}",
"Up to 500 alphanumeric characters"),
CPT_CODE_DESCRIPTION("[a-zA-Z0-9\\s ()<>,.\\-?/']{1,30}",
"Up to 30 alphanumeric, space and ()<>,.\\-?/'"),
CPT("[\\d]{1,4}[A-Za-z0-9]",
"Up to four digit integer plus a letter or digit"),
DATE("[\\d]{2}/[\\d]{2}/[\\d]{4}",
"MM/DD/YYYY"),
DATETIME("[\\d]{4}-[\\d]{2}-[\\d]{2}[\\s]{1}[\\d]{2}:[\\d]{2}:[\\d]{2}.[\\d]{1}",
"mm/dd/yyyy"),
DIASTOLIC_BLOOD_PRESSURE("^([4-9][0-9]|1[0-4][0-9]|150)$",
"Must be between 40 and 150"),
DRUG_INT_COMMENTS("[a-zA-Z0-9.\\-',!;:()?\\s]{1,500}",
"Up to 500 alphanumeric characters and .-',!;:()?"),
EMAILS("[a-zA-Z0-9.\\-',!;:()?\\s\\\\/]{1,500}",
"Up to 500 alphanumeric characters and .-',!;:()?"),
EMAIL(".+@.+\\..+",
"Up to 30 alphanumeric characters and symbols . and _ @"),
EXERCISETYPE("^(?:Cardio|Weight Training)$",
"must be one of {Cardio, Weight Training}"),
FHR("^[0-9]\\d*",
"Must be 0 or positive integer."),
FHU("^[0-9]*.^[1-9][0-9]*|^[1-9][0-9]*.?[0-9]*$",
"Must be a positive double."),
FULL_ADDRESS("[a-zA-Z0-9.,\\s]{1,100}",
"Up to 100 alphanumeric characters, comma, and ."),
GENDERCOD("(Male)|(Female)|(Not Specified)",
"Only Male, Female, or All Patients"),
GLUCOSE_LEVEL("^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|250)$",
"Must be between 0 and 250"),
HCPMID("9[0-9]{0,9}",
"1-10 digit number beginning with 9"),
HDL_OV("^[0-8]?[0-9]$",
"integer less than 90"),
HeadCircumference("[\\d]{0,3}(\\.(\\d){0,1}){0,1}",
"Up to 3-digit number + up to 1 decimal place"),
HEAD_CIRCUMFERENCE_OV("^[0-9]{0,3}(?:\\.[0-9])?$",
"Up to 3 digit number and up to 1 decimal place"),
HEIGHT("^([0-9]{1,4}\\.[0-9])$",
"Up to 4 digit number and 1 decimal place"),
Height("[\\d]{0,3}(\\.(\\d){0,1}){0,1}",
"Up to 3-digit number + up to 1 decimal place"),
HEIGHT_OV("^[0-9]{0,3}(?:\\.[0-9])?$",
"Up to 3 digit number and up to 1 decimal place"),
HOSPITAL_ID("[\\d]{1,10}",
"Between 1 and 10 digits"),
HOSPITAL_NAME("[0-9a-zA-Z' .]{1,30}",
"Between 1 and 30 alphanumerics, space, ', and ."),
HOURS_LABOR("[\\d]{0,3}.[\\d]{0,2}",
"Hours in labor must between 0.0 and 999.99"),
HSS_OV("^[0-3]$",
"0, 1, 2, or 3, representing household smoking status"),
ICD10CM("^[A-Z][0-9][A-Z0-9]([A-Z0-9]{1,4})?$",
"A capital letter, followed by a number, followed by a capital letter or number, optionally followed by 1-4 capital letters or numbers"),
ICD_CODE_DESCRIPTION("[a-zA-Z0-9\\s ()<>,.\\-?/']{1,30}",
"Up to 30 alphanumeric, space, and ()<>,.\\-?/'"),
INSURANCE_ID("[\\s\\da-zA-Z'-]{1,20}",
"Up to 20 letters, digits, space, ' and -"),
LABPROCEDURE_CONFIDENCE_INTERVAL("^[0-9]|[1-9][0-9]|100$",
"Integer between 0 and 100"),
LABPROCEDURE_NUMRESULT_CONTENT("^[\\-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$",
"A number containing an optional minus sign and an optional decimal point."),
LABPROCEDURE_NUMRESULT_LENGTH("^.{1,20}$",
"A number containing between 1 and 20 characters, including the optional minus sign and decimal point."),
LAB_RIGHTS("(ALLOWED)|(RESTRICTED)",
"Only ALLOWED, or RESTRICTED"),
LAB_STATUS("(In Transit)|(Received)|(Testing)|(Pending)|(Completed)",
"Only In Transit, Received, Testing, Pending, or Completed"),
LDL_OV("^(?:[1-5]?[0-9]{1,2}|600)$",
"integer between 0 and 600"),
LENGTH_OV("^[0-9]{0,3}(?:\\.[0-9])?$",
"Up to 3 digit number and up to 1 decimal place"),
LOINC("[\\d]{1,5}[-]{1}[\\d]{1}",
"Must be 1-5 digits followed by a - then another digit"),
LOINC_ITEM("[^\"]{1,100}",
"Up to 100 characters, excluding quotation marks"),
MEALTYPE("^(?:Breakfast|Lunch|Snack|Dinner)$",
"must be one of {Breakfast, Lunch, Snack, Dinner}"),
MESSAGES_BODY("[a-zA-Z0-9\\s'\"?!:;\\-.,_\n\t()\\\\/]{1,1000}",
"Up to 1000 alphanumeric characters, with space, and other punctuation"),
MESSAGES_SUBJECT("[a-zA-Z0-9\\s'\"?!:;\\-._\n\t()]{1,100}",
"Up to 100 alphanumeric characters, with space, and other punctuation"),
MID("[\\d]{1,10}",
"Between 1 and 10 digits"),
NAME("^(?=.*[a-zA-Z])[\\sa-zA-Z'-]{1,20}$",
"Up to 20 Letters, space, ' and -"),
ND_CODE_DESCRIPTION("[a-zA-Z0-9\\s ()<>,.\\-?/']{1,100}",
"Up to 100 alphanumeric characters plus space and ()<>,.-?/'"),
ND("^[\\d]{1,5}(-[\\d]{1,4})?$",
"Up to five digits, followed by an optional dash with 1-4 more digits"),
NOTES("[a-zA-Z0-9\\s'\"?!:#;\\-.,_\n\t]{1,300}",
"Up to 300 alphanumeric characters, with space, and other punctuation"),
NPMID("[0-8][0-9]{0,9}",
"1-10 digit number not beginning with 9"),
ORC("[\\d]{1,5}",
"Up to five digit integer"),
OR_CODE_DESCRIPTION("[a-zA-Z0-9\\s]{1,80}",
"Up to 80 characters, letters, numbers, and a space"),
PASSWORD("[a-zA-Z0-9]{8,20}",
"8-20 alphanumeric characters"),
PATIENT_INSTRUCTIONS_COMMENTS("^[a-zA-Z0-9#;?\\-'.:,!/ \n]{1,500}$",
"Up to 500 alphanumeric characters, with space, and other punctuation"),
PATIENT_INSTRUCTIONS_NAME("^[a-zA-Z0-9#;?\\-'.:,!/ \n]{1,100}$",
"Up to 100 alphanumeric characters, with space, and other punctuation"),
PATIENT_INSTRUCTIONS_URL("^.{1,200}$",
"Up to 200 characters, as a valid URL"),
PEDOMETER_READING("^([0-9]{1,10})$",
"Up to ten digit integer"),
PHONE_NUMBER("[\\d]{3}-[\\d]{3}-[\\d]{4}",
"xxx-xxx-xxxx"),
PRIORITY("[1-3]",
"Priority must be between 1 and 3"),
PSS_OV("^[0-59]$",
"0-5 or 9, representing patient smoking status"),
QUESTION("[a-zA-Z0-9?\\-'.\\s]{1,50}",
"Up to 50 alphanumeric characters and symbols ?-'."),
REFERRAL_NOTES("[a-zA-Z0-9\\s'\"?!:;\\-.,_\n\t()\\\\/]{1,500}",
"Up to 500 alphanumeric characters, with space, and other punctuation"),
SLEEPTYPE("^(?:Nightly|Nap)$",
"must be one of {Nightly, Nap}"),
STATE("[A-Z]{2}",
"Two capital letters"),
SYSTOLIC_BLOOD_PRESSURE("^([4-9][0-9]|1[0-9][0-9]|2[0-3][0-9]|240)$",
"Must be between 40 and 240"),
TRIGLYCERIDE_OV("^(?:[1-5][0-9]{2}|600)$",
"integer between 100 and 600"),
WEEKS_PREGNANT("^([0-9]|[1-3][0-9]|4[0-2])-[0-6]{1}$",
"Weeks must be between 0 and 42, Days must be between 0 and 6"),
WEEKS_PREGNANT_OV("^([0-9]|[1-3][0-9]|4[0-2])-[0-6]{1}$",
"The patient chosen is not a current obstetrics patient"),
WEIGHT("^([0-9]{1,4}\\.[0-9])$",
"Up to 4 digit number and 1 decimal place"),
Weight("[\\d]{0,4}(\\.(\\d){0,1}){0,1}",
"Up to 4-digit number + up to 1 decimal place"),
WEIGHT_OV("^[0-9]{0,3}(?:\\.[0-9])?$",
"Up to 4 digit number and up to 1 decimal place"),
YEAR("[\\d]{4}",
"Must be 4 digits"),
ZIPCODE("([0-9]{5})|([0-9]{5}-[0-9]{4})",
"xxxxx or xxxxx-xxxx"), // ^[0-9]{5}(?:-[0-9]{4})?$
;
private Pattern regex;
private String description;
ValidationFormat(String regex, String errorMessage) {
this.regex = Pattern.compile(regex);
this.description = errorMessage;
}
public Pattern getRegex() {
return regex;
}
public String getDescription() {
return description;
}
}
| 8,443
| 42.081633
| 140
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/apptType/ApptType.java
|
package edu.ncsu.csc.itrust.model.apptType;
public class ApptType {
private long ID;
private String name;
private int duration;
private int price;
public ApptType() {
this.name = null;
this.duration = 0;
}
public ApptType(String name, int duration) {
this.name = name;
this.duration = duration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public long getID() {
return ID;
}
public void setID(long iD) {
ID = iD;
}
}
| 747
| 13.666667
| 45
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/apptType/ApptTypeData.java
|
package edu.ncsu.csc.itrust.model.apptType;
import java.util.Map;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
import edu.ncsu.csc.itrust.model.apptType.ApptType;
public interface ApptTypeData extends DataBean<ApptType> {
Map<Long, ApptType> getApptTypeIDs(String name) throws DBException;
String getApptTypeName(Long id) throws DBException;
}
| 397
| 29.615385
| 68
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/apptType/ApptTypeMySQLConverter.java
|
package edu.ncsu.csc.itrust.model.apptType;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.DBUtil;
import edu.ncsu.csc.itrust.exception.DBException;
@ManagedBean(name="appt_type")
@SessionScoped
public class ApptTypeMySQLConverter implements Serializable, ApptTypeData{
/**
*
*/
private static final long serialVersionUID = 4035629854880598008L;
@Resource(name="jdbc/itrust")
private DataSource ds;
private ApptTypeMySQLLoader apptTypeLoader;
/**
* @throws DBException
*
*/
public ApptTypeMySQLConverter() throws DBException{
apptTypeLoader = new ApptTypeMySQLLoader();
try {
Context ctx = new InitialContext();
ds = ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: "+e.getMessage()));
}
}
public ApptTypeMySQLConverter(DataSource ds){
apptTypeLoader = new ApptTypeMySQLLoader();
this.ds = ds;
}
@Override
public Map<Long, ApptType> getApptTypeIDs(String name) throws DBException{
Map<Long, ApptType> apptRef = null;
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
try{
apptRef = new HashMap<Long, ApptType>();
conn=ds.getConnection();
pstring = conn.prepareStatement("SELECT * FROM appointmenttype WHERE appt_type=?");
pstring.setString(1, name);
results = pstring.executeQuery();
apptRef = apptTypeLoader.loadRefList(results);
}
catch(SQLException e){
throw new DBException(e);
}
finally {
try{
if(results !=null){
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
return apptRef;
}
@Override
public String getApptTypeName(Long id) throws DBException{
String apptname = null;
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
try{
conn=ds.getConnection();
pstring = conn.prepareStatement("SELECT appt_type FROM appointmenttype WHERE apptType_id=?;");
pstring.setLong(1, id);
results = pstring.executeQuery();
@SuppressWarnings("unused") // Check is useful for debugging purposes
boolean check = results.next();
apptname = results.getString("appt_type");
}
catch(SQLException e){
throw new DBException(e);
}
finally {
try{
if(results !=null){
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
return apptname;
}
@Override
public List<ApptType> getAll() throws DBException {
List<ApptType> ret = null;
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
try{
conn=ds.getConnection();
pstring = conn.prepareStatement("SELECT * FROM appointmenttype;");
results = pstring.executeQuery();
ret = apptTypeLoader.loadList(results);
}
catch(SQLException e){
throw new DBException(e);
}
finally {
try{
if(results !=null){
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
return ret;
}
@Override
public ApptType getByID(long id) throws DBException {
ApptType ret = null;
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
try{
conn=ds.getConnection();
pstring = conn.prepareStatement("SELECT * FROM appointmenttype WHERE apptType_id=?;");
pstring.setLong(1, id);
results = pstring.executeQuery();
results.next();
ret = apptTypeLoader.loadSingle(results);
}
catch(SQLException e){
throw new DBException(e);
}
finally {
try{
if(results !=null){
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
return ret;
}
@Override
public boolean add(ApptType at) throws DBException {
boolean retval = false;
Connection conn = null;
PreparedStatement pstring = null;
int results;
try {
conn = ds.getConnection();
pstring = apptTypeLoader.loadParameters(conn, pstring, at, true);
results = pstring.executeUpdate();
retval = (results >0);
}
catch(SQLException e){
throw new DBException(e);
}
finally{
DBUtil.closeConnection(conn, pstring);
}
return retval;
}
@Override
public boolean update(ApptType at) throws DBException {
boolean retval = false;
Connection conn = null;
PreparedStatement pstring = null;
int results;
try {
conn = ds.getConnection();
pstring = apptTypeLoader.loadParameters(conn, pstring, at, false);
results = pstring.executeUpdate();
retval = (results >0);
}
catch(SQLException e){
throw new DBException(e);
}
finally{
DBUtil.closeConnection(conn, pstring);
}
return retval;
}
}
| 5,463
| 21.302041
| 97
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/apptType/ApptTypeMySQLLoader.java
|
package edu.ncsu.csc.itrust.model.apptType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.ncsu.csc.itrust.model.SQLLoader;
public class ApptTypeMySQLLoader implements SQLLoader<ApptType> {
@Override
public List<ApptType> loadList(ResultSet rs) throws SQLException {
List<ApptType> list = new ArrayList<ApptType>();
while (rs.next())
list.add(loadSingle(rs));
return list;
}
@Override
public ApptType loadSingle(ResultSet rs) throws SQLException {
ApptType apptType = new ApptType();
apptType.setName(rs.getString("appt_type"));
apptType.setDuration(rs.getInt("duration"));
apptType.setID(rs.getLong("apptType_id"));
apptType.setPrice(rs.getInt("price"));
return apptType;
}
public Map<Long, ApptType> loadRefList(ResultSet rs) throws SQLException {
Map<Long,ApptType> map = new HashMap<Long,ApptType>();
while (rs.next()) {
long id;
id= rs.getLong("apptType_id");
map.put(id,loadSingle(rs));
}
return map;
}
@Override
public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, ApptType at,
boolean newInstance) throws SQLException {
String stmt = "";
if (newInstance) {
stmt = "INSERT INTO appointmenttype(apptType_id, appt_type, duration, price) "
+ "VALUES (? ,?, ?, ?);";
} else {
long id = at.getID();
stmt = "UPDATE officeVisit SET apptType_i=?, "
+ "appt_type=?, "
+ "duration=?, "
+ "price=? "
+ "WHERE apptType_id=" + id + ";";
}
ps = conn.prepareStatement(stmt);
ps.setLong(1, at.getID());
ps.setString(2, at.getName());
ps.setInt(3, at.getDuration());
ps.setInt(4,at.getPrice());
return ps;
}
}
| 1,830
| 24.788732
| 92
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/cptcode/CPTCode.java
|
package edu.ncsu.csc.itrust.model.cptcode;
public class CPTCode {
/** Code of the cptCode for immunization, cannot be more than 5 characters long. */
private String code = "";
/** Name of the code of diagnosis, cannot be more than 30 characters long. */
private String name = "";
/**
* Constructor for creating cptCode instance.
*
* @param code
* cpt code, cannot be more than 5 characters long
* @param name
* Name of the immunizations, cannot be more than 30 characters long
*/
public CPTCode(String code, String name) {
super();
this.code = code;
this.name = name;
}
public CPTCode() {
// TODO Auto-generated constructor stub
}
/**
* @return cpt code of the instance
*/
public String getCode() {
return code;
}
/**
* Sets the cpt code of the instance.
* @param code
* new cpt code of the instance
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return immunization name of the instance
*/
public String getName() {
return name;
}
/**
* Sets the immunization name of the instance.
* @param code
* new immunization name of the instance
*/
public void setName(String name) {
this.name = name;
}
public String toString(){
return code + " - " + name;
}
}
| 1,296
| 18.651515
| 84
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/cptcode/CPTCodeMySQL.java
|
package edu.ncsu.csc.itrust.model.cptcode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
public class CPTCodeMySQL {
private CPTCodeValidator validator;
private DataSource ds;
/**
* Constructor of ImmunizationsMySQL instance.
*
* @throws DBException when data source cannot be created from the given context names
*/
public CPTCodeMySQL() throws DBException {
try {
Context ctx = new InitialContext();
this.ds = ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
validator = new CPTCodeValidator();
}
/**
* Constructor for testing.
*
* @param ds testing data source
*/
public CPTCodeMySQL(DataSource ds) {
this.ds = ds;
validator = new CPTCodeValidator();
}
public List<CPTCode> getAll() throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetAllPreparedStatement(conn);
ResultSet rs = pstring.executeQuery()){
return loadResults(rs);
}
}
private PreparedStatement createGetAllPreparedStatement(Connection conn) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM cptCode");
return pstring;
}
private List<CPTCode> loadResults(ResultSet rs) throws SQLException {
List<CPTCode> cptList = new ArrayList<>();
while (rs.next()){
String newCode = rs.getString("code");
String newName = rs.getString("name");
cptList.add(new CPTCode(newCode, newName));
}
return cptList;
}
/**
* Gets a single CPTCode from the database given its code
* @param code The code we should get
* @return The code if it exists in the database, null if it does not exist
* @throws SQLException
*/
public CPTCode getByCode(String code) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetByCodePreparedStatement(conn, code);
ResultSet rs = pstring.executeQuery()){
return loadOneResultIfExists(rs);
}
}
private CPTCode loadOneResultIfExists(ResultSet rs) throws SQLException {
CPTCode returnCode = null;
if (rs.next()){
returnCode = new CPTCode(rs.getString("Code"), rs.getString("name"));
}
return returnCode;
}
private PreparedStatement createGetByCodePreparedStatement(Connection conn, String code) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM cptCode WHERE Code=?");
pstring.setString(1, code);
return pstring;
}
public boolean add(CPTCode addObj) throws SQLException, FormValidationException {
validator.validate(addObj);
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createAddPreparedStatement(conn, addObj);){
return pstring.executeUpdate() > 0;
} catch (MySQLIntegrityConstraintViolationException e){
return false;
}
}
private PreparedStatement createAddPreparedStatement(Connection conn, CPTCode addObj) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("INSERT INTO cptCode(Code, name) "
+ "VALUES(?, ?)");
pstring.setString(1, addObj.getCode());
pstring.setString(2, addObj.getName());
return pstring;
}
public boolean update(CPTCode updateObj) throws SQLException, FormValidationException {
validator.validate(updateObj);
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createUpdatePreparedStatement(conn, updateObj);){
return pstring.executeUpdate() > 0;
}
}
private PreparedStatement createUpdatePreparedStatement(Connection conn, CPTCode updateObj) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("UPDATE cptCode SET name=? WHERE code=?");
pstring.setString(1, updateObj.getName());
pstring.setString(2, updateObj.getCode());
return pstring;
}
public boolean delete(CPTCode deleteObj) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createDeletePreparedStatement(conn, deleteObj);){
return pstring.executeUpdate() > 0;
}
}
private PreparedStatement createDeletePreparedStatement(Connection conn, CPTCode deleteObj) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("DELETE FROM cptCode WHERE code=?");
pstring.setString(1, deleteObj.getCode());
return pstring;
}
public List<CPTCode> getCodesWithFilter(String filter) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = creategetCodesWithFilterPreparedStatement(conn, filter);
ResultSet rs = pstring.executeQuery()){
return loadResults(rs);
}
}
private PreparedStatement creategetCodesWithFilterPreparedStatement(Connection conn, String filter) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM cptCode WHERE Code LIKE ?");
pstring.setString(1, "%" + filter + "%");
return pstring;
}
}
| 5,945
| 35.703704
| 125
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/cptcode/CPTCodeValidator.java
|
package edu.ncsu.csc.itrust.model.cptcode;
import edu.ncsu.csc.itrust.exception.ErrorList;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
import edu.ncsu.csc.itrust.model.ValidationFormat;
public class CPTCodeValidator extends POJOValidator<CPTCode> {
/**
* {@inheritDoc}
*/
@Override
public void validate(CPTCode obj) throws FormValidationException {
ErrorList errorList = new ErrorList();
// code
errorList.addIfNotNull(checkFormat("CPTCode", obj.getCode(), ValidationFormat.CPT, false));
// name
errorList.addIfNotNull(checkFormat("Name", obj.getName(), ValidationFormat.CPT_CODE_DESCRIPTION, false));
if (errorList.hasErrors()) {
throw new FormValidationException(errorList);
}
}
}
| 806
| 27.821429
| 107
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/diagnosis/Diagnosis.java
|
package edu.ncsu.csc.itrust.model.diagnosis;
import edu.ncsu.csc.itrust.model.icdcode.ICDCode;
/**
* Model of HCP's diagnosis of a patient during office visit.
*/
public class Diagnosis {
/**
* Primary identifier of diagnosis.
*/
private long id;
/**
* ID references the office visit that the diagnosis belongs.
*/
private long visitId;
/**
* ICD10CM code representing description of the diagnosis.
*/
private ICDCode icdCode;
/**
* Default constructor.
*/
public Diagnosis() {
super();
icdCode = new ICDCode();
}
/**
* Constructor for creating an instance of Diagnosis.
*
* @param id
* id of diagnosis
* @param visitId
* office visit id of diagnosis
* @param icdCode
* ICD10CM code for diagnosis
*/
public Diagnosis(long id, long visitId, ICDCode icdCode) {
super();
this.id = id;
this.visitId = visitId;
this.icdCode = icdCode;
}
/**
* @return id of the instance
*/
public long getId() {
return id;
}
/**
* @return office visit id of the instance
*/
public long getVisitId() {
return visitId;
}
/**
* Sets the office visit id of the instance.
* @param visitId
* new office visit id of the instance
*/
public void setVisitId(long visitId) {
this.visitId = visitId;
}
/**
* @return ICD10CM code of the instance
*/
public ICDCode getIcdCode() {
return icdCode;
}
/**
* Sets the ICD10CM code of the instance.
* @param icdCode
* new ICD10CM code of the instance
*/
public void setIcdCode(ICDCode icdCode) {
this.icdCode = icdCode;
}
/**
* @return ICD10CM code string of the instance
*/
public String getCode() {
return getIcdCode() == null ? "" : getIcdCode().getCode();
}
/**
* @return ICD10CM name description of the instance
*/
public String getName() {
return getIcdCode() == null ? "" : getIcdCode().getName();
}
}
| 1,883
| 17.291262
| 62
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/diagnosis/DiagnosisData.java
|
package edu.ncsu.csc.itrust.model.diagnosis;
import java.sql.SQLException;
import java.util.List;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
public interface DiagnosisData extends DataBean<Diagnosis> {
/**
* Gets a list of Diagnosis that are either chronic diagnoses or short term
* diagnoses made within the last 30 days.
*
* @param mid
* patient MID
* @return a list of diagnosis shown for emergency reporting
* @throws DBException when error occurs when accessing database
*/
public List<Diagnosis> getAllEmergencyDiagnosis(long mid) throws SQLException;
/**
* Removes a given diagnosis by id.
*
* @param id
* id of diagnosis to remove
* @return whether if a diagnosis is removed
* @throws DBException when error occurs when accessing database
*/
public boolean remove(long id) throws DBException;
/**
* @param visitId
* office visit id
* @return list of diagnosis from a given office visit
* @throws SQLException when error occurs when accessing database
*/
public List<Diagnosis> getAllDiagnosisByOfficeVisit(long visitId) throws DBException;
}
| 1,163
| 28.846154
| 86
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/diagnosis/DiagnosisMySQL.java
|
package edu.ncsu.csc.itrust.model.diagnosis;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
public class DiagnosisMySQL implements DiagnosisData {
private DiagnosisSQLLoader loader;
private DiagnosisValidator validator;
private DataSource ds;
/**
* Constructor of DiagnosisMySQL instance.
*
* @throws DBException when data source cannot be created from the given context names
*/
public DiagnosisMySQL() throws DBException {
loader = new DiagnosisSQLLoader();
try {
this.ds = getDataSource();
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
validator = new DiagnosisValidator();
}
public Context getContext() throws NamingException {
return new InitialContext();
}
public DataSource getDataSource() throws NamingException {
return ((DataSource) (((Context) getContext().lookup("java:comp/env"))).lookup("jdbc/itrust"));
}
/**
* Constructor for testing.
*
* @param ds
* testing data source
*/
public DiagnosisMySQL(DataSource ds) {
loader = new DiagnosisSQLLoader();
this.ds = ds;
validator = new DiagnosisValidator();
}
/**
* {@inheritDoc}
*/
@Override
public List<Diagnosis> getAll() throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM diagnosis, icdcode where icdcode = code");
ResultSet rs = ps.executeQuery()) {
return loader.loadList(rs);
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public Diagnosis getByID(long id) throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement ps = createGetByIdStatement(conn, id);
ResultSet rs = ps.executeQuery()) {
return rs.next() ? loader.loadSingle(rs) : null;
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* @param conn
* database connection
* @param id
* id of diagnosis
* @return statement to retrieve diagnosis by id
* @throws SQLException when error occurs when querying db
*/
private PreparedStatement createGetByIdStatement(Connection conn, long id) throws SQLException {
PreparedStatement result = conn.prepareStatement("SELECT * FROM diagnosis, icdcode where icdcode = code AND id = ?");
result.setLong(1, id);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(Diagnosis addObj) throws DBException {
try {
validator.validate(addObj);
} catch (FormValidationException e) {
throw new DBException(new SQLException(e.getMessage()));
}
try (Connection conn = ds.getConnection();
PreparedStatement ps = loader.loadParameters(conn, null, addObj, true);) {
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean update(Diagnosis updateObj) throws DBException {
try {
validator.validate(updateObj);
} catch (FormValidationException e) {
throw new DBException(new SQLException(e.getMessage()));
}
try (Connection conn = ds.getConnection();
PreparedStatement ps = loader.loadParameters(conn, null, updateObj, false);) {
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new DBException(e);
}
}
public boolean remove(long diagnosisId) throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement ps = createRemoveStatement(conn, diagnosisId)) {
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new DBException(e);
}
}
private PreparedStatement createRemoveStatement(Connection conn, long id) throws SQLException {
PreparedStatement ps = conn.prepareStatement("DELETE FROM diagnosis WHERE id = ?");
ps.setLong(1, id);
return ps;
}
/**
* {@inheritDoc}
*/
@Override
public List<Diagnosis> getAllEmergencyDiagnosis(long mid) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement statement = createEmergencyDiagnosisPreparedStatement(conn, mid);
ResultSet resultSet = statement.executeQuery()) {
return loader.loadList(resultSet);
}
}
public PreparedStatement createEmergencyDiagnosisPreparedStatement(Connection conn, long mid) throws SQLException {
PreparedStatement ps = conn.prepareStatement(
"SELECT d.id, d.visitId, d.icdCode, c.name, c.is_chronic FROM diagnosis d, icdcode c, officevisit ov "
+ "WHERE d.visitId = ov.visitID AND ov.patientMID = ? AND d.icdCode = c.code "
+ "AND (c.is_chronic OR ov.visitDate >= DATE_SUB(NOW(), INTERVAL 30 DAY)) "
+ "ORDER BY ov.visitDate DESC");
ps.setLong(1, mid);
return ps;
}
@Override
public List<Diagnosis> getAllDiagnosisByOfficeVisit(long visitId) throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement ps = createGetByOfficeVisitStatement(conn, visitId);
ResultSet rs = ps.executeQuery()) {
return loader.loadList(rs);
} catch (SQLException e) {
throw new DBException(e);
}
}
public PreparedStatement createGetByOfficeVisitStatement(Connection conn, long visitId) throws SQLException {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM diagnosis, icdcode where icdcode = code AND visitId = ?");
ps.setLong(1, visitId);
return ps;
}
}
| 5,666
| 28.826316
| 120
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/diagnosis/DiagnosisSQLLoader.java
|
package edu.ncsu.csc.itrust.model.diagnosis;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import edu.ncsu.csc.itrust.model.SQLLoader;
import edu.ncsu.csc.itrust.model.icdcode.ICDCode;
public class DiagnosisSQLLoader implements SQLLoader<Diagnosis> {
@Override
public List<Diagnosis> loadList(ResultSet rs) throws SQLException {
List<Diagnosis> list = new LinkedList<Diagnosis>();
while (rs.next()) {
list.add(loadSingle(rs));
}
return list;
}
@Override
public Diagnosis loadSingle(ResultSet rs) throws SQLException {
long id = rs.getLong("id");
long visitId = rs.getLong("visitId");
String icdCode = rs.getString("icdCode");
String name = rs.getString("name");
boolean isChronic = rs.getBoolean("is_chronic");
return new Diagnosis(id, visitId, new ICDCode(icdCode, name, isChronic));
}
@Override
public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, Diagnosis insertObject,
boolean newInstance) throws SQLException {
if (newInstance) {
ps = conn.prepareStatement("INSERT INTO diagnosis (visitId, icdCode) values (?, ?)");
ps.setLong(1, insertObject.getVisitId());
ps.setString(2, insertObject.getCode());
} else {
ps = conn.prepareStatement("UPDATE diagnosis SET icdCode = ?, visitId = ? WHERE id = ?");
ps.setString(1, insertObject.getCode());
ps.setLong(2, insertObject.getVisitId());
ps.setLong(3, insertObject.getId());
}
return ps;
}
}
| 1,564
| 29.686275
| 103
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/diagnosis/DiagnosisValidator.java
|
package edu.ncsu.csc.itrust.model.diagnosis;
import java.time.format.DateTimeFormatter;
import edu.ncsu.csc.itrust.exception.ErrorList;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
import edu.ncsu.csc.itrust.model.ValidationFormat;
/**
* Validates instance of Diagnosis.
*/
public class DiagnosisValidator extends POJOValidator<Diagnosis> {
/**
* {@inheritDoc}
*/
@Override
public void validate(Diagnosis obj) throws FormValidationException {
ErrorList errorList = new ErrorList();
if (obj == null) {
errorList.addIfNotNull("Invalid Diagnosis object");
throw new FormValidationException(errorList);
}
if (obj.getIcdCode() == null) {
errorList.addIfNotNull("Invalid ICDCode object");
} else {
errorList.addIfNotNull(checkFormat("ICD Code", obj.getIcdCode().getCode(), ValidationFormat.ICD10CM, false));
}
if (errorList.hasErrors()) {
throw new FormValidationException(errorList);
}
}
}
| 1,001
| 26.081081
| 112
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/emergencyRecord/EmergencyRecord.java
|
package edu.ncsu.csc.itrust.model.emergencyRecord;
import java.util.ArrayList;
import java.util.List;
import edu.ncsu.csc.itrust.model.prescription.Prescription;
import edu.ncsu.csc.itrust.model.diagnosis.Diagnosis;
import edu.ncsu.csc.itrust.model.immunization.Immunization;
import edu.ncsu.csc.itrust.model.old.beans.AllergyBean;
/**
* A class for storing emergency health record data for UC21
* @author nmiles
*
*/
public class EmergencyRecord {
private String name;
private int age;
private String gender;
private String contactName;
private String contactPhone;
private List<AllergyBean> allergies;
private String bloodType;
private List<Diagnosis> diagnoses;
private List<Prescription> prescriptions;
private List<Immunization> immunizations;
/**
* Get the patient name
* @return
*/
public String getName() {
return name;
}
/**
* Set the patient name
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the patient age
* @return
*/
public int getAge() {
return age;
}
/**
* Set the patient age
* @param age
*/
public void setAge(int age) {
this.age = age;
}
/**
* Get the patient's gender
* @return
*/
public String getGender() {
return gender;
}
/**
* Set the patient's gender
* @param gender
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* Get the patient's emergency contact's name
* @return
*/
public String getContactName() {
return contactName;
}
/**
* Set the patient's emergency contact's name
* @param contactName
*/
public void setContactName(String contactName) {
this.contactName = contactName;
}
/**
* Get the patient's emergency contact's phone number
* @return
*/
public String getContactPhone() {
return contactPhone;
}
/**
* Set the patient's emergency contact's name
* @param contactPhone
*/
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
/**
* Gets a list of all this patient's allergies.
* WARNING: Allergy functionality has not been added to the system yet, so
* this list will always be empty or null.
* @return
*/
public List<AllergyBean> getAllergies() {
return allergies;
}
/**
* Sets a List of all this patient's allergies
* @param allergies
*/
public void setAllergies(List<AllergyBean> allergies) {
this.allergies = allergies;
}
/**
* Gets the patient's blood type
* @return
*/
public String getBloodType() {
return bloodType;
}
/**
* Sets the patient's blood type
* @param bloodType
*/
public void setBloodType(String bloodType) {
this.bloodType = bloodType;
}
/**
* Gets a List of all the patient's diagnoses
* WARNING: Diagnosis functionality has not been added to the system yet,
* so this list will always be empty or null.
* @return
*/
public List<Diagnosis> getDiagnoses() {
return diagnoses;
}
/**
* Sets the List of this patient's diagnoses
* @param diagnoses
*/
public void setDiagnoses(List<Diagnosis> diagnoses) {
this.diagnoses = new ArrayList<Diagnosis>(diagnoses);
}
/**
* Gets a List of all the patient's prescriptions
* WARNING: Prescription functionality has not been added to the system yet,
* so this list will always be empty or null.
* @return
*/
public List<Prescription> getPrescriptions() {
return prescriptions;
}
/**
* Sets a List of all the patient's prescriptions
* @param prescriptions
*/
public void setPrescriptions(List<Prescription> prescriptions) {
this.prescriptions = prescriptions;
}
/**
* Gets a List of all the patient's immunizations
* WARNING: Immunization functionality has not been added to the system yet,
* so this list will always be empty or null.
* @return
*/
public List<Immunization> getImmunizations() {
return immunizations;
}
/**
* Sets a List of all the patient's immunizations
* @param immunizations
*/
public void setImmunizations(List<Immunization> immunizations) {
this.immunizations = immunizations;
}
}
| 4,679
| 22.877551
| 80
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/emergencyRecord/EmergencyRecordMySQL.java
|
package edu.ncsu.csc.itrust.model.emergencyRecord;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.prescription.PrescriptionMySQL;
import edu.ncsu.csc.itrust.model.diagnosis.DiagnosisData;
import edu.ncsu.csc.itrust.model.diagnosis.DiagnosisMySQL;
import edu.ncsu.csc.itrust.model.immunization.ImmunizationMySQL;
import edu.ncsu.csc.itrust.model.old.dao.DAOFactory;
import edu.ncsu.csc.itrust.model.old.dao.mysql.AllergyDAO;
public class EmergencyRecordMySQL {
private DataSource ds;
private PrescriptionMySQL prescriptionLoader;
private DiagnosisData diagnosisData;
private AllergyDAO allergyData;
private ImmunizationMySQL immunizationData;
/**
* Standard constructor for use in deployment
* @throws DBException
*/
public EmergencyRecordMySQL() throws DBException {
try {
this.ds = getDataSource();
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
diagnosisData = new DiagnosisMySQL(ds);
allergyData = DAOFactory.getProductionInstance().getAllergyDAO();
prescriptionLoader = new PrescriptionMySQL(ds);
immunizationData = new ImmunizationMySQL(ds);
}
protected DataSource getDataSource() throws NamingException {
Context ctx = new InitialContext();
return ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
}
/**
* Constructor for testing purposes
* @param ds The DataSource to use
* @param allergyData the AllergyDAO to use
*/
public EmergencyRecordMySQL(DataSource ds, AllergyDAO allergyData) {
this.ds = ds;
diagnosisData = new DiagnosisMySQL(ds);
this.allergyData = allergyData;
prescriptionLoader = new PrescriptionMySQL(ds);
immunizationData = new ImmunizationMySQL(ds);
}
/**
* Gets the EmergencyRecord for the patient with the given MID
* @param patientMID The MID of the patient whose record you want
* @return The retrieved EmergencyRecord
* @throws DBException
*/
public EmergencyRecord getEmergencyRecordForPatient(long patientMID) throws DBException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createPreparedStatement(conn, patientMID);
ResultSet results = pstring.executeQuery()){
return loadRecord(results);
} catch (SQLException e){
throw new DBException(e);
}
}
/**
* A utility method that uses a ResultSet to load an EmergencyRecord.
* @param rs The ResultSet to load from
* @param patientMID The MID of the patient that we're loading results for
* @return The loaded EmergencyRecord
* @throws SQLException
* @throws DBException
*/
public EmergencyRecord loadRecord(ResultSet rs) throws SQLException, DBException {
EmergencyRecord newRecord = new EmergencyRecord();
if (!rs.next()){
return null;
}
long mid = rs.getLong("MID");
newRecord.setName(rs.getString("firstName") + " " + rs.getString("lastName"));
LocalDate now = LocalDate.now();
LocalDate birthdate = rs.getDate("DateOfBirth").toLocalDate();
int age = (int) ChronoUnit.YEARS.between(birthdate, now);
newRecord.setAge(age);
newRecord.setGender(rs.getString("Gender"));
newRecord.setContactName(rs.getString("eName"));
newRecord.setContactPhone(rs.getString("ePhone"));
newRecord.setBloodType(rs.getString("BloodType"));
LocalDate endDate = LocalDate.now().minusDays(91);
newRecord.setPrescriptions(
prescriptionLoader.getPrescriptionsForPatientEndingAfter(
mid, endDate));
newRecord.setAllergies(allergyData.getAllergies(mid));
newRecord.setDiagnoses(diagnosisData.getAllEmergencyDiagnosis(mid));
newRecord.setImmunizations(immunizationData.getAllImmunizations(mid));
return newRecord;
}
/**
* A convenience method for preparing the needed SQL query
*
* @param conn The Connection the PreparedStatement should be made on
* @param mid The mid of the patient whose record we want
* @return The PreparedStatement for the query
* @throws SQLException
*/
private PreparedStatement createPreparedStatement(Connection conn, long mid) throws SQLException{
PreparedStatement statement = conn.prepareStatement("SELECT * FROM patients WHERE MID=?");
statement.setLong(1, mid);
return statement;
}
}
| 5,048
| 38.139535
| 106
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/hospital/Hospital.java
|
package edu.ncsu.csc.itrust.model.hospital;
import javax.faces.bean.ManagedBean;
/**
* 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)
*/
@ManagedBean(name="hospital")
public class Hospital {
String hospitalID = "";
String hospitalName = "";
String hospitalAddress = "";
String hospitalCity = "";
String hospitalState = "";
String hospitalZip = "";
public Hospital() {
}
public Hospital(String hospitalID) {
this.hospitalID = hospitalID;
}
public Hospital(String hospitalID, String hospitalName) {
this.hospitalID = hospitalID;
this.hospitalName = hospitalName;
}
public Hospital(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((Hospital) obj);
}
@Override
public int hashCode() {
return 42; // any arbitrary constant will do
}
private boolean equals(Hospital other) {
return hospitalID.equals(other.hospitalID) && hospitalName.equals(other.hospitalName);
}
}
| 2,582
| 23.367925
| 145
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/hospital/HospitalData.java
|
package edu.ncsu.csc.itrust.model.hospital;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
import edu.ncsu.csc.itrust.model.hospital.Hospital;
public interface HospitalData extends DataBean<Hospital>{
public String getHospitalName(String id) throws DBException;
public Hospital getHospitalByID(String locationID) throws DBException;
}
| 386
| 31.25
| 71
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/hospital/HospitalMySQLConverter.java
|
package edu.ncsu.csc.itrust.model.hospital;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.DBUtil;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.SQLLoader;
import edu.ncsu.csc.itrust.model.ValidationFormat;
import edu.ncsu.csc.itrust.model.hospital.Hospital;
@ManagedBean
public class HospitalMySQLConverter implements HospitalData, Serializable{
/**
*
*/
private static final long serialVersionUID = 964736533764578154L;
private DataSource ds;
private static SQLLoader<Hospital> hospitalLoader;
public HospitalMySQLConverter() throws DBException{
hospitalLoader = new HospitalMySQLLoader();
try {
Context ctx = new InitialContext();
this.ds = ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: "+e.getMessage()));
}
}
public HospitalMySQLConverter(DataSource ds){
hospitalLoader = new HospitalMySQLLoader();
this.ds = ds;
}
@Override
public List<Hospital> getAll() throws DBException{
List<Hospital> ret = null;
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
try{
conn=ds.getConnection();
pstring = conn.prepareStatement("SELECT HospitalID, HospitalName, Address, City, State, Zip FROM hospitals;");
results = pstring.executeQuery();
ret = hospitalLoader.loadList(results);
}
catch(SQLException e){
throw new DBException(e);
}
finally {
try{
if(results !=null){
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
return ret;
}
@Override
public String getHospitalName(String id) throws DBException{
String hospitalname = null;
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
try{
conn=ds.getConnection();
pstring = conn.prepareStatement("SELECT HospitalName FROM hospitals WHERE HospitalID = ?;");
pstring.setString(1, id);
results = pstring.executeQuery();
@SuppressWarnings("unused") //temp is useful for debugging purposes
boolean temp = results.next();
hospitalname = results.getString("HospitalName");
}
catch(SQLException e){
throw new DBException(e);
}
finally {
try{
if(results !=null){
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
return hospitalname;
}
@Override
@Deprecated
public Hospital getByID(long id) throws DBException {
throw new IllegalStateException("HospitalID is NOT a 'long' value");
}
@Override
public boolean add(Hospital hospital) throws DBException {
boolean retval = false;
Connection conn = null;
PreparedStatement pstring = null;
int results;
try {
conn = ds.getConnection();
pstring = hospitalLoader.loadParameters(conn, pstring, hospital, true);
results = pstring.executeUpdate();
retval = (results >0);
}
catch(SQLException e){
throw new DBException(e);
}
finally{
DBUtil.closeConnection(conn, pstring);
}
return retval;
}
@Override
public boolean update(Hospital hospital) throws DBException {
boolean retval = false;
Connection conn = null;
PreparedStatement pstring = null;
int results;
try {
conn = ds.getConnection();
pstring = hospitalLoader.loadParameters(conn, pstring, hospital, false);
results = pstring.executeUpdate();
retval = (results >0);
}
catch(SQLException e){
throw new DBException(e);
}
finally{
DBUtil.closeConnection(conn, pstring);
}
return retval; }
@Override
public Hospital getHospitalByID(String locationID) throws DBException {
Hospital ret = null;
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
if(!(ValidationFormat.HOSPITAL_ID.getRegex().matcher(locationID).matches())){
throw new DBException(new SQLException("Invalid Location ID"));
}
try{
conn=ds.getConnection();
pstring = conn.prepareStatement("SELECT * FROM hospitals WHERE HospitalID=?;");
ValidationFormat.HOSPITAL_ID.getRegex().matcher(locationID).matches();
pstring.setString(1, locationID);
results = pstring.executeQuery();
results.next();
ret = hospitalLoader.loadSingle(results);
}
catch(SQLException e){
throw new DBException(e);
}
finally {
try{
if(results !=null){
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
return ret;
}
}
| 5,089
| 23.589372
| 114
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/hospital/HospitalMySQLLoader.java
|
package edu.ncsu.csc.itrust.model.hospital;
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.model.SQLLoader;
public class HospitalMySQLLoader implements SQLLoader<Hospital> {
@Override
public List<Hospital> loadList(ResultSet rs) throws SQLException {
List<Hospital> list = new ArrayList<Hospital>();
while (rs.next())
list.add(loadSingle(rs));
return list;
}
@Override
public Hospital loadSingle(ResultSet rs) throws SQLException {
Hospital hospital = new Hospital();
hospital.setHospitalID(rs.getString("HospitalID"));
hospital.setHospitalName(rs.getString("HospitalName"));
hospital.setHospitalAddress(rs.getString("Address"));
hospital.setHospitalCity(rs.getString("City"));
hospital.setHospitalState(rs.getString("State"));
hospital.setHospitalZip(rs.getString("Zip"));
return hospital;
}
@Override
public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, Hospital hospital,
boolean newInstance) throws SQLException {
String stmt = "";
if (newInstance) {
stmt = "INSERT INTO hospitals(HospitalID, HospitalName, Address, City, State, Zip) "
+ "VALUES (? ,?, ?, ?, ?, ?);";
} else {
String id = hospital.getHospitalID();
stmt = "UPDATE officeVisit SET HospitalID=?, "
+ "HospitalName=?, "
+ "Address=?, "
+ "City=?, "
+ "State=?, "
+ "Zip=?"
+ "WHERE HospitalID=" + id + ";";
}
ps = conn.prepareStatement(stmt);
ps.setString(1, hospital.getHospitalID());
ps.setString(2, hospital.getHospitalName());
ps.setString(3, hospital.getHospitalAddress());
ps.setString(4, hospital.getHospitalCity());
ps.setString(5,hospital.getHospitalState());
ps.setString(6, hospital.getHospitalZip());
return ps;
}
}
| 1,889
| 28.53125
| 98
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/icdcode/ICDCode.java
|
package edu.ncsu.csc.itrust.model.icdcode;
public class ICDCode {
/**
* Code of the ICDCode for diagnosis, cannot be more than 8 characters long.
*/
private String code;
/**
* Name of the code of diagnosis, cannot be more than 30 characters long.
*/
private String name;
/**
* Represents whether the symptom is chronic.
*/
private boolean isChronic;
/**
* Constructor for creating ICDCode instance.
*
* @param code
* ICD10CM code, cannot be more than 8 characters long
* @param name
* Name of the diagnosis, cannot be more than 30 characters long
* @param isChronic
* Whether if the symptom is chronic
*/
public ICDCode(String code, String name, boolean isChronic) {
super();
this.code = code;
this.name = name;
this.isChronic = isChronic;
}
public ICDCode() {
// TODO Auto-generated constructor stub
}
/**
* @return ICD10CM code of the instance
*/
public String getCode() {
return code;
}
/**
* Sets the ICD10CM code of the instance.
* @param code
* new ICD10CM code of the instance
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return diagnosis name of the instance
*/
public String getName() {
return name;
}
/**
* Sets the diagnosis name of the instance.
* @param code
* new diagnosis name of the instance
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the isChronic flag of the instance
*/
public boolean isChronic() {
return isChronic;
}
/**
* Sets the isChronic flag of the instance.
* @param code
* new isChronic flag of the instance
*/
public void setChronic(boolean isChronic) {
this.isChronic = isChronic;
}
public String toString(){
String ret = code + " - " + name + " - ";
if( isChronic)
return ret + "Chronic";
return ret + "Not Chronic";
}
}
| 1,898
| 18.78125
| 77
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/icdcode/ICDCodeMySQL.java
|
package edu.ncsu.csc.itrust.model.icdcode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
public class ICDCodeMySQL {
private DataSource ds;
private ICDCodeValidator validator;
/**
* Production constructor
* @throws DBException
*/
public ICDCodeMySQL() throws DBException{
validator = new ICDCodeValidator();
try {
this.ds = getDataSource();
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
}
/**
* Testing constructor
* @param ds The DataSource to use
*/
public ICDCodeMySQL(DataSource ds){
validator = new ICDCodeValidator();
this.ds = ds;
}
/**
* A utility method for getting the DataSource
* @return The DataSource
* @throws NamingException
*/
protected DataSource getDataSource() throws NamingException {
Context ctx = new InitialContext();
return ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
}
/**
* Gets all ICDCodes in the database
* @return A List<ICDCode> of all ICDCodes in the database
* @throws DBException
* @throws SQLException
*/
public List<ICDCode> getAll() throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetAllPreparedStatement(conn);
ResultSet rs = pstring.executeQuery()){
return loadResults(rs);
}
}
/**
* A utility method for loading results from a ResultSet
* @param rs The ResultSet to load from
* @return A List<ICDCode> of all ICDCodes in the ResultSet
* @throws SQLException
*/
private List<ICDCode> loadResults(ResultSet rs) throws SQLException {
List<ICDCode> icdList = new ArrayList<>();
while (rs.next()){
String newCode = rs.getString("code");
String newName = rs.getString("name");
boolean newChronic = rs.getBoolean("is_chronic");
icdList.add(new ICDCode(newCode, newName, newChronic));
}
return icdList;
}
/**
* Creates the PreparedStatement for the getAll() method
* @param conn The Connection to use
* @return The new PreparedStatement
* @throws SQLException
*/
private PreparedStatement createGetAllPreparedStatement(Connection conn) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM icdCode");
return pstring;
}
/**
* Gets the given ICDCode
* @param code The code to get
* @return The ICDCode
* @throws SQLException
*/
public ICDCode getByCode(String code) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = creategetByCodePreparedStatement(conn, code);
ResultSet rs = pstring.executeQuery()){
return loadOneResult(rs);
}
}
/**
* A utility method for loading a single ICDCode from a ResultSet
* @param rs The ResultSet to load from
* @return The first ICDCode from the ResultSet if present, null if
* ResultSet is empty.
* @throws SQLException
*/
private ICDCode loadOneResult(ResultSet rs) throws SQLException {
ICDCode loadedCode = null;
if (rs.next()){
loadedCode = new ICDCode(rs.getString("code"), rs.getString("name"), rs.getBoolean("is_chronic"));
}
return loadedCode;
}
/**
* Creates the PreparedStatement for the getByCode() method
* @param conn The Connection to use
* @param code The code to get
* @return The new PreparedStatement
* @throws SQLException
*/
private PreparedStatement creategetByCodePreparedStatement(Connection conn, String code) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM icdCode WHERE code=?");
pstring.setString(1, code);
return pstring;
}
/**
* Adds an ICDCode to the database
* @param addObj The ICDCode to add
* @return True if the record was added successfully, false otherwise
* @throws SQLException If there was a database error
* @throws FormValidationException If there was a validation error
*/
public boolean add(ICDCode addObj) throws SQLException, FormValidationException {
validator.validate(addObj);
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createAddPreparedStatement(conn, addObj);){
return pstring.executeUpdate() > 0;
} catch (MySQLIntegrityConstraintViolationException e){
return false;
}
}
/**
* Creates the PreparedStatement for the add() method
* @param conn The Connection to use
* @param addObj The ICDCode to add
* @return The new PreparedStatement
* @throws SQLException
*/
private PreparedStatement createAddPreparedStatement(Connection conn, ICDCode addObj) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("INSERT INTO icdCode(code, name, is_chronic) "
+ "VALUES(?, ?, ?)");
pstring.setString(1, addObj.getCode());
pstring.setString(2, addObj.getName());
pstring.setBoolean(3, addObj.isChronic());
return pstring;
}
/**
* Updates an existing ICDCode in the database
* @param updateObj The ICDCode to update. NOTE: this object MUST have the
* code of the ICDCode that you wish to update. Updating
* the code requires deleting the record from the database
* and adding a new one with an updated code.
* @return True if successfully updated, false otherwise
* @throws SQLException If there was a database error
* @throws FormValidationException If there was a validation error
*/
public boolean update(ICDCode updateObj) throws SQLException, FormValidationException {
validator.validate(updateObj);
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createUpdatePreparedStatement(conn, updateObj);){
return pstring.executeUpdate() > 0;
}
}
/**
* Creates the PreparedStatement for the update() method
* @param conn The Connection to use
* @param updateObj The ICDCode to update
* @return The new PreparedStatement
* @throws SQLException
*/
private PreparedStatement createUpdatePreparedStatement(Connection conn, ICDCode updateObj) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("UPDATE icdCode SET name=?, is_chronic=? WHERE code=?");
pstring.setString(1, updateObj.getName());
pstring.setBoolean(2, updateObj.isChronic());
pstring.setString(3, updateObj.getCode());
return pstring;
}
/**
* Deletes an ICDCode from the database
* @param deleteObj The ICDCode to delete
* @return True if the deletion was successful, false otherwise
* @throws SQLException
*/
public boolean delete(ICDCode deleteObj) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createDeletePreparedStatement(conn, deleteObj);){
return pstring.executeUpdate() > 0;
}
}
/**
* Creates the PreparedStatement for the delete() method
* @param conn The Connection to use
* @param deleteObj The ICDCode to delete
* @return The new PreparedStatement
* @throws SQLException
*/
private PreparedStatement createDeletePreparedStatement(Connection conn, ICDCode deleteObj) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("DELETE FROM icdCode WHERE code=?");
pstring.setString(1, deleteObj.getCode());
return pstring;
}
public List<ICDCode> getCodesWithFilter(String filterString) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = creategetCodesWithFilterPreparedStatement(conn, filterString);
ResultSet rs = pstring.executeQuery()){
return loadResults(rs);
}
}
private PreparedStatement creategetCodesWithFilterPreparedStatement(Connection conn, String filterString) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM icdCode WHERE code LIKE ?");
pstring.setString(1, "%" + filterString + "%");
return pstring;
}
}
| 9,088
| 35.797571
| 131
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/icdcode/ICDCodeValidator.java
|
package edu.ncsu.csc.itrust.model.icdcode;
import edu.ncsu.csc.itrust.exception.ErrorList;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
import edu.ncsu.csc.itrust.model.ValidationFormat;
public class ICDCodeValidator extends POJOValidator<ICDCode>{
@Override
public void validate(ICDCode obj) throws FormValidationException {
ErrorList errorList = new ErrorList();
// code
errorList.addIfNotNull(checkFormat("ICDCode", obj.getCode(), ValidationFormat.ICD10CM, false));
// name
errorList.addIfNotNull(checkFormat("Name", obj.getName(), ValidationFormat.ICD_CODE_DESCRIPTION, false));
if (errorList.hasErrors()) {
throw new FormValidationException(errorList);
}
}
}
| 825
| 30.769231
| 113
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/immunization/Immunization.java
|
package edu.ncsu.csc.itrust.model.immunization;
import edu.ncsu.csc.itrust.model.cptcode.CPTCode;
/**
* Model of HCP's immunization of a patient during office visit.
*/
public class Immunization {
/** Primary identifier of immunization. */
private long id;
/** ID references the office visit that the immunization belongs. */
private long visitId;
/** cpt code representing description of the immunization. */
private CPTCode cptCode;
public Immunization(){
cptCode = new CPTCode();
}
/**
* Constructor for creating an instance of immunization.
*
* @param id
* id of immunization
* @param visitId
* office visit id of immunization
* @param cptCode
* cpt code for immunization
*/
public Immunization(long id, long visitId, CPTCode cptCode) {
super();
this.id = id;
this.visitId = visitId;
this.cptCode = cptCode;
}
/**
* @return id of the instance
*/
public long getId() {
return id;
}
/**
* Sets the id of the instance.
* @param id
* new id of instance
*/
public void setId(long id) {
this.id = id;
}
/**
* @return office visit id of the instance
*/
public long getVisitId() {
return visitId;
}
/**
* Sets the office visit id of the instance.
* @param visitId
* new office visit id of the instance
*/
public void setVisitId(long visitId) {
this.visitId = visitId;
}
/**
* @return cpt code of the instance
*/
public CPTCode getCptCode() {
return cptCode;
}
/**
* Sets the cpt code of the instance.
* @param icdCode
* new cpt code of the instance
*/
public void setCptCode(CPTCode cptCode) {
this.cptCode = cptCode;
}
/**
* @return cpt code string of the instance
*/
public String getCode() {
return getCptCode().getCode();
}
/**
* @return cpt code description of the instance
*/
public String getName() {
return getCptCode().getName();
}
}
| 1,903
| 18.04
| 69
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/immunization/ImmunizationData.java
|
package edu.ncsu.csc.itrust.model.immunization;
import java.util.List;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
public interface ImmunizationData extends DataBean<Immunization> {
/**
* Gets a list of immunizations that are either chronic diagnoses or short term
*
* @param mid patient MID
* @return a list of immunizations
* @throws DBException when error occurs when accessing database
*/
public List<Immunization> getAllImmunizations(long mid) throws DBException;
}
| 541
| 27.526316
| 81
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/immunization/ImmunizationMySQL.java
|
package edu.ncsu.csc.itrust.model.immunization;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
public class ImmunizationMySQL implements ImmunizationData {
private ImmunizationSQLLoader loader;
private ImmunizationValidator validator;
private DataSource ds;
/**
* Constructor of ImmunizationsMySQL instance.
*
* @throws DBException when data source cannot be created from the given context names
*/
public ImmunizationMySQL() throws DBException {
loader = new ImmunizationSQLLoader();
try {
Context ctx = new InitialContext();
this.ds = ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
validator = new ImmunizationValidator(this.ds);
}
/**
* Constructor for testing.
*
* @param ds testing data source
*/
public ImmunizationMySQL(DataSource ds) {
loader = new ImmunizationSQLLoader();
this.ds = ds;
validator = new ImmunizationValidator(this.ds);
}
/**
* {@inheritDoc}
*/
@Override
public List<Immunization> getAll() throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM immunization, cptCode WHERE code=cptcode");
ResultSet results = pstring.executeQuery()) {
List<Immunization> list = loader.loadList(results);
return list;
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public Immunization getByID(long id) throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement statement = conn.prepareStatement("SELECT * FROM immunization, cptCode WHERE id="+id+" AND code=cptcode");
ResultSet resultSet = statement.executeQuery()) {
List<Immunization> immunizationList = loader.loadList(resultSet);
if (immunizationList.size() > 0) {
return immunizationList.get(0);
} else {
return null;
}
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(Immunization addObj) throws DBException {
try {
validator.validate(addObj);
} catch (FormValidationException e1) {
throw new DBException(new SQLException(e1));
}
try (Connection conn = ds.getConnection();
PreparedStatement statement = loader.loadParameters(conn, null, addObj, true);) {
int results = statement.executeUpdate();
return results == 1;
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean update(Immunization updateObj) throws DBException {
try {
validator.validate(updateObj);
} catch (FormValidationException e1) {
throw new DBException(new SQLException(e1.getMessage()));
}
try (Connection conn = ds.getConnection();
PreparedStatement statement = loader.loadParameters(conn, null, updateObj, false);) {
int results = statement.executeUpdate();
return results == 1;
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<Immunization> getAllImmunizations(long mid) throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement statement = createImmunizationPreparedStatement(conn, mid);
ResultSet resultSet = statement.executeQuery()) {
List<Immunization> list = loader.loadList(resultSet);
return list;
} catch (SQLException e) {
throw new DBException(e);
}
}
public PreparedStatement createImmunizationPreparedStatement(Connection conn, long mid) throws SQLException {
StringBuffer sb = new StringBuffer();
sb.append("SELECT ");
sb.append("i.id, ");
sb.append("i.visitId, ");
sb.append("i.cptCode, ");
sb.append("c.name ");
sb.append("FROM ");
sb.append("immunization i, ");
sb.append("cptcode c, ");
sb.append("officevisit ov ");
sb.append("WHERE i.visitId = ov.visitID ");
sb.append("AND ov.patientMID = ? ");
sb.append("AND i.cptCode = c.code ");
PreparedStatement ps = conn.prepareStatement(sb.toString());
ps.setLong(1, mid);
return ps;
}
public boolean remove(long id) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createRemovePreparedStatement(conn, id);){
return pstring.executeUpdate() > 0;
}
}
private PreparedStatement createRemovePreparedStatement(Connection conn, long id) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("DELETE FROM immunization WHERE id=?");
pstring.setLong(1, id);
return pstring;
}
public List<Immunization> getImmunizationsForOfficeVisit(long officeVisitId) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createOVPreparedStatement(conn, officeVisitId);
ResultSet results = pstring.executeQuery()){
return loader.loadList(results);
}
}
private PreparedStatement createOVPreparedStatement(Connection conn, long officeVisitId) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM immunization, cptcode WHERE cptCode=code AND visitId=?");
pstring.setLong(1, officeVisitId);
return pstring;
}
public List<Immunization> getImmunizationsByMID(long mid) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetByMIDStatement(conn, mid);
ResultSet results = pstring.executeQuery()) {
return loader.loadList(results);
}
}
private PreparedStatement createGetByMIDStatement(Connection conn, long mid) throws SQLException {
PreparedStatement pstring = conn.prepareStatement(
"SELECT * FROM immunization, cptcode, officevisit " +
"WHERE immunization.cptCode=cptcode.code " +
"AND immunization.visitId=officevisit.visitID " +
"AND officevisit.patientMID=?");
pstring.setLong(1, mid);
return pstring;
}
public String getCodeName(String code) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetCodeNamePreparedStatement(conn, code);
ResultSet rs = pstring.executeQuery()){
if (!rs.next())
return "";
return rs.getString("name");
}
}
private PreparedStatement createGetCodeNamePreparedStatement(Connection conn, String code) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT name FROM cptCode WHERE Code=?");
pstring.setString(1, code);
return pstring;
}
}
| 7,195
| 31.414414
| 130
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/immunization/ImmunizationSQLLoader.java
|
package edu.ncsu.csc.itrust.model.immunization;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import com.mysql.jdbc.Statement;
import edu.ncsu.csc.itrust.model.SQLLoader;
import edu.ncsu.csc.itrust.model.cptcode.CPTCode;
public class ImmunizationSQLLoader implements SQLLoader<Immunization> {
@Override
public List<Immunization> loadList(ResultSet rs) throws SQLException {
List<Immunization> list = new LinkedList<Immunization>();
while (rs.next()) {
list.add(loadSingle(rs));
}
return list;
}
@Override
public Immunization loadSingle(ResultSet rs) throws SQLException {
long id = rs.getLong("id");
long visitId = rs.getLong("visitId");
String cptCode = rs.getString("cptCode");
String name = rs.getString("name");
return new Immunization(id, visitId, new CPTCode(cptCode, name));
}
@Override
public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, Immunization insertObject,
boolean newInstance) throws SQLException {
String stmt = "";
if( newInstance ){ // IS NEW CODE
stmt = "INSERT INTO immunization(visitId, cptcode) "
+ "VALUES (?, ?);";
} else { // NOT NEW
long id = insertObject.getId();
stmt = "UPDATE immunization SET "
+ "visitId=?, "
+ "cptcode=? "
+ "WHERE id=" + id + ";";
}
ps = conn.prepareStatement(stmt, Statement.RETURN_GENERATED_KEYS);
ps.setLong( 1, insertObject.getVisitId() );
ps.setString( 2, insertObject.getCptCode().getCode() );
return ps;
}
}
| 1,615
| 27.350877
| 106
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/immunization/ImmunizationValidator.java
|
package edu.ncsu.csc.itrust.model.immunization;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.ErrorList;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
/**
* Validates instance of Immunization.
*/
public class ImmunizationValidator extends POJOValidator<Immunization> {
/** Data source for retrieving from database. */
@SuppressWarnings("unused")
private DataSource ds;
/**
* Constructor for ImmunizationValidator.
*/
public ImmunizationValidator(DataSource ds) {
this.ds = ds;
}
/**
* {@inheritDoc}
*/
@Override
public void validate(Immunization obj) throws FormValidationException {
ErrorList errorList = new ErrorList();
String code = obj.getCode();
if( code.isEmpty() || code.length() > 5 )
errorList.addIfNotNull("Invalid code: code are 5 digit numbers");
if ( errorList.hasErrors() )
throw new FormValidationException(errorList);
}
}
| 979
| 22.333333
| 72
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/labProcedure/LabProcedure.java
|
package edu.ncsu.csc.itrust.model.labProcedure;
import java.sql.Timestamp;
import java.util.Arrays;
public class LabProcedure {
public static int PRIORITY_HIGH = 1;
public static int PRIORITY_MEDIUM = 2;
public static int PRIORITY_LOW = 3;
private Long labProcedureID;
private Long labTechnicianID;
private Long officeVisitID;
private Long hcpMID;
private String labProcedureCode;
private Integer priority;
private boolean isRestricted;
private LabProcedureStatus status;
private String commentary;
private String results;
private Timestamp updatedDate;
private Integer confidenceIntervalLower;
private Integer confidenceIntervalUpper;
/** Enum for String representation of lab procedure status */
public enum LabProcedureStatus {
PENDING(1L, "Pending"), IN_TRANSIT(2L, "In transit"), RECEIVED(3L, "Received"), TESTING(4L,
"Testing"), COMPLETED(5L, "Completed");
private String name;
private long id;
LabProcedureStatus(long id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public long getID() {
return id;
}
/**
* Returns status enum with given ID.
*
* @param id
* The ID of the status
* @return Status with the given ID
*/
private static LabProcedureStatus getStatusByID(long id) {
return Arrays.asList(values()).stream().filter(p -> p.getID() == id).findFirst().get();
}
/**
* Returns status enum with given name.
*
* @param name
* The name of the status to return
* @return Status with the given name
*/
private static LabProcedureStatus getStatusByName(String name) {
return Arrays.asList(values()).stream().filter(p -> p.getName().equals(name)).findFirst().get();
}
}
public LabProcedure() {
}
public Long getLabProcedureID() {
return labProcedureID;
}
public void setLabProcedureID(Long labProcedureID) {
this.labProcedureID = labProcedureID;
}
public Long getLabTechnicianID() {
return labTechnicianID;
}
public void setLabTechnicianID(Long labTechnicianID) {
this.labTechnicianID = labTechnicianID;
}
public Long getOfficeVisitID() {
return officeVisitID;
}
public void setOfficeVisitID(Long officeVisitID) {
this.officeVisitID = officeVisitID;
}
public Long getHcpMID() {
return hcpMID;
}
public void setHcpMID(Long hcpMID) {
this.hcpMID = hcpMID;
}
public String getLabProcedureCode() {
return labProcedureCode;
}
public void setLabProcedureCode(String newCode) {
this.labProcedureCode = newCode;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public boolean isRestricted() {
return isRestricted;
}
public void setIsRestricted(boolean isRestricted) {
this.isRestricted = isRestricted;
}
public LabProcedureStatus getStatus() {
return status;
}
public void setStatus(long id) {
this.status = LabProcedureStatus.getStatusByID(id);
}
public void setStatus(String name) {
this.status = LabProcedureStatus.getStatusByName(name);
}
public String getCommentary() {
return commentary;
}
public void setCommentary(String commentary) {
this.commentary = commentary;
}
public String getResults() {
return results;
}
public void setResults(String results) {
this.results = results;
}
public Timestamp getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Timestamp updatedDate) {
this.updatedDate = updatedDate;
}
public Integer getConfidenceIntervalLower() {
return confidenceIntervalLower;
}
public void setConfidenceIntervalLower(Integer confidenceIntervalLower) {
this.confidenceIntervalLower = confidenceIntervalLower;
}
public Integer getConfidenceIntervalUpper() {
return confidenceIntervalUpper;
}
public void setConfidenceIntervalUpper(Integer confidenceIntervalUpper) {
this.confidenceIntervalUpper = confidenceIntervalUpper;
}
}
| 3,960
| 20.883978
| 99
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/labProcedure/LabProcedureData.java
|
package edu.ncsu.csc.itrust.model.labProcedure;
import java.sql.SQLException;
import java.util.List;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
public interface LabProcedureData extends DataBean<LabProcedure> {
/**
* Returns all lab procedures with the given lab technician ID, or empty
* list if no lab procedures exist for the given lab technician ID.
*
* @param technicianID
* The ID of the lab technician to query by
* @return all lab procedures with given lab technician ID
* @throws DBException
*/
List<LabProcedure> getLabProceduresForLabTechnician(Long technicianID) throws DBException;
/**
* Returns all lab procedures with the given office visit ID, or empty
* list if no lab procedures exist for the given office visit ID.
*
* @param officeVisitID
* The ID of the office visit to query by
* @return all lab procedures with given office visit ID
* @throws DBException
*/
List<LabProcedure> getLabProceduresByOfficeVisit(Long officeVisitID) throws DBException;
/**
* Removes lab procedure with given ID.
*
* @param labProcedureID
* The ID of the lab procedure to remove
* @return true if the lab procedure was successfully removed from the
* database
* @throws DBException
*/
boolean removeLabProcedure(Long labProcedureID) throws DBException;
}
| 1,409
| 31.045455
| 91
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/labProcedure/LabProcedureMySQL.java
|
package edu.ncsu.csc.itrust.model.labProcedure;
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 javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.DBUtil;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
public class LabProcedureMySQL implements LabProcedureData {
@Resource(name = "jdbc/itrust2")
private LabProcedureSQLLoader loader;
private DataSource ds;
private LabProcedureValidator validator;
public LabProcedureMySQL() throws DBException {
loader = new LabProcedureSQLLoader();
try {
Context ctx = new InitialContext();
ds = ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
validator = new LabProcedureValidator(ds);
}
/**
* Constructor injection, intended only for unit testing purposes.
*
* @param ds
* The injected DataSource dependency
*/
public LabProcedureMySQL(DataSource ds) {
loader = new LabProcedureSQLLoader();
this.ds = ds;
validator = new LabProcedureValidator(this.ds);
}
/**
* {@inheritDoc}
*/
@Override
public LabProcedure getByID(long id) throws DBException {
LabProcedure labProcedure = null;
Connection conn = null;
PreparedStatement query = null;
ResultSet results = null;
List<LabProcedure> procedureList = null;
try {
conn = ds.getConnection();
query = conn.prepareStatement(LabProcedureSQLLoader.SELECT_BY_LAB_PROCEDURE);
query.setLong(1, id);
results = query.executeQuery();
procedureList = loader.loadList(results);
if (procedureList.size() > 0) {
labProcedure = procedureList.get(0);
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
try {
if (results != null) {
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, query);
}
}
return labProcedure;
}
/**
* {@inheritDoc}
*/
@Override
public List<LabProcedure> getAll() throws DBException {
Connection conn = null;
PreparedStatement query = null;
ResultSet results = null;
try {
conn = ds.getConnection();
query = conn.prepareStatement(LabProcedureSQLLoader.SELECT_ALL);
results = query.executeQuery();
return loader.loadList(results);
} catch (SQLException e) {
throw new DBException(e);
} finally {
try {
if (results != null) {
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, query);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(LabProcedure procedure) throws DBException {
boolean successfullyAdded = false;
Connection conn = null;
PreparedStatement addStatement = null;
procedure.setUpdatedDate(new Timestamp(new Date().getTime()));
try {
validator.validate(procedure);
} catch (FormValidationException e1) {
throw new DBException(new SQLException(e1.getMessage()));
}
try {
conn = ds.getConnection();
addStatement = loader.loadParameters(conn, addStatement, procedure, true);
int exitStatus = addStatement.executeUpdate();
successfullyAdded = (exitStatus > 0);
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, addStatement);
}
return successfullyAdded;
}
/**
* {@inheritDoc}
*/
@Override
public boolean update(LabProcedure procedure) throws DBException {
boolean successfullyUpdated = false;
Connection conn = null;
PreparedStatement updateStatement = null;
procedure.setUpdatedDate(new Timestamp(new Date().getTime()));
try {
validator.validate(procedure);
} catch (FormValidationException e1) {
throw new DBException(new SQLException(e1.getMessage()));
}
try {
conn = ds.getConnection();
updateStatement = loader.loadParameters(conn, updateStatement, procedure, false);
int exitStatus = updateStatement.executeUpdate();
successfullyUpdated = (exitStatus > 0);
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, updateStatement);
}
return successfullyUpdated;
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeLabProcedure(Long labProcedureID) throws DBException {
Connection conn = null;
PreparedStatement removeStatement = null;
try {
conn = ds.getConnection();
removeStatement = conn.prepareStatement(LabProcedureSQLLoader.REMOVE_BY_LAB_PROCEDURE);
removeStatement.setLong(1, labProcedureID);
int exitCode = removeStatement.executeUpdate();
return exitCode > 0;
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, removeStatement);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<LabProcedure> getLabProceduresForLabTechnician(Long technicianID) throws DBException {
Connection conn = null;
PreparedStatement query = null;
ResultSet procedures = null;
try {
conn = ds.getConnection();
query = conn.prepareStatement(LabProcedureSQLLoader.SELECT_BY_LAB_TECHNICIAN);
query.setLong(1, technicianID);
procedures = query.executeQuery();
return loader.loadList(procedures);
} catch (SQLException e) {
throw new DBException(e);
} finally {
try {
if (procedures != null) {
procedures.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, query);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public List<LabProcedure> getLabProceduresByOfficeVisit(Long officeVisitID) throws DBException {
Connection conn = null;
PreparedStatement query = null;
ResultSet procedures = null;
try {
conn = ds.getConnection();
query = conn.prepareStatement(LabProcedureSQLLoader.SELECT_BY_OFFICE_VISIT);
query.setLong(1, officeVisitID);
procedures = query.executeQuery();
return loader.loadList(procedures);
} catch (SQLException e) {
throw new DBException(e);
} finally {
try {
if (procedures != null) {
procedures.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, query);
}
}
}
}
| 6,576
| 25.308
| 99
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/labProcedure/LabProcedureSQLLoader.java
|
package edu.ncsu.csc.itrust.model.labProcedure;
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.model.SQLLoader;
public class LabProcedureSQLLoader implements SQLLoader<LabProcedure> {
/** Lab Procedure table name */
private static final String LAB_PROCEDURE_TABLE_NAME = "labProcedure";
/** Database column names */
private static final String COMMENTARY = "commentary";
private static final String LAB_PROCEDURE_ID = "labProcedureID";
private static final String LAB_TECHNICIAN_ID = "labTechnicianID";
private static final String OFFICE_VISIT_ID = "officeVisitID";
private static final String LAB_PROCEDURE_CODE = "labProcedureCode";
private static final String PRIORITY = "priority";
private static final String RESULTS = "results";
private static final String IS_RESTRICTED = "isRestricted";
private static final String STATUS = "status";
private static final String UPDATED_DATE = "updatedDate";
private static final String CONFIDENCE_INTERVAL_LOWER = "confidenceIntervalLower";
private static final String CONFIDENCE_INTERVAL_UPPER = "confidenceIntervalUpper";
private static final String HCP_MID = "hcpMID";
/** SQL statements relating to lab procedures */
private static final String INSERT = "INSERT INTO " + LAB_PROCEDURE_TABLE_NAME + " ("
+ COMMENTARY + ", "
+ LAB_TECHNICIAN_ID + ", "
+ OFFICE_VISIT_ID + ", "
+ LAB_PROCEDURE_CODE + ", "
+ PRIORITY + ", "
+ RESULTS + ", "
+ IS_RESTRICTED + ", "
+ STATUS + ", "
+ CONFIDENCE_INTERVAL_LOWER + ", "
+ CONFIDENCE_INTERVAL_UPPER + ", "
+ HCP_MID + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
private static final String UPDATE = "UPDATE " + LAB_PROCEDURE_TABLE_NAME + " SET "
+ COMMENTARY + "=?, "
+ LAB_TECHNICIAN_ID + "=?, "
+ OFFICE_VISIT_ID + "=?, "
+ LAB_PROCEDURE_CODE + "=?, "
+ PRIORITY + "=?, "
+ RESULTS + "=?, "
+ IS_RESTRICTED + "=?, "
+ STATUS + "=?, "
+ CONFIDENCE_INTERVAL_LOWER + "=?, "
+ CONFIDENCE_INTERVAL_UPPER + "=?, "
+ HCP_MID + "=? WHERE " + LAB_PROCEDURE_ID + "=?;";
public static final String SELECT_BY_LAB_PROCEDURE = "SELECT * from " + LAB_PROCEDURE_TABLE_NAME + " WHERE "
+ LAB_PROCEDURE_ID + "=?;";
public static final String SELECT_BY_LAB_TECHNICIAN = "SELECT * from " + LAB_PROCEDURE_TABLE_NAME + " WHERE "
+ LAB_TECHNICIAN_ID + "=?;";
public static final String SELECT_BY_OFFICE_VISIT = "SELECT * from " + LAB_PROCEDURE_TABLE_NAME + " WHERE "
+ OFFICE_VISIT_ID + "=?;";
public static final String SELECT_ALL = "SELECT * from " + LAB_PROCEDURE_TABLE_NAME + ";";
public static final String REMOVE_BY_LAB_PROCEDURE = "DELETE FROM " + LAB_PROCEDURE_TABLE_NAME + " WHERE "
+ LAB_PROCEDURE_ID + "=?;";
@Override
public List<LabProcedure> loadList(ResultSet rs) throws SQLException {
List<LabProcedure> list = new ArrayList<LabProcedure>();
while (rs.next())
list.add(loadSingle(rs));
return list;
}
@Override
public LabProcedure loadSingle(ResultSet rs) throws SQLException {
LabProcedure labProcedure = new LabProcedure();
labProcedure.setLabProcedureID(rs.getLong(LAB_PROCEDURE_ID));
labProcedure.setCommentary(rs.getString(COMMENTARY));
labProcedure.setLabTechnicianID(rs.getLong(LAB_TECHNICIAN_ID));
labProcedure.setOfficeVisitID(rs.getLong(OFFICE_VISIT_ID));
labProcedure.setLabProcedureCode(rs.getString(LAB_PROCEDURE_CODE));
labProcedure.setPriority(rs.getInt(PRIORITY));
labProcedure.setResults(rs.getString(RESULTS));
labProcedure.setIsRestricted(rs.getBoolean(IS_RESTRICTED));
labProcedure.setStatus(rs.getLong(STATUS));
labProcedure.setUpdatedDate(rs.getTimestamp(UPDATED_DATE));
labProcedure.setConfidenceIntervalLower(rs.getInt(CONFIDENCE_INTERVAL_LOWER));
labProcedure.setConfidenceIntervalUpper(rs.getInt(CONFIDENCE_INTERVAL_UPPER));
labProcedure.setHcpMID(rs.getLong(HCP_MID));
return labProcedure;
}
@Override
public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, LabProcedure labProcedure,
boolean newInstance) throws SQLException {
StringBuilder query = new StringBuilder(newInstance ? INSERT : UPDATE);
ps = conn.prepareStatement(query.toString());
ps.setString(1, labProcedure.getCommentary());
ps.setLong(2, labProcedure.getLabTechnicianID());
ps.setLong(3, labProcedure.getOfficeVisitID());
ps.setString(4, labProcedure.getLabProcedureCode());
ps.setInt(5, labProcedure.getPriority());
ps.setString(6, labProcedure.getResults());
ps.setBoolean(7, labProcedure.isRestricted());
ps.setLong(8, labProcedure.getStatus().getID());
setIntOrNull(ps, 9, labProcedure.getConfidenceIntervalLower());
setIntOrNull(ps, 10, labProcedure.getConfidenceIntervalUpper());
ps.setLong(11, labProcedure.getHcpMID());
if (!newInstance) {
ps.setLong(12, labProcedure.getLabProcedureID());
}
return ps;
}
/**
* Set integer placeholder in statement to a value or null
*
* @param ps
* PreparedStatement object
* @param index
* Index of placeholder in the prepared statement
* @param value
* Value to set to placeholder, the value may be null
* @throws SQLException
* When placeholder is invalid
*/
public void setIntOrNull(PreparedStatement ps, int index, Integer value) throws SQLException {
if (value == null) {
ps.setNull(index, java.sql.Types.INTEGER);
} else {
ps.setInt(index, value);
}
}
}
| 5,515
| 36.52381
| 110
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/labProcedure/LabProcedureValidator.java
|
package edu.ncsu.csc.itrust.model.labProcedure;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.ErrorList;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
import edu.ncsu.csc.itrust.model.ValidationFormat;
import edu.ncsu.csc.itrust.model.labProcedure.LabProcedure.LabProcedureStatus;
public class LabProcedureValidator extends POJOValidator<LabProcedure> {
private DataSource ds;
public LabProcedureValidator() {
}
public LabProcedureValidator(DataSource ds) {
this.ds = ds;
}
@Override
public void validate(LabProcedure proc) throws FormValidationException {
ErrorList errorList = new ErrorList();
// Commentary
errorList.addIfNotNull(checkFormat("Commentary", proc.getCommentary(),
ValidationFormat.COMMENTS, true));
// Confidence interval lower
Integer confidenceLower = proc.getConfidenceIntervalLower();
if(confidenceLower != null && (confidenceLower < 0 || confidenceLower > 100)) {
errorList.addIfNotNull("Confidence Interval Lower: Confidence interval lower is invalid");
}
// Confidence interval upper
Integer confidenceUpper = proc.getConfidenceIntervalUpper();
if(confidenceUpper != null && (confidenceUpper < 0 || confidenceUpper > 100)) {
errorList.addIfNotNull("Confidence Interval Upper: Confidence interval upper is invalid");
}
if(confidenceLower != null && confidenceUpper != null && confidenceUpper - confidenceLower < 0) {
errorList.addIfNotNull("Confidence Interval: second number must be at least as big as the first number");
}
// Lab procedure code (LOINC code)
errorList.addIfNotNull(checkFormat("Lab procedure code", proc.getLabProcedureCode(),
ValidationFormat.LOINC, false));
// Lab procedure ID, this variable is null on lab procedure creation
if (proc.getLabProcedureID() != null && proc.getLabProcedureID() <= 0) {
errorList.addIfNotNull("Lab Procedure ID: Invalid Lab Procedure ID");
}
// Office visit ID, required
if (proc.getOfficeVisitID() == null || proc.getOfficeVisitID() <= 0) {
errorList.addIfNotNull("Office Visit ID: Invalid Office Visit ID");
}
// Lab technician ID, required
if (proc.getLabTechnicianID() == null || proc.getLabTechnicianID() <= 0) {
errorList.addIfNotNull("Lab Technician ID: Invalid Lab Technician ID");
}
// Priority
if(proc.getPriority() != null && (proc.getPriority() < 1 || proc.getPriority() > 3)) {
errorList.addIfNotNull("Priority: invalid priority (null or out of bounds");
}
// Results
errorList.addIfNotNull(checkFormat("Results", proc.getResults(),
ValidationFormat.COMMENTS, true));
// Status
boolean statusIsValid = false;
LabProcedureStatus statusToValidate = proc.getStatus();
if(statusToValidate != null) {
for(LabProcedureStatus status : LabProcedureStatus.values()) {
if(status.getID() == statusToValidate.getID()) {
statusIsValid = true;
break;
}
}
}
if(!statusIsValid) {
errorList.addIfNotNull("Status: Invalid status");
}
// Updated date
if(proc.getUpdatedDate() == null) {
errorList.addIfNotNull("Updated date: null updated date");
}
// HCP MID
if(proc.getHcpMID() == null) {
errorList.addIfNotNull("HCP MID: Cannot be null");
} else {
errorList.addIfNotNull(checkFormat("HCP MID", proc.getHcpMID(), ValidationFormat.HCPMID, false));
}
if (errorList.hasErrors()) {
throw new FormValidationException(errorList);
}
}
}
| 3,507
| 31.481481
| 108
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/loinccode/LOINCCode.java
|
package edu.ncsu.csc.itrust.model.loinccode;
public class LOINCCode {
private String code;
private String component;
private String kindOfProperty;
private String timeAspect;
private String system;
private String scaleType;
private String methodType;
public LOINCCode(String code, String component, String kindOfProperty) {
this.code = code;
this.component = component;
this.kindOfProperty = kindOfProperty;
}
public LOINCCode(String code, String component, String kindOfProperty, String timeAspect, String system,
String scaleType, String methodType) {
this(code, component, kindOfProperty);
this.timeAspect = timeAspect;
this.system = system;
this.scaleType = scaleType;
this.methodType = methodType;
}
public String getCode() {
return code;
}
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getKindOfProperty() {
return kindOfProperty;
}
public void setKindOfProperty(String kindOfProperty) {
this.kindOfProperty = kindOfProperty;
}
public String getTimeAspect() {
return timeAspect;
}
public void setTimeAspect(String timeAspect) {
this.timeAspect = timeAspect;
}
public String getSystem() {
return system;
}
public void setSystem(String system) {
this.system = system;
}
public String getScaleType() {
return scaleType;
}
public void setScaleType(String scaleType) {
this.scaleType = scaleType;
}
public String getMethodType() {
return methodType;
}
public void setMethodType(String methodType) {
this.methodType = methodType;
}
public String toString(){
return code + " - " + component + " - " + kindOfProperty + " - " + timeAspect + " - " + system + " - " + scaleType + " - " + methodType;
}
}
| 1,783
| 25.626866
| 141
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/loinccode/LOINCCodeData.java
|
package edu.ncsu.csc.itrust.model.loinccode;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
public interface LOINCCodeData extends DataBean<LOINCCode> {
public LOINCCode getByCode(String code) throws DBException;
}
| 264
| 28.444444
| 60
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/loinccode/LOINCCodeMySQL.java
|
package edu.ncsu.csc.itrust.model.loinccode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
public class LOINCCodeMySQL implements LOINCCodeData {
private DataSource ds;
private LOINCCodeValidator validator;
private LOINCCodeSQLLoader loader;
/**
* Standard constructor for use in deployment
*
* @throws DBException
*/
public LOINCCodeMySQL() throws DBException {
try {
this.ds = getDataSource();
this.validator = new LOINCCodeValidator();
this.loader = new LOINCCodeSQLLoader();
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
}
protected DataSource getDataSource() throws NamingException {
Context ctx = new InitialContext();
return ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
}
/**
* Constructor for testing purposes
*
* @param ds
* The DataSource to use
*/
public LOINCCodeMySQL(DataSource ds) {
this.ds = ds;
this.validator = new LOINCCodeValidator();
this.loader = new LOINCCodeSQLLoader();
}
@Override
public List<LOINCCode> getAll() throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM loincCode;");
ResultSet rs = ps.executeQuery();) {
return loader.loadList(rs);
} catch (SQLException e) {
throw new DBException(e);
}
}
@Override
public LOINCCode getByID(long id) throws DBException {
// Not applicable for LOINCCode because it doesn't have id
return null;
}
@Override
public LOINCCode getByCode(String code) throws DBException {
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement(String.format("SELECT * FROM loincCode WHERE code='%s';", code));
ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
return loader.loadSingle(rs);
}
return null;
} catch (SQLException e) {
throw new DBException(e);
}
}
@Override
public boolean add(LOINCCode addObj) throws FormValidationException, DBException {
validator.validate(addObj);
PreparedStatement pstring = null;
try (Connection conn = ds.getConnection();
PreparedStatement ps = loader.loadParameters(conn, pstring, addObj, true);) {
return ps.executeUpdate() > 0;
} catch (MySQLIntegrityConstraintViolationException e){
return false;
} catch (SQLException e) {
throw new DBException(e);
}
}
@Override
public boolean update(LOINCCode updateObj) throws DBException, FormValidationException {
validator.validate(updateObj);
PreparedStatement pstring = null;
try (Connection conn = ds.getConnection();
PreparedStatement ps = loader.loadParameters(conn, pstring, updateObj, false);) {
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new DBException(e);
}
}
public boolean delete(LOINCCode deleteObj) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createDeletePreparedStatement(conn, deleteObj);){
return pstring.executeUpdate() > 0;
}
}
private PreparedStatement createDeletePreparedStatement(Connection conn, LOINCCode deleteObj) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("DELETE FROM loinccode WHERE code=?");
pstring.setString(1, deleteObj.getCode());
return pstring;
}
public List<LOINCCode> getCodesWithFilter(String filterString) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = creategetCodesWithFilterPreparedStatement(conn, filterString);
ResultSet rs = pstring.executeQuery()){
return loader.loadList(rs);
}
}
private PreparedStatement creategetCodesWithFilterPreparedStatement(Connection conn, String filterString) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM loinccode WHERE code LIKE ?");
pstring.setString(1, "%" + filterString + "%");
return pstring;
}
}
| 4,553
| 30.846154
| 131
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/loinccode/LOINCCodeSQLLoader.java
|
package edu.ncsu.csc.itrust.model.loinccode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import edu.ncsu.csc.itrust.model.SQLLoader;
public class LOINCCodeSQLLoader implements SQLLoader<LOINCCode> {
@Override
public List<LOINCCode> loadList(ResultSet rs) throws SQLException {
ArrayList<LOINCCode> list = new ArrayList<LOINCCode>();
while (rs.next()) {
list.add(loadSingle(rs));
}
return list;
}
@Override
public LOINCCode loadSingle(ResultSet rs) throws SQLException {
String code = rs.getString("code");
String component = rs.getString("component");
String kindOfProperty = rs.getString("kind_of_property");
String timeAspect = rs.getString("time_aspect");
String system = rs.getString("system");
String scaleType = rs.getString("scale_type");
String methodType = rs.getString("method_type");
return new LOINCCode(code, component, kindOfProperty, timeAspect, system, scaleType, methodType);
}
@Override
public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, LOINCCode insertObject,
boolean newInstance) throws SQLException {
String stmt = "";
if (newInstance) {
stmt = "INSERT INTO loinccode (code, component, kind_of_property, time_aspect, system, scale_type, method_type) "
+ "values (?, ?, ?, ?, ?, ?, ?);";
} else {
stmt = "UPDATE loinccode SET "
+ "code=?, "
+ "component=?, "
+ "kind_of_property=?, "
+ "time_aspect=?, "
+ "system=?, "
+ "scale_type=?, "
+ "method_type=? "
+ "WHERE code='" + insertObject.getCode() + "';";
}
ps = conn.prepareStatement(stmt, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, insertObject.getCode());
ps.setString(2, insertObject.getComponent());
ps.setString(3, insertObject.getKindOfProperty());
ps.setString(4, insertObject.getTimeAspect());
ps.setString(5, insertObject.getSystem());
ps.setString(6, insertObject.getScaleType());
ps.setString(7, insertObject.getMethodType());
return ps;
}
}
| 2,140
| 31.439394
| 116
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/loinccode/LOINCCodeValidator.java
|
package edu.ncsu.csc.itrust.model.loinccode;
import org.apache.commons.lang3.StringUtils;
import edu.ncsu.csc.itrust.exception.ErrorList;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
import edu.ncsu.csc.itrust.model.ValidationFormat;
public class LOINCCodeValidator extends POJOValidator<LOINCCode> {
@Override
public void validate(LOINCCode obj) throws FormValidationException {
ErrorList errorList = new ErrorList();
if (StringUtils.isEmpty(obj.getCode())) {
errorList.addIfNotNull("Code cannot be empty");
} else {
errorList.addIfNotNull(checkFormat("Code", obj.getCode(), ValidationFormat.LOINC, false));
}
if (StringUtils.isEmpty(obj.getComponent())) {
errorList.addIfNotNull("Component cannot be empty");
}
if (StringUtils.isEmpty(obj.getKindOfProperty())) {
errorList.addIfNotNull("Kind of Property cannot be empty");
}
if (errorList.hasErrors()) {
throw new FormValidationException(errorList);
}
}
}
| 1,014
| 32.833333
| 93
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/medicalProcedure/MedicalProcedure.java
|
package edu.ncsu.csc.itrust.model.medicalProcedure;
import edu.ncsu.csc.itrust.model.cptcode.CPTCode;
public class MedicalProcedure {
private long officeVisitId;
private CPTCode cptCode;
private long id;
public MedicalProcedure(){
cptCode = new CPTCode();
}
public long getOfficeVisitId() {
return officeVisitId;
}
public void setOfficeVisitId(long officeVisitId) {
this.officeVisitId = officeVisitId;
}
public CPTCode getCptCode() {
return cptCode;
}
public void setCptCode(CPTCode code) {
this.cptCode = code;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
/**
* @return cpt code string of the instance
*/
public String getCode() {
return getCptCode().getCode();
}
/**
* @return cpt code description of the instance
*/
public String getName() {
return getCptCode().getName();
}
}
| 1,023
| 20.787234
| 54
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/medicalProcedure/MedicalProcedureMySQL.java
|
package edu.ncsu.csc.itrust.model.medicalProcedure;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.cptcode.CPTCode;
public class MedicalProcedureMySQL {
private DataSource ds;
private MedicalProcedureValidator validator;
public MedicalProcedureMySQL() throws DBException {
try {
this.ds = getDataSource();
this.validator = new MedicalProcedureValidator();
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
}
protected DataSource getDataSource() throws NamingException {
Context ctx = new InitialContext();
return ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
}
public MedicalProcedureMySQL(DataSource ds) {
this.ds = ds;
this.validator = new MedicalProcedureValidator();
}
public boolean add(MedicalProcedure p) throws SQLException{
try {
validator.validate(p);
} catch (FormValidationException e) {
throw new SQLException(e.getMessage());
}
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createAddPreparedStatement(conn, p);){
return pstring.executeUpdate() > 0;
}
}
private PreparedStatement createAddPreparedStatement(Connection conn, MedicalProcedure p) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("INSERT INTO medicalProcedure" +
"(visitId, cptCode) " +
"VALUES(?, ?)");
pstring.setLong(1, p.getOfficeVisitId());
pstring.setString(2, p.getCode());
return pstring;
}
public MedicalProcedure get(long id) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetStatement(conn, id);
ResultSet results = pstring.executeQuery()) {
return loadSingle(results);
}
}
private PreparedStatement createGetStatement(Connection conn, long id) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM medicalProcedure, cptcode " +
"WHERE cptcode.code=medicalProcedure.cptCode " +
"AND id=?");
pstring.setLong(1, id);
return pstring;
}
private MedicalProcedure loadSingle(ResultSet results) throws SQLException {
if (results.next()){
MedicalProcedure loadedProc = new MedicalProcedure();
loadedProc.setId(results.getLong("id"));
loadedProc.setOfficeVisitId(results.getLong("visitId"));
loadedProc.setCptCode(new CPTCode(results.getString("code"), results.getString("name")));
return loadedProc;
} else {
return null;
}
}
public boolean update(MedicalProcedure p) throws SQLException{
try {
validator.validate(p);
} catch (FormValidationException e) {
throw new SQLException(e.getMessage());
}
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createUpdatePreparedStatement(conn, p);){
return pstring.executeUpdate() > 0;
}
}
private PreparedStatement createUpdatePreparedStatement(Connection conn, MedicalProcedure p) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("UPDATE medicalProcedure SET visitId=?, cptCode=? WHERE id=?");
pstring.setLong(1, p.getOfficeVisitId());
pstring.setString(2, p.getCode());
pstring.setLong(3, p.getId());
return pstring;
}
public boolean remove(long id) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createRemovePreparedStatement(conn, id);){
return pstring.executeUpdate() > 0;
}
}
private PreparedStatement createRemovePreparedStatement(Connection conn, long id) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("DELETE FROM medicalProcedure WHERE id=?");
pstring.setLong(1, id);
return pstring;
}
public List<MedicalProcedure> getMedicalProceduresForOfficeVisit(long officeVisitId) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createOVPreparedStatement(conn, officeVisitId);
ResultSet results = pstring.executeQuery()){
return loadRecords(results);
}
}
private PreparedStatement createOVPreparedStatement(Connection conn, long officeVisitId) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM medicalProcedure, cptCode WHERE medicalProcedure.cptCode=cptCode.code AND visitId=?");
pstring.setLong(1, officeVisitId);
return pstring;
}
private List<MedicalProcedure> loadRecords(ResultSet results) throws SQLException {
List<MedicalProcedure> list = new LinkedList<>();
while (results.next()){
MedicalProcedure temp = new MedicalProcedure();
temp.setId(results.getLong("id"));
temp.setOfficeVisitId(results.getLong("visitId"));
temp.setCptCode(new CPTCode(results.getString("cptCode"), results.getString("name")));
list.add(temp);
}
return list;
}
public String getCodeName(String code) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetCodeNamePreparedStatement(conn, code);
ResultSet rs = pstring.executeQuery()){
if (!rs.next())
return "";
return rs.getString("name");
}
}
private PreparedStatement createGetCodeNamePreparedStatement(Connection conn, String code) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT name FROM cptCode WHERE Code=?");
pstring.setString(1, code);
return pstring;
}
}
| 6,600
| 38.059172
| 159
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/medicalProcedure/MedicalProcedureValidator.java
|
package edu.ncsu.csc.itrust.model.medicalProcedure;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
public class MedicalProcedureValidator extends POJOValidator<MedicalProcedure>{
@Override
public void validate(MedicalProcedure obj) throws FormValidationException {
// nothing to validate
}
}
| 384
| 26.5
| 80
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/ndcode/NDCCode.java
|
package edu.ncsu.csc.itrust.model.ndcode;
public class NDCCode {
private String code;
private String description;
public NDCCode() {
}
public NDCCode(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString(){
return code + " - " + description;
}
}
| 645
| 19.83871
| 52
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/ndcode/NDCCodeMySQL.java
|
package edu.ncsu.csc.itrust.model.ndcode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
public class NDCCodeMySQL {
private DataSource ds;
NDCCodeValidator validator;
/**
* Standard constructor for use in deployment
* @throws DBException
*/
public NDCCodeMySQL() throws DBException {
validator = new NDCCodeValidator();
try {
this.ds = getDataSource();
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
}
protected DataSource getDataSource() throws NamingException {
Context ctx = new InitialContext();
return ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
}
/**
* Constructor for testing purposes
* @param ds The DataSource to use
*/
public NDCCodeMySQL(DataSource ds) {
validator = new NDCCodeValidator();
this.ds = ds;
}
/**
* Adds an NDCode to the database
*
* @param nd The NDCCode to add
* @return True if the NDCCode was successfully added
* @throws FormValidationException
* @throws SQLException
*/
public boolean add(NDCCode nd) throws FormValidationException, SQLException{
validator.validate(nd);
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createAddPreparedStatement(conn, nd);){
return pstring.executeUpdate() > 0;
} catch (MySQLIntegrityConstraintViolationException e){
return false;
}
}
/**
* A utility method used to create a PreparedStatement for the add() method
*
* @param conn The Connection to use
* @param nd The NDCCode that we're adding
* @return The new PreparedStatement
* @throws SQLException
*/
private PreparedStatement createAddPreparedStatement(Connection conn, NDCCode nd) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("INSERT INTO ndcodes(Code, Description) "
+ "VALUES(?, ?)");
pstring.setString(1, nd.getCode());
pstring.setString(2, nd.getDescription());
return pstring;
}
/**
* Deletes an NDCCode from the database
* @param nd The NDCCode to delete
* @return True if the record was successfully deleted
* @throws SQLException
*/
public boolean delete(NDCCode nd) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createDeletePreparedStatement(conn, nd);){
return pstring.executeUpdate() > 0;
}
}
/**
* A utility method used to create a PreparedStatement for the delete() method
*
* @param conn The Connection to use
* @param nd The NDCCode that we're deleting
* @return The new PreparedStatement
* @throws SQLException
*/
private PreparedStatement createDeletePreparedStatement(Connection conn, NDCCode nd) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("DELETE FROM ndcodes WHERE Code=?");
pstring.setString(1, nd.getCode());
return pstring;
}
/**
* Gets all NDCCode in the database
* @return A List<NDCCode> containing all NDCCode in the database
* @throws SQLException
*/
public List<NDCCode> getAll() throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetAllPreparedStatement(conn);
ResultSet rs = pstring.executeQuery()){
return loadResults(rs);
}
}
/**
* A utility method used to create a PreparedStatement for the getAll() method
*
* @param conn The Connection to use
* @return The new PreparedStatement
* @throws SQLException
*/
private PreparedStatement createGetAllPreparedStatement(Connection conn) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM ndcodes");
return pstring;
}
/**
* A utility method that loads all NDCCodes in a ResultSet
*
* @param rs The ResultSet to load from
* @return A List<NDCCode> of all NDCCodes from the ResultSet
* @throws SQLException
*/
private List<NDCCode> loadResults(ResultSet rs) throws SQLException {
List<NDCCode> codes = new ArrayList<>();
while (rs.next()){
NDCCode newNDCode = new NDCCode();
newNDCode.setCode(rs.getString("Code"));
newNDCode.setDescription(rs.getString("Description"));
codes.add(newNDCode);
}
return codes;
}
public NDCCode getByCode(String code) throws SQLException{
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createGetByCodePreparedStatement(conn, code);
ResultSet rs = pstring.executeQuery()){
return loadOneResult(rs);
}
}
private PreparedStatement createGetByCodePreparedStatement(Connection conn, String code) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM ndcodes WHERE Code=?");
pstring.setString(1, code);
return pstring;
}
private NDCCode loadOneResult(ResultSet rs) throws SQLException {
NDCCode code = null;
if (rs.next()){
code = new NDCCode();
code.setCode(rs.getString("Code"));
code.setDescription(rs.getString("Description"));
}
return code;
}
public boolean update(NDCCode toChange) throws FormValidationException, SQLException{
validator.validate(toChange);
try (Connection conn = ds.getConnection();
PreparedStatement pstring = createUpdatePreparedStatement(conn, toChange);){
return pstring.executeUpdate() > 0;
}
}
private PreparedStatement createUpdatePreparedStatement(Connection conn, NDCCode toChange) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("UPDATE ndcodes SET Description=? WHERE Code=?");
pstring.setString(1, toChange.getDescription());
pstring.setString(2, toChange.getCode());
return pstring;
}
public List<NDCCode> getCodesWithFilter(String filter) throws SQLException {
try (Connection conn = ds.getConnection();
PreparedStatement pstring = creategetCodesWithFilterPreparedStatement(conn, filter);
ResultSet rs = pstring.executeQuery()){
return loadResults(rs);
}
}
private PreparedStatement creategetCodesWithFilterPreparedStatement(Connection conn, String filter) throws SQLException {
PreparedStatement pstring = conn.prepareStatement("SELECT * FROM ndcodes WHERE Code LIKE ?");
pstring.setString(1, "%" + filter + "%");
return pstring;
}
}
| 7,486
| 34.995192
| 125
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/ndcode/NDCCodeValidator.java
|
package edu.ncsu.csc.itrust.model.ndcode;
import edu.ncsu.csc.itrust.exception.ErrorList;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
import edu.ncsu.csc.itrust.model.ValidationFormat;
public class NDCCodeValidator extends POJOValidator<NDCCode>{
@Override
public void validate(NDCCode obj) throws FormValidationException {
ErrorList errorList = new ErrorList();
// NDCCode
errorList.addIfNotNull(checkFormat("NDCCode", obj.getCode(), ValidationFormat.ND, false));
// Description
errorList.addIfNotNull(checkFormat("Description", obj.getDescription(), ValidationFormat.ND_CODE_DESCRIPTION, false));
if (errorList.hasErrors()) {
throw new FormValidationException(errorList);
}
}
}
| 849
| 31.692308
| 126
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/officeVisit/OfficeVisit.java
|
/**
*
*/
package edu.ncsu.csc.itrust.model.officeVisit;
import java.time.LocalDateTime;
import javax.faces.bean.ManagedBean;
/**
* @author seelder
*
*/
@ManagedBean(name="office_visit")
public class OfficeVisit {
private Long visitID;
private Long patientMID;
private LocalDateTime date;
private String locationID;
private Long apptTypeID;
private String notes;
private Boolean sendBill;
private Float height;
private Float length;
private Float weight;
private Float headCircumference;
private String bloodPressure;
private Integer hdl;
private Integer triglyceride;
private Integer ldl;
private Integer householdSmokingStatus;
private Integer patientSmokingStatus;
/**
* Enum for household smoking status in basic health metrics
*/
public enum HouseholdSmokingStatus {
NON_SMOKING_HOUSEHOLD(1, "Non-Smoking Household"),
OUTDOOR_SMOKERS(2, "Outdoor Smokers"),
INDOOR_SMOKERS(3, "Indoor Smokers"),
UNSELECTED(0, "Unselected");
private int id;
private String description;
HouseholdSmokingStatus(int id, String description) {
this.id = id;
this.description = description;
}
public static String getDesriptionById(int id) {
for(HouseholdSmokingStatus status: values()) {
if (status.id == id) {
return status.description;
}
}
return null;
}
}
/**
* Enum for patient smoking status in basic health metrics
*/
public enum PatientSmokingStatus {
CURRENT_EVERY_DAY_SMOKER(1, "Current Every Day Smoker"),
CURRENT_SOME_DAY_SMOKER(2, "Current Some Day Smoker"),
FORMER_SMOKER(3, "Former Smoker"),
NEVER_SMOKER(4, "Never Smoker"),
SMOKER_CURRENT_STATUS_UNKNOWN(5, "Smoker, current status unknown"),
UNKNOWN_IF_EVER_SMOKED(9, "Unknown if ever smoked"),
UNSELECTED(0, "Unselected");
private int id;
private String description;
PatientSmokingStatus(int id, String description) {
this.id = id;
this.description = description;
}
public static String getDesriptionById(int id) {
for(PatientSmokingStatus status: values()) {
if (status.id == id) {
return status.description;
}
}
return null;
}
}
/**
* Default constructor for OfficeVisit
*/
public OfficeVisit(){
sendBill = true;
}
/**
* @return the patientMID
*/
public Long getPatientMID() {
return patientMID;
}
/**
* @param patientID the patient MID to set
*/
public void setPatientMID(Long patientID) {
this.patientMID = patientID;
}
/**
* @return the date
*/
public LocalDateTime getDate() {
return date;
}
/**
* @param date the date of the office visit
*/
public void setDate(LocalDateTime date) {
this.date = date;
}
/**
* @return the locationID
*/
public String getLocationID() {
return locationID;
}
/**
* @param locationID the locationID to set
*/
public void setLocationID(String location) {
this.locationID = location;
}
/**
* @return the apptTypeID
*/
public Long getApptTypeID() {
return apptTypeID;
}
/**
* @param apptTypeID the apptTypeID to set
*/
public void setApptTypeID(Long apptType) {
this.apptTypeID = apptType;
}
public Long getVisitID() {
return visitID;
}
public void setVisitID(Long visitID) {
this.visitID = visitID;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Boolean getSendBill() {
return sendBill;
}
public void setSendBill(Boolean sendBill) {
this.sendBill = sendBill;
}
/**
* Returns the Height recorded at the office visit.
*
* @return the Height recorded at the office visit.
*/
public Float getHeight() {
return height;
}
/**
* Sets the height recorded at the office visit.
*
* @param height
* The height recorded at the office visit
*/
public void setHeight(Float height) {
this.height = height;
}
/**
* Gets the length recorded at the office visit.
*
* @param length
* The height recorded at the office visit
*/
public Float getLength() {
return length;
}
/**
* Sets the length recorded at the office visit.
*
* @param length
* The height recorded at the office visit
*/
public void setLength(Float length) {
this.length = length;
}
/**
* Returns the weight recorded at the office visit.
*
* @return the weight recorded at the office visit.
*/
public Float getWeight() {
return weight;
}
/**
* @param weight
* the weight to set
*/
public void setWeight(Float weight) {
this.weight = weight;
}
/**
* Returns the head circumference measured at the office visit.
*
* @return the headCircumference
*/
public Float getHeadCircumference() {
return headCircumference;
}
/**
* @param headCircumference
* the headCircumference to set
*/
public void setHeadCircumference(Float headCircumference) {
this.headCircumference = headCircumference;
}
/**
* Returns the blood pressure measured at the office visit.
*
* @return the bloodPressure
*/
public String getBloodPressure() {
return bloodPressure;
}
/**
* @param bloodPressure
* the bloodPressure to set
*/
public void setBloodPressure(String bloodPressure) {
this.bloodPressure = bloodPressure;
}
/**
* Returns the HDL cholesterol level measured at the office visit.
*
* @return the hdl
*/
public Integer getHDL() {
return hdl;
}
/**
* @param hdl
* the hdl to set
*/
public void setHDL(Integer hdl) {
this.hdl = hdl;
}
/**
* Returns the triglyceride cholesterol level measured at the office visit.
*
* @return the triglyceride
*/
public Integer getTriglyceride() {
return triglyceride;
}
/**
* @param triglyceride
* the triglyceride to set
*/
public void setTriglyceride(Integer triglyceride) {
this.triglyceride = triglyceride;
}
/**
* Returns the LDL cholesterol level measured at the office visit.
*
* @return the ldl
*/
public Integer getLDL() {
return ldl;
}
/**
* @param ldl
* the ldl to set
*/
public void setLDL(Integer ldl) {
this.ldl = ldl;
}
/**
* Returns the household smoking status indicated at the office visit.
*
* @return the householdSmokingStatus
*/
public Integer getHouseholdSmokingStatus() {
return householdSmokingStatus;
}
/**
* @param householdSmokingStatus
* the householdSmokingStatus to set
*/
public void setHouseholdSmokingStatus(Integer householdSmokingStatus) {
this.householdSmokingStatus = householdSmokingStatus;
}
/**
* Returns the patient smoking status indicated at the office visit.
*
* @return the patientSmokingStatus
*/
public Integer getPatientSmokingStatus() {
return patientSmokingStatus;
}
/**
* @return string representation of patient smoking status in the format of:
* "id - description"
*/
public String getPatientSmokingStatusDescription() {
String description = PatientSmokingStatus.getDesriptionById(patientSmokingStatus);
if (description == null) {
return "";
}
return String.format("%d - %s", patientSmokingStatus, description);
}
/**
* @param patientSmokingStatus
* the patientSmokingStatus to set
*/
public void setPatientSmokingStatus(Integer patientSmokingStatus) {
this.patientSmokingStatus = patientSmokingStatus;
}
/**
* @return string representation of household smoking status in the format of:
* "id - description"
*/
public String getHouseholdSmokingStatusDescription() {
String description = HouseholdSmokingStatus.getDesriptionById(householdSmokingStatus);
if (description == null) {
return "";
}
return String.format("%d - %s", householdSmokingStatus, description);
}
/**
* Calculates adult/child patient's BMI according to patient's height and weight.
*
* @see http://extoxnet.orst.edu/faqs/dietcancer/web2/twohowto.html
* @return patient's BMI in 2 decimal places, "N/A" if patient's height or weight
* is uninitialized or invalid
*/
public String getAdultBMI() {
return getBMI(weight, height);
}
/**
* Calculates baby patient's BMI according to patient's height and length.
*
* @see http://extoxnet.orst.edu/faqs/dietcancer/web2/twohowto.html
* @return patient's BMI in 2 decimal places, "N/A" if patient's height or weight
* is uninitialized or invalid
*/
public String getBabyBMI() {
return getBMI(weight, length);
}
/**
* Calculates BMI according to provided height and weight.
*
* @see http://extoxnet.orst.edu/faqs/dietcancer/web2/twohowto.html
* @return BMI in 2 decimal places, "N/A" if given height or weight
* is uninitialized or invalid
*/
public static String getBMI(Float weight, Float height) {
if (weight == null || height == null || weight <= 0 || height <= 0) {
return "N/A";
}
return String.format("%.2f", weight * 0.45 / Math.pow(height * 0.025, 2));
}
}
| 8,940
| 20.64891
| 88
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/officeVisit/OfficeVisitData.java
|
package edu.ncsu.csc.itrust.model.officeVisit;
import java.time.LocalDate;
import java.util.List;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.DataBean;
public interface OfficeVisitData extends DataBean<OfficeVisit>{
public List<OfficeVisit> getVisitsForPatient(Long patientID) throws DBException;
/**
* Retrieves the patient's date of birth from database.
*
* @param patientMID
* MID of the patient
* @return patient's date of birth
*/
public LocalDate getPatientDOB(Long patientID);
/**
* Add office visit to the database and return the generated VisitID.
*
* @param ov
* Office visit to add to the database
* @return VisitID generated from the database insertion, -1 if nothing was generated
* @throws DBException if error occurred in inserting office visit
*/
public long addReturnGeneratedId(OfficeVisit ov) throws DBException;
}
| 919
| 28.677419
| 86
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/officeVisit/OfficeVisitMySQL.java
|
/**
*
*/
package edu.ncsu.csc.itrust.model.officeVisit;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.DBUtil;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.ValidationFormat;
/**
* @author seelder
*
*/
@ManagedBean
public class OfficeVisitMySQL implements Serializable, OfficeVisitData {
@Resource(name = "jdbc/itrust2")
private OfficeVisitSQLLoader ovLoader;
private static final long serialVersionUID = -8631210448583854595L;
private DataSource ds;
private OfficeVisitValidator validator;
/**
* Default constructor for OfficeVisitMySQL.
*
* @throws DBException if there is a context lookup naming exception
*/
public OfficeVisitMySQL() throws DBException {
ovLoader = new OfficeVisitSQLLoader();
try {
Context ctx = new InitialContext();
this.ds = ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust"));
} catch (NamingException e) {
throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage()));
}
validator = new OfficeVisitValidator(this.ds);
}
/**
* Constructor for testing.
*
* @param ds
*/
public OfficeVisitMySQL(DataSource ds) {
ovLoader = new OfficeVisitSQLLoader();
this.ds = ds;
validator = new OfficeVisitValidator(this.ds);
}
/**
* {@inheritDoc}
*/
@Override
public List<OfficeVisit> getVisitsForPatient(Long patientID) throws DBException {
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
if (ValidationFormat.NPMID.getRegex().matcher(Long.toString(patientID)).matches()) {
try {
conn = ds.getConnection();
pstring = conn.prepareStatement("SELECT * FROM officeVisit WHERE patientMID=?");
pstring.setLong(1, patientID);
results = pstring.executeQuery();
final List<OfficeVisit> visitList = ovLoader.loadList(results);
return visitList;
} catch (SQLException e) {
throw new DBException(e);
} finally {
try {
if (results != null) {
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(OfficeVisit ov) throws DBException {
return addReturnGeneratedId(ov) >= 0;
}
/**
* {@inheritDoc}
*/
@Override
public long addReturnGeneratedId(OfficeVisit ov) throws DBException {
Connection conn = null;
PreparedStatement pstring = null;
try {
validator.validate(ov);
} catch (FormValidationException e1) {
throw new DBException(new SQLException(e1.getMessage()));
}
long generatedId = -1;
try {
conn = ds.getConnection();
pstring = ovLoader.loadParameters(conn, pstring, ov, true);
int results = pstring.executeUpdate();
if (results != 0) {
ResultSet generatedKeys = pstring.getGeneratedKeys();
if(generatedKeys.next()) {
generatedId = generatedKeys.getLong(1);
}
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
return generatedId;
}
/**
* {@inheritDoc}
*/
@Override
public List<OfficeVisit> getAll() throws DBException {
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
try {
conn = ds.getConnection();
pstring = conn.prepareStatement("SELECT * FROM officeVisit");
results = pstring.executeQuery();
final List<OfficeVisit> visitList = ovLoader.loadList(results);
return visitList;
} catch (SQLException e) {
throw new DBException(e);
} finally {
try {
if (results != null) {
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public OfficeVisit getByID(long id) throws DBException {
OfficeVisit ret = null;
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
List<OfficeVisit> visitList = null;
try {
conn = ds.getConnection();
pstring = conn.prepareStatement("SELECT * FROM officeVisit WHERE visitID=?");
pstring.setLong(1, id);
results = pstring.executeQuery();
/* May update with loader instead */
visitList = ovLoader.loadList(results);
if (visitList.size() > 0) {
ret = visitList.get(0);
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
try {
if (results != null) {
results.close();
}
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
return ret;
}
/**
* {@inheritDoc}
*/
@Override
public boolean update(OfficeVisit ov) throws DBException {
boolean retval = false;
Connection conn = null;
PreparedStatement pstring = null;
try {
validator.validate(ov);
} catch (FormValidationException e1) {
throw new DBException(new SQLException(e1.getMessage()));
}
int results;
try {
conn = ds.getConnection();
pstring = ovLoader.loadParameters(conn, pstring, ov, false);
results = pstring.executeUpdate();
retval = (results > 0);
} catch (SQLException e) {
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, pstring);
}
return retval;
}
/**
* {@inheritDoc}
*/
public LocalDate getPatientDOB(final Long patientMID) {
Connection conn = null;
PreparedStatement pstring = null;
ResultSet results = null;
java.sql.Date patientDOB = null;
try {
conn = ds.getConnection();
pstring = conn.prepareStatement("SELECT DateOfBirth FROM patients WHERE MID=?");
pstring.setLong(1, patientMID);
results = pstring.executeQuery();
if (!results.next()) {
return null;
}
patientDOB = results.getDate("DateOfBirth");
} catch (SQLException e) {
return null;
} finally {
try {
if (results != null) {
results.close();
}
} catch (SQLException e) {
return null;
} finally {
DBUtil.closeConnection(conn, pstring);
}
}
if (patientDOB == null) {
return null;
}
return patientDOB.toLocalDate();
}
}
| 6,605
| 22.76259
| 97
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/officeVisit/OfficeVisitSQLLoader.java
|
package edu.ncsu.csc.itrust.model.officeVisit;
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.List;
import com.mysql.jdbc.Statement;
import edu.ncsu.csc.itrust.model.SQLLoader;
import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit;
public class OfficeVisitSQLLoader implements SQLLoader<OfficeVisit>{
/**
* {@inheritDoc}
*/
@Override
public List<OfficeVisit> loadList(ResultSet rs) throws SQLException {
ArrayList<OfficeVisit> list = new ArrayList<OfficeVisit>();
while (rs.next()) {
list.add(loadSingle(rs));
}
return list;
}
/**
* {@inheritDoc}
*/
@Override
public OfficeVisit loadSingle(ResultSet rs) throws SQLException {
OfficeVisit retVisit = new OfficeVisit();
retVisit.setVisitID(Long.parseLong(rs.getString("visitID")));
retVisit.setPatientMID(Long.parseLong(rs.getString("patientMID")));
retVisit.setLocationID(rs.getString("locationID"));
retVisit.setDate(rs.getTimestamp("visitDate").toLocalDateTime());
retVisit.setApptTypeID(rs.getLong("apptTypeID"));
retVisit.setNotes(rs.getString("notes"));
retVisit.setSendBill(rs.getBoolean("sendBill"));
// Load patient health metrics
retVisit.setHeight(getFloatOrNull(rs, "height"));
retVisit.setLength(getFloatOrNull(rs, "length"));
retVisit.setWeight(getFloatOrNull(rs, "weight"));
retVisit.setHeadCircumference(getFloatOrNull(rs, "head_circumference"));
retVisit.setBloodPressure(rs.getString("blood_pressure"));
retVisit.setHDL(getIntOrNull(rs, "hdl"));
retVisit.setTriglyceride(getIntOrNull(rs, "triglyceride"));
retVisit.setLDL(getIntOrNull(rs, "ldl"));
retVisit.setHouseholdSmokingStatus(getIntOrNull(rs, "household_smoking_status"));
retVisit.setPatientSmokingStatus(getIntOrNull(rs, "patient_smoking_status"));
return retVisit;
}
/**
* {@inheritDoc}
*/
@Override
public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, OfficeVisit ov, boolean newInstance)
throws SQLException {
String stmt = "";
if (newInstance) {
stmt = "INSERT INTO officeVisit(patientMID, visitDate, locationID, apptTypeID, notes, sendBill, height, length, weight,"
+ "head_circumference, blood_pressure, hdl, triglyceride, ldl, household_smoking_status, patient_smoking_status) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
} else {
long id = ov.getVisitID();
stmt = "UPDATE officeVisit SET patientMID=?, "
+ "visitDate=?, "
+ "locationID=?, "
+ "apptTypeID=?, "
+ "notes=?, "
+ "sendBill=?, "
+ "height=?, "
+ "length=?, "
+ "weight=?, "
+ "head_circumference=?, "
+ "blood_pressure=?, "
+ "hdl=?, "
+ "triglyceride=?, "
+ "ldl=?, "
+ "household_smoking_status=?, "
+ "patient_smoking_status=? "
+ "WHERE visitID=" + id + ";";
}
ps = conn.prepareStatement(stmt, Statement.RETURN_GENERATED_KEYS);
ps.setLong(1, ov.getPatientMID());
Timestamp ts = Timestamp.valueOf(ov.getDate());
ps.setTimestamp(2, ts);
ps.setString(3, ov.getLocationID());
ps.setLong(4, ov.getApptTypeID());
String noteText = "";
if (ov.getNotes() != (null)){
noteText = ov.getNotes();
}
ps.setString(5, noteText);
boolean bill = false;
if(ov.getSendBill() != null){
bill = ov.getSendBill();
}
ps.setBoolean(6, bill);
// Patient health metrics
setFloatOrNull(ps, 7, ov.getHeight());
setFloatOrNull(ps, 8, ov.getLength());
setFloatOrNull(ps, 9, ov.getWeight());
setFloatOrNull(ps, 10, ov.getHeadCircumference());
ps.setString(11, ov.getBloodPressure());
setIntOrNull(ps, 12, ov.getHDL());
setIntOrNull(ps, 13, ov.getTriglyceride());
setIntOrNull(ps, 14, ov.getLDL());
Integer hss = ov.getHouseholdSmokingStatus();
if (hss == null) {
hss = 0;
}
ps.setInt(15, hss);
Integer pss = ov.getPatientSmokingStatus();
if (pss == null) {
pss = 0;
}
ps.setInt(16, pss);
return ps;
}
/**
* Get the integer value if initialized in DB, otherwise get null.
*
* @param rs
* ResultSet object
* @param field
* name of DB attribute
* @return Integer value or null
* @throws SQLException when field doesn't exist in the result set
*/
public Integer getIntOrNull(ResultSet rs, String field) throws SQLException {
Integer ret = rs.getInt(field);
if (rs.wasNull()) {
ret = null;
}
return ret;
}
/**
* Get the float value if initialized in DB, otherwise get null.
*
* @param rs
* ResultSet object
* @param field
* name of DB attribute
* @return Float value or null
* @throws SQLException when field doesn't exist in the result set
*/
public Float getFloatOrNull(ResultSet rs, String field) throws SQLException {
Float ret = rs.getFloat(field);
if (rs.wasNull()) {
ret = null;
}
return ret;
}
/**
* Set integer placeholder in statement to a value or null
*
* @param ps
* PreparedStatement object
* @param index
* Index of placeholder in the prepared statement
* @param value
* Value to set to placeholder, the value may be null
* @throws SQLException
* When placeholder is invalid
*/
public void setIntOrNull(PreparedStatement ps, int index, Integer value) throws SQLException {
if (value == null) {
ps.setNull(index, java.sql.Types.INTEGER);
} else {
ps.setInt(index, value);
}
}
/**
* Set float placeholder in statement to a value or null
*
* @param ps
* PreparedStatement object
* @param index
* Index of placeholder in the prepared statement
* @param value
* Value to set to placeholder, the value may be null
* @throws SQLException
* When placeholder is invalid
*/
public void setFloatOrNull(PreparedStatement ps, int index, Float value) throws SQLException {
if (value == null) {
ps.setNull(index, java.sql.Types.FLOAT);
} else {
ps.setFloat(index, value);
}
}
}
| 6,002
| 27.316038
| 123
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/officeVisit/OfficeVisitValidator.java
|
package edu.ncsu.csc.itrust.model.officeVisit;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.sql.DataSource;
import edu.ncsu.csc.itrust.controller.officeVisit.OfficeVisitController;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.exception.ErrorList;
import edu.ncsu.csc.itrust.exception.FormValidationException;
import edu.ncsu.csc.itrust.model.POJOValidator;
import edu.ncsu.csc.itrust.model.ValidationFormat;
import edu.ncsu.csc.itrust.model.apptType.ApptTypeData;
import edu.ncsu.csc.itrust.model.apptType.ApptTypeMySQLConverter;
import edu.ncsu.csc.itrust.model.hospital.Hospital;
import edu.ncsu.csc.itrust.model.hospital.HospitalData;
import edu.ncsu.csc.itrust.model.hospital.HospitalMySQLConverter;
public class OfficeVisitValidator extends POJOValidator<OfficeVisit> {
private DataSource ds;
/**
* Default constructor for OfficeVisitValidator.
*/
public OfficeVisitValidator(DataSource ds) {
this.ds = ds;
}
/**
* Used to Validate an office visit object. If the validation does not
* succeed, a {@link FormValidationException} is thrown. only performs
* checks on the values stored in the object (e.g. Patient MID) Does NOT
* validate the format of the visit date and other attributes that are NOT
* stored in the object itself
*
* @param obj
* the Office Visit to be validated
*/
@Override
public void validate(OfficeVisit obj) throws FormValidationException {
OfficeVisitController ovc = new OfficeVisitController(ds);
ErrorList errorList = new ErrorList();
LocalDateTime date = obj.getDate();
Long patientMID = obj.getPatientMID();
if (patientMID == null) {
errorList.addIfNotNull("Cannot add office visit information: invalid patient MID");
throw new FormValidationException(errorList);
}
LocalDate patientDOB = ovc.getPatientDOB(patientMID);
if (patientDOB == null) {
errorList.addIfNotNull("Cannot add office visit information: patient does not have a birthday");
throw new FormValidationException(errorList);
}
if (date.toLocalDate().isBefore(patientDOB)) {
errorList.addIfNotNull("Date: date cannot be earlier than patient's birthday at " + patientDOB.format(DateTimeFormatter.ISO_DATE));
}
errorList.addIfNotNull(checkFormat("Patient MID", patientMID, ValidationFormat.NPMID, false));
errorList.addIfNotNull(checkFormat("Location ID", obj.getLocationID(), ValidationFormat.HOSPITAL_ID, false));
if (obj.getVisitID() != null) {
if (obj.getVisitID() <= 0) {
errorList.addIfNotNull("Visit ID: Invalid Visit ID");
}
}
Long apptTypeID = obj.getApptTypeID();
ApptTypeData atData = new ApptTypeMySQLConverter(ds);
String apptTypeName = "";
try {
apptTypeName = atData.getApptTypeName(apptTypeID);
} catch (DBException e) {
// Do nothing
}
if (apptTypeName.isEmpty()) {
errorList.addIfNotNull("Appointment Type: Invalid ApptType ID");
}
HospitalData hData = new HospitalMySQLConverter(ds);
Hospital temp = null;
try {
temp = hData.getHospitalByID(obj.getLocationID());
} catch (DBException e) {
// Do nothing
}
if (temp == null) {
errorList.addIfNotNull("Location: Invalid Hospital ID");
}
errorList.addIfNotNull(checkFormat("Weight", obj.getWeight(), ValidationFormat.WEIGHT_OV, true));
errorList.addIfNotNull(checkFormat("Household Smoking Status", obj.getHouseholdSmokingStatus(), ValidationFormat.HSS_OV, true));
if (ovc.isPatientABaby(patientMID, date)) {
errorList.addIfNotNull(checkFormat("Length", obj.getLength(), ValidationFormat.LENGTH_OV, true));
errorList.addIfNotNull(checkFormat("Head Circumference", obj.getHeadCircumference(), ValidationFormat.HEAD_CIRCUMFERENCE_OV, true));
}
if (ovc.isPatientAnAdult(patientMID, date) || ovc.isPatientAChild(patientMID, date)) {
errorList.addIfNotNull(checkFormat("Height", obj.getHeight(), ValidationFormat.HEIGHT_OV, true));
errorList.addIfNotNull(checkFormat("Blood Pressure", obj.getBloodPressure(), ValidationFormat.BLOOD_PRESSURE_OV, true));
}
if (ovc.isPatientAnAdult(patientMID, date)) {
errorList.addIfNotNull(checkFormat("Patient Smoking Status", obj.getPatientSmokingStatus(), ValidationFormat.PSS_OV, true));
errorList.addIfNotNull(checkFormat("HDL", obj.getHDL(), ValidationFormat.HDL_OV, true));
errorList.addIfNotNull(checkFormat("Triglyceride", obj.getTriglyceride(), ValidationFormat.TRIGLYCERIDE_OV, true));
errorList.addIfNotNull(checkFormat("LDL", obj.getLDL(), ValidationFormat.LDL_OV, true));
}
if (errorList.hasErrors()) {
throw new FormValidationException(errorList);
}
}
}
| 4,699
| 37.211382
| 135
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/AllergyBean.java
|
package edu.ncsu.csc.itrust.model.old.beans;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* A bean for storing data about Allergies.
*
* 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 AllergyBean {
private long id;
private long patientID;
private String description;
private String ndcode;
private Date firstFound;
/**
* Default constructor.
*/
public AllergyBean() {
}
/**
* Returns the description for the allergy.
*
* @return
*/
public String getDescription() {
return description;
}
/**
* Sets the description for the allergy.
*
* @param description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Returns the ND code for the allergy.
*
* @return
*/
public String getNDCode() {
return ndcode;
}
/**
* Sets the ND code for the allergy.
*
* @param ndcode
*/
public void setNDCode(String ndcode) {
this.ndcode = ndcode;
}
/**
* Returns the date the allergy was first found.
*
* @return
*/
public Date getFirstFound() {
if (firstFound == null) {
return null;
}
return (Date) firstFound.clone();
}
/**
* Sets the date the allergy was first found.
*
* @param firstFound
*/
public void setFirstFound(Date firstFound) {
if (null != firstFound)
this.firstFound = (Date) firstFound.clone();
else
this.firstFound = null;
}
/**
* Returns the allergy ID.
*
* @return
*/
public long getId() {
return id;
}
/**
* Sets the allergy ID.
*
* @param id
*/
public void setId(long id) {
this.id = id;
}
/**
* Returns the description of the allergy.
*/
@Override
public String toString() {
return this.description;
}
/**
* Returns the patient ID.
*
* @return
*/
public long getPatientID() {
return patientID;
}
/**
* Sets the patient ID.
*
* @param patientID
*/
public void setPatientID(long patientID) {
this.patientID = patientID;
}
/**
* Returns the date first found as a String.
*
* @return
*/
public String getFirstFoundStr() {
try {
return new SimpleDateFormat("MM/dd/yyyy").format(getFirstFound());
} catch (Exception e) {
return "";
}
}
}
| 2,497
| 16.109589
| 78
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/ApptBean.java
|
package edu.ncsu.csc.itrust.model.old.beans;
import java.io.Serializable;
import java.sql.Timestamp;
public class ApptBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1965704529780021183L;
private String apptType;
private int apptID;
private long patient;
private long hcp;
private Timestamp date;
private String comment;
private int price;
/**
* @return the price
*/
public int getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(int price) {
this.price = price;
}
/**
* @return the apptType
*/
public String getApptType() {
return apptType;
}
/**
* @param apptID the apptID to set
*/
public void setApptID(int apptID) {
this.apptID = apptID;
}
public int getApptID() {
return apptID;
}
/**
* @param apptType the apptType to set
*/
public void setApptType(String apptType) {
this.apptType = apptType;
}
/**
* @return the patient
*/
public long getPatient() {
return patient;
}
/**
* @param patient the patient to set
*/
public void setPatient(long patient) {
this.patient = patient;
}
/**
* @return the hcp
*/
public long getHcp() {
return hcp;
}
/**
* @param hcp the hcp to set
*/
public void setHcp(long hcp) {
this.hcp = hcp;
}
/**
* @return the date
*/
public Timestamp getDate() {
return (Timestamp) date.clone();
}
/**
* @param date the date to set
*/
public void setDate(Timestamp date) {
this.date = (Timestamp) date.clone();
}
/**
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* @param comment the comment to set
*/
public void setComment(String comment) {
this.comment = comment;
}
@Override
public int hashCode() {
return apptID; // any arbitrary constant will do
}
/**
* Returns true if both id's are equal. Probably needs more advance field by field checking.
*/
@Override public boolean equals(Object other) {
if ( this == other ){
return true;
}
if ( !(other instanceof ApptBean) ){
return false;
}
ApptBean otherAppt = (ApptBean)other;
return otherAppt.getApptID() == getApptID();
}
}
| 2,227
| 16.138462
| 93
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/ApptRequestBean.java
|
package edu.ncsu.csc.itrust.model.old.beans;
/**
* ApptRequestBean
*/
public class ApptRequestBean {
private ApptBean requestedAppt;
private Boolean status;
/**
* getRequestedAppt
* @return requestedAppt
*/
public ApptBean getRequestedAppt() {
return requestedAppt;
}
/**
* isPending
* @return status
*/
public boolean isPending() {
return status == null;
}
/**
* isAccepted
* @return status
*/
public boolean isAccepted() {
return status != null && status.booleanValue();
}
/**
* setRequestedAppt
* @param appt appt
*/
public void setRequestedAppt(ApptBean appt) {
requestedAppt = appt;
}
/**
* setPending
* @param pending pending
*/
public void setPending(boolean pending) {
if (pending) {
status = null;
} else {
status = Boolean.valueOf(false);
}
}
/**
* If setPending(false) has not been called before using this method, this method will have no effect.
*
* @param accepted accepted
*/
public void setAccepted(boolean accepted) {
if (status != null) {
status = Boolean.valueOf(accepted);
}
}
}
| 1,094
| 15.846154
| 103
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/ApptTypeBean.java
|
package edu.ncsu.csc.itrust.model.old.beans;
public class ApptTypeBean {
private String name;
private int duration;
private int price; //added for UC60
public ApptTypeBean() {
this.name = null;
this.duration = 0;
}
public ApptTypeBean(String name, int duration) {
this.name = name;
this.duration = duration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
| 675
| 14.72093
| 49
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/BillingBean.java
|
package edu.ncsu.csc.itrust.model.old.beans;
import java.sql.Timestamp;
import java.util.Date;
/**
* Stores information about a bill
*/
public class BillingBean {
public static final String SUBMITTED = "Submitted";
public static final String UNSUBMITTED = "Unsubmitted";
public static final String PENDING = "Pending";
public static final String APPROVED = "Approved";
public static final String DENIED = "Denied";
public static final int MAX_SUBMISSIONS = 2;
private int billID;
private int apptID;
private long patient;
private long hcp;
private int amt;
private String status;
private String ccHolderName = null;
private String billingAddress = null;
private String ccType = null;
private String ccNumber = null;
private String cvv = null;
private String insHolderName = null;
private String insID = null;
private String insProviderName = null;
private String insAddress1 = null;
private String insAddress2 = null;
private String insCity = null;
private String insState = null;
private String insZip = null;
private String insPhone = null;
private int submissions = 0;
private boolean isInsurance = false;
private Date billTime = null;
private Timestamp subTime = null;
/**
* @return the isInsurance
*/
public boolean isInsurance() {
return isInsurance;
}
/**
* @param isInsurance the isInsurance to set
*/
public void setInsurance(boolean isInsurance) {
this.isInsurance = isInsurance;
}
/**
* @return the ccHolderName
*/
public String getCcHolderName() {
return ccHolderName;
}
/**
* @param ccHolderName the ccHolderName to set
*/
public void setCcHolderName(String ccHolderName) {
this.ccHolderName = ccHolderName;
}
/**
* @return the billingAddress
*/
public String getBillingAddress() {
return billingAddress;
}
/**
* @param billingAddress the billingAddress to set
*/
public void setBillingAddress(String billingAddress) {
this.billingAddress = billingAddress;
}
/**
* @return the ccType
*/
public String getCcType() {
return ccType;
}
/**
* @param ccType the ccType to set
*/
public void setCcType(String ccType) {
this.ccType = ccType;
}
/**
* @return the ccNumber
*/
public String getCcNumber() {
return ccNumber;
}
/**
* @param ccNumber the ccNumber to set
*/
public void setCcNumber(String ccNumber) {
this.ccNumber = ccNumber;
}
/**
* @return the cvv
*/
public String getCvv() {
return cvv;
}
/**
* @param cvv the cvv to set
*/
public void setCvv(String cvv) {
this.cvv = cvv;
}
/**
* @return the insHolderName
*/
public String getInsHolderName() {
return insHolderName;
}
/**
* @param insHolderName the insHolderName to set
*/
public void setInsHolderName(String insHolderName) {
this.insHolderName = insHolderName;
}
/**
* @return the insID
*/
public String getInsID() {
return insID;
}
/**
* @param insID the insID to set
*/
public void setInsID(String insID) {
this.insID = insID;
}
/**
* @return the insProviderName
*/
public String getInsProviderName() {
return insProviderName;
}
/**
* @param insProviderName the insProviderName to set
*/
public void setInsProviderName(String insProviderName) {
this.insProviderName = insProviderName;
}
/**
* @return the insAddress1
*/
public String getInsAddress1() {
return insAddress1;
}
/**
* @param insAddress1 the insAddress1 to set
*/
public void setInsAddress1(String insAddress1) {
this.insAddress1 = insAddress1;
}
/**
* @return the insAddress2
*/
public String getInsAddress2() {
return insAddress2;
}
/**
* @param insAddress2 the insAddress2 to set
*/
public void setInsAddress2(String insAddress2) {
this.insAddress2 = insAddress2;
}
/**
* @return the insCity
*/
public String getInsCity() {
return insCity;
}
/**
* @param insCity the insCity to set
*/
public void setInsCity(String insCity) {
this.insCity = insCity;
}
/**
* @return the insState
*/
public String getInsState() {
return insState;
}
/**
* @param insState the insState to set
*/
public void setInsState(String insState) {
this.insState = insState;
}
/**
* @return the insZip
*/
public String getInsZip() {
return insZip;
}
/**
* @param insZip the insZip to set
*/
public void setInsZip(String insZip) {
this.insZip = insZip;
}
/**
* @return the insPhone
*/
public String getInsPhone() {
return insPhone;
}
/**
* @param insPhone the insPhone to set
*/
public void setInsPhone(String insPhone) {
this.insPhone = insPhone;
}
/**
* @return the billID
*/
public int getBillID() {
return billID;
}
/**
* @param billID the billID to set
*/
public void setBillID(int billID) {
this.billID = billID;
}
/**
* @return the apptID
*/
public int getApptID() {
return apptID;
}
/**
* @param apptID the apptID to set
*/
public void setApptID(int apptID) {
this.apptID = apptID;
}
/**
* @return the patient
*/
public long getPatient() {
return patient;
}
/**
* @param patient the patient to set
*/
public void setPatient(long patient) {
this.patient = patient;
}
/**
* @return the hcp
*/
public long getHcp() {
return hcp;
}
/**
* @param hcp the hcp to set
*/
public void setHcp(long hcp) {
this.hcp = hcp;
}
/**
* @return the amt
*/
public int getAmt() {
return amt;
}
/**
* @param amt the amt to set
*/
public void setAmt(int amt) {
this.amt = amt;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return the submissions
*/
public int getSubmissions() {
return submissions;
}
/**
* @param submissions the submissions to set
*/
public void setSubmissions(int submissions) {
this.submissions = submissions;
}
/**
* @return the billTime
*/
public Date getBillTime() {
return new Date(billTime.getTime());
}
/**
* @param billTime the billTime to set
*/
public void setBillTime(Date billTime) {
if(billTime != null)
this.billTime = new Date(billTime.getTime());
else
this.billTime = null;
}
/**
* @return the subTime
*/
public Timestamp getSubTime() {
return subTime != null ? new Timestamp(subTime.getTime()) : null;
}
/**
* @return the subDate
*/
public Date getSubDate(){
return subTime != null ? new Date(subTime.getTime()) : null;
}
/**
* @param subTime the subTime to set
*/
public void setSubTime(Timestamp subTime) {
if(subTime != null)
this.subTime = new Timestamp(subTime.getTime());
else
this.subTime = null;
}
}
| 6,675
| 18.294798
| 67
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/CustomComparator.java
|
package edu.ncsu.csc.itrust.model.old.beans;
import java.util.Comparator;
public class CustomComparator implements Comparator<PersonnelBean> {
@Override
public int compare(PersonnelBean bean1, PersonnelBean bean2)
{
return (int) (bean1.getMID() - bean2.getMID());
}
}
| 277
| 20.384615
| 68
|
java
|
iTrust
|
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/DistanceComparator.java
|
package edu.ncsu.csc.itrust.model.old.beans;
import java.util.Comparator;
import edu.ncsu.csc.itrust.action.ZipCodeAction;
import edu.ncsu.csc.itrust.exception.DBException;
public class DistanceComparator implements Comparator<PersonnelBean> {
ZipCodeAction action;
String patientZipCode;
@Override
public int compare(PersonnelBean bean1, PersonnelBean bean2)
{
try {
return action.calcDistance(bean1.getZip(), patientZipCode) - action.calcDistance(bean2.getZip(), patientZipCode);
} catch (DBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
public DistanceComparator(ZipCodeAction action, String patientZipCode)
{
this.action = action;
this.patientZipCode = patientZipCode;
}
}
| 768
| 23.806452
| 118
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.