Boolean returnType = false;
if (healthRecordIdToRemove != null)
{
PersistenceService persistenceSvc = PersistenceService.getInstance();
try {
if (! securityContext.isUserInRole(UserConfig.ROLE_PATIENT)) throw new Exception("Not in patient role for removing access");
EntityManager em = PersistenceService.getInstance().getEntityManager();
User userToDisallow = null;
User removingUser = null;
try {
persistenceSvc.beginTx();
//get user
userToDisallow = getUserById(userId);
removingUser = getAuthenticatedUser();
//TODO check we are owner of HR
//if HR owner == removingUser
//find the correct hr
List<HealthRecord> healthRecords = userToDisallow.getHealthRecords();
boolean shouldRemove = false;
HealthRecord toRemove = null;
//make sure we aren't removing ourself
if (removingUser.getUserId().compareTo(userId) == 0) {
shouldRemove = false;
logger.debug("Preventing self-removal attempt id1 {} id2 {}", userToDisallow.getUserId(), userId);
} else {
for (HealthRecord hr : healthRecords) {
//prepare to remove link
if (healthRecordIdToRemove.compareTo(hr.getHealthRecordId()) == 0) {
toRemove = hr;
logger.debug("Ready to remove healthRecord {} from user {}", hr, userToDisallow);
shouldRemove = true;
}
}
if ( toRemove == null) {
logger.error("Unable to find matching hr to remove");
}
}
if (shouldRemove) {
healthRecords.remove(toRemove);
userToDisallow.setHealthRecords(healthRecords);
em.flush();
persistenceSvc.commitTx();
returnType = true;
} else {
returnType = false;
persistenceSvc.rollbackTx();
}
}
catch (NoResultException ex) {
logger.error("Unable to find remove access for HRID: {}", healthRecordIdToRemove);
returnType = false;
}
}
catch (Exception ex) {
logger.error("removeAccess encountered exception: {}", ex);
returnType = false;
} finally {
persistenceSvc.close();
}
} else {
returnType = false;
}