use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.
the class EditUserJSONRequestController method process.
/**
* Processes the request to edit an user. Simply gathers the fields submitted from the
* web page and updates the database.
*
* @param jsonRequestContext The JSON request context
*/
public void process(JSONRequestContext requestContext) {
StaffMemberDAO staffDAO = DAOFactory.getInstance().getStaffMemberDAO();
UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
OrganizationDAO organizationDAO = DAOFactory.getInstance().getOrganizationDAO();
Long loggedUserId = requestContext.getLoggedUserId();
StaffMember loggedUser = staffDAO.findById(loggedUserId);
Role loggedUserRole = loggedUser.getRole();
Long userId = requestContext.getLong("userId");
StaffMember user = staffDAO.findById(userId);
if (user.getOrganization() != null) {
// Check that the editing user has access to the organization
if (!UserUtils.canAccessOrganization(loggedUser, user.getOrganization())) {
throw new RuntimeException("Cannot access users' organization");
}
} else {
// Check that the editing user has generic access when users' organization is null
if (!UserUtils.canAccessAllOrganizations(loggedUser)) {
throw new RuntimeException("Cannot access users' organization");
}
}
String firstName = requestContext.getString("firstName");
String lastName = requestContext.getString("lastName");
String title = requestContext.getString("title");
Role role = Role.getRole(requestContext.getInteger("role").intValue());
String username = requestContext.getString("username");
String password = requestContext.getString("password1");
String password2 = requestContext.getString("password2");
String tagsText = requestContext.getString("tags");
Long organizationId = requestContext.getLong("organizationId");
Organization organization = null;
if (organizationId != null) {
organization = organizationDAO.findById(organizationId);
}
if (organization != null) {
// Check that the editing user has access to the organization
if (!UserUtils.canAccessOrganization(loggedUser, organization)) {
throw new RuntimeException("Cannot access organization");
}
} else {
// Check that the editing user can set the organization as null
if (!UserUtils.canAccessAllOrganizations(loggedUser)) {
throw new RuntimeException("Cannot access organization");
}
}
// #921: Check username
if (!StringUtils.isBlank(username)) {
InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
InternalAuth internalAuth = internalAuthDAO.findByUsername(username);
if (internalAuth != null) {
UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndExternalId("internal", internalAuth.getId().toString());
if (userIdentification != null && !user.getPerson().getId().equals(userIdentification.getPerson().getId())) {
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.usernameInUse"));
}
}
}
int emailCount2 = requestContext.getInteger("emailTable.rowCount");
for (int i = 0; i < emailCount2; i++) {
String colPrefix = "emailTable." + i;
String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
if (StringUtils.isNotBlank(email)) {
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
if (!UserUtils.isAllowedEmail(email, contactType, user.getPerson().getId())) {
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.emailInUse"));
}
}
}
Set<Tag> tagEntities = new HashSet<>();
if (!StringUtils.isBlank(tagsText)) {
List<String> tags = Arrays.asList(tagsText.split("[\\ ,]"));
for (String tag : tags) {
if (!StringUtils.isBlank(tag)) {
Tag tagEntity = tagDAO.findByText(tag.trim());
if (tagEntity == null)
tagEntity = tagDAO.create(tag);
tagEntities.add(tagEntity);
}
}
}
staffDAO.update(user, organization, firstName, lastName, role);
if (Role.ADMINISTRATOR.equals(loggedUserRole)) {
Integer propertyCount = requestContext.getInteger("propertiesTable.rowCount");
for (int i = 0; i < (propertyCount != null ? propertyCount : 0); i++) {
String colPrefix = "propertiesTable." + i;
String propertyKey = requestContext.getString(colPrefix + ".key");
String propertyValue = requestContext.getString(colPrefix + ".value");
if (StaffMemberProperties.isProperty(propertyKey)) {
user.getProperties().put(propertyKey, propertyValue);
}
}
}
staffDAO.updateTitle(user, title);
// SSN
String ssn = requestContext.getString("ssn");
String existingSsn = user.getPerson().getSocialSecurityNumber();
if (!StringUtils.equals(ssn, existingSsn)) {
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
personDAO.updateSocialSecurityNumber(user.getPerson(), ssn);
}
// Tags
staffDAO.updateTags(user, tagEntities);
// Addresses
Set<Long> existingAddresses = new HashSet<>();
int addressCount = requestContext.getInteger("addressTable.rowCount");
for (int i = 0; i < addressCount; i++) {
String colPrefix = "addressTable." + i;
Long addressId = requestContext.getLong(colPrefix + ".addressId");
Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String name = requestContext.getString(colPrefix + ".name");
String street = requestContext.getString(colPrefix + ".street");
String postal = requestContext.getString(colPrefix + ".postal");
String city = requestContext.getString(colPrefix + ".city");
String country = requestContext.getString(colPrefix + ".country");
boolean hasAddress = name != null || street != null || postal != null || city != null || country != null;
if (addressId == -1 && hasAddress) {
Address address = addressDAO.create(user.getContactInfo(), contactType, name, street, postal, city, country, defaultAddress);
existingAddresses.add(address.getId());
} else if (addressId > 0) {
Address address = addressDAO.findById(addressId);
if (hasAddress) {
existingAddresses.add(addressId);
addressDAO.update(address, defaultAddress, contactType, name, street, postal, city, country);
}
}
}
List<Address> addresses = user.getContactInfo().getAddresses();
for (int i = addresses.size() - 1; i >= 0; i--) {
Address address = addresses.get(i);
if (!existingAddresses.contains(address.getId())) {
addressDAO.delete(address);
}
}
// E-mail addresses
Set<Long> existingEmails = new HashSet<>();
int emailCount = requestContext.getInteger("emailTable.rowCount");
for (int i = 0; i < emailCount; i++) {
String colPrefix = "emailTable." + i;
Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
Long emailId = requestContext.getLong(colPrefix + ".emailId");
if (emailId == -1 && email != null) {
emailId = emailDAO.create(user.getContactInfo(), contactType, defaultAddress, email).getId();
existingEmails.add(emailId);
} else if (emailId > 0 && email != null) {
existingEmails.add(emailId);
emailDAO.update(emailDAO.findById(emailId), contactType, defaultAddress, email);
}
}
List<Email> emails = user.getContactInfo().getEmails();
for (int i = emails.size() - 1; i >= 0; i--) {
Email email = emails.get(i);
if (!existingEmails.contains(email.getId())) {
emailDAO.delete(email);
}
}
// Phone numbers
Set<Long> existingPhoneNumbers = new HashSet<>();
int phoneCount = requestContext.getInteger("phoneTable.rowCount");
for (int i = 0; i < phoneCount; i++) {
String colPrefix = "phoneTable." + i;
Boolean defaultNumber = requestContext.getBoolean(colPrefix + ".defaultNumber");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String number = requestContext.getString(colPrefix + ".phone");
Long phoneId = requestContext.getLong(colPrefix + ".phoneId");
if (phoneId == -1 && number != null) {
phoneId = phoneNumberDAO.create(user.getContactInfo(), contactType, defaultNumber, number).getId();
existingPhoneNumbers.add(phoneId);
} else if (phoneId > 0 && number != null) {
phoneNumberDAO.update(phoneNumberDAO.findById(phoneId), contactType, defaultNumber, number);
existingPhoneNumbers.add(phoneId);
}
}
List<PhoneNumber> phoneNumbers = user.getContactInfo().getPhoneNumbers();
for (int i = phoneNumbers.size() - 1; i >= 0; i--) {
PhoneNumber phoneNumber = phoneNumbers.get(i);
if (!existingPhoneNumbers.contains(phoneNumber.getId())) {
phoneNumberDAO.delete(phoneNumber);
}
}
if (Role.ADMINISTRATOR.equals(loggedUserRole)) {
Integer variableCount = requestContext.getInteger("variablesTable.rowCount");
for (int i = 0; i < (variableCount != null ? variableCount : 0); i++) {
String colPrefix = "variablesTable." + i;
String variableKey = requestContext.getString(colPrefix + ".key");
String variableValue = requestContext.getString(colPrefix + ".value");
userVariableDAO.setUserVariable(user, variableKey, variableValue);
}
}
boolean usernameBlank = StringUtils.isBlank(username);
boolean passwordBlank = StringUtils.isBlank(password);
if (!usernameBlank || !passwordBlank) {
if (!passwordBlank) {
if (!password.equals(password2))
throw new SmvcRuntimeException(PyramusStatusCode.PASSWORD_MISMATCH, "Passwords don't match");
}
// TODO: Support for multiple internal authentication providers
List<InternalAuthenticationProvider> internalAuthenticationProviders = AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders();
if (internalAuthenticationProviders.size() == 1) {
InternalAuthenticationProvider internalAuthenticationProvider = internalAuthenticationProviders.get(0);
if (internalAuthenticationProvider != null) {
UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndPerson(internalAuthenticationProvider.getName(), user.getPerson());
if (internalAuthenticationProvider.canUpdateCredentials()) {
if (userIdentification == null) {
String externalId = internalAuthenticationProvider.createCredentials(username, password);
userIdentificationDAO.create(user.getPerson(), internalAuthenticationProvider.getName(), externalId);
} else {
if ("-1".equals(userIdentification.getExternalId())) {
String externalId = internalAuthenticationProvider.createCredentials(username, password);
userIdentificationDAO.updateExternalId(userIdentification, externalId);
} else {
if (!StringUtils.isBlank(username))
internalAuthenticationProvider.updateUsername(userIdentification.getExternalId(), username);
if (!StringUtils.isBlank(password))
internalAuthenticationProvider.updatePassword(userIdentification.getExternalId(), password);
}
}
}
}
}
}
if (requestContext.getLoggedUserId().equals(user.getId())) {
user = staffDAO.findById(user.getId());
HttpSession session = requestContext.getRequest().getSession(true);
session.setAttribute("loggedUserName", user.getFullName());
session.setAttribute("loggedUserRole", Role.valueOf(user.getRole().name()));
}
requestContext.setRedirectURL(requestContext.getReferer(true));
}
use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.
the class SetDefaultUserJSONRequestController method process.
public void process(JSONRequestContext requestContext) {
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
Person person = personDAO.findById(requestContext.getLong("personId"));
User user = userDAO.findById(requestContext.getLong("userId"));
if (user.getPerson().getId().equals(person.getId()))
personDAO.updateDefaultUser(person, user);
requestContext.setRedirectURL(requestContext.getReferer(true));
}
use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.
the class StudentAPI method updateStudentPerson.
public void updateStudentPerson(Long studentId, Long personId) {
StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
Student student = studentDAO.findById(studentId);
Person person = personDAO.findById(personId);
studentDAO.updatePerson(student, person);
}
use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.
the class PersonAPI method findIdBySocialSecurityNumber.
public Long findIdBySocialSecurityNumber(String socialSecurityNumber) {
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
Person person = personDAO.findBySSN(socialSecurityNumber);
return person != null ? person.getId() : null;
}
use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.
the class ApplicationRESTService method createOrUpdateApplication.
@Path("/saveapplication")
@POST
@Unsecure
public Response createOrUpdateApplication(Object object, @HeaderParam("Referer") String referer) {
if (!isApplicationCall(referer)) {
return Response.status(Status.FORBIDDEN).build();
}
try {
JSONObject formData = JSONObject.fromObject(object);
String applicationId = formData.getString("field-application-id");
if (applicationId == null) {
logger.log(Level.WARNING, "Refusing application due to missing applicationId");
return Response.status(Status.BAD_REQUEST).build();
}
String line = formData.getString("field-line");
if (line == null) {
logger.log(Level.WARNING, "Refusing application due to missing line");
return Response.status(Status.BAD_REQUEST).build();
}
String firstName = formData.getString("field-first-names");
if (firstName == null) {
logger.log(Level.WARNING, "Refusing application due to missing first name");
return Response.status(Status.BAD_REQUEST).build();
}
String lastName = formData.getString("field-last-name");
if (lastName == null) {
logger.log(Level.WARNING, "Refusing application due to missing last name");
return Response.status(Status.BAD_REQUEST).build();
}
String email = StringUtils.lowerCase(StringUtils.trim(formData.getString("field-email")));
if (StringUtils.isBlank(email)) {
logger.log(Level.WARNING, "Refusing application due to missing email");
return Response.status(Status.BAD_REQUEST).build();
}
// Store application
Map<String, String> response = new HashMap<String, String>();
ApplicationDAO applicationDAO = DAOFactory.getInstance().getApplicationDAO();
Application application = applicationDAO.findByApplicationId(applicationId);
String referenceCode = ApplicationUtils.generateReferenceCode(lastName, application == null ? null : application.getReferenceCode());
// #765: Prevent multiple (active) applications with same e-mail
List<Application> existingApplications = applicationDAO.listByEmailAndArchived(email, Boolean.FALSE);
for (Application existingApplication : existingApplications) {
if (application != null && existingApplication.getId().equals(application.getId())) {
continue;
}
switch(existingApplication.getState()) {
case PENDING:
case PROCESSING:
case WAITING_STAFF_SIGNATURE:
case STAFF_SIGNED:
case APPROVED_BY_SCHOOL:
case APPROVED_BY_APPLICANT:
return Response.status(Status.CONFLICT).build();
default:
break;
}
}
if (application == null) {
application = applicationDAO.create(applicationId, line, firstName, lastName, email, referenceCode, formData.toString(), // applicantEditable (#769: Internetix applicants may not edit submitted data)
!StringUtils.equals(line, "aineopiskelu"), ApplicationState.PENDING);
logger.log(Level.INFO, String.format("Created new %s application with id %s", line, application.getApplicationId()));
// Automatic registration of new Internetix students
boolean autoRegistration = StringUtils.equals("aineopiskelu", line);
if (autoRegistration) {
Person person = null;
try {
person = ApplicationUtils.resolvePerson(application);
} catch (DuplicatePersonException dpe) {
autoRegistration = false;
}
autoRegistration = autoRegistration && person == null;
}
if (autoRegistration) {
Student student = ApplicationUtils.createPyramusStudent(application, null, null);
if (student != null) {
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
personDAO.updateDefaultUser(student.getPerson(), student);
String credentialToken = RandomStringUtils.randomAlphanumeric(32).toLowerCase();
application = applicationDAO.updateApplicationStudentAndCredentialToken(application, student, credentialToken);
application = applicationDAO.updateApplicationStateAsApplicant(application, ApplicationState.REGISTERED_AS_STUDENT);
application = applicationDAO.updateApplicantEditable(application, Boolean.FALSE);
ApplicationUtils.sendNotifications(application, httpRequest, null, true, null, true);
ApplicationUtils.mailCredentialsInfo(httpRequest, student, application);
response.put("autoRegistered", "true");
} else {
logger.log(Level.SEVERE, "Creating student for application %s failed. Falling back to manual processing");
newApplicationPostProcessing(application);
}
} else {
// If the application doesn't lead to auto-registration, send out the
// usual confirmation and notification e-mails about a new application
newApplicationPostProcessing(application);
}
} else {
String oldSurname = null;
boolean referenceCodeModified = false;
if (!StringUtils.equalsIgnoreCase(application.getLastName(), lastName)) {
referenceCodeModified = true;
oldSurname = application.getLastName();
referenceCode = ApplicationUtils.generateReferenceCode(lastName, application.getReferenceCode());
} else {
referenceCode = application.getReferenceCode();
}
boolean lineChanged = !StringUtils.equals(line, application.getLine());
String oldLine = application.getLine();
application = applicationDAO.update(application, line, firstName, lastName, email, referenceCode, formData.toString(), application.getState(), application.getApplicantEditable(), null);
logger.log(Level.INFO, String.format("Updated %s application with id %s", line, application.getApplicationId()));
modifiedApplicationPostProcessing(application);
if (lineChanged) {
String notification = String.format("Hakija vaihtoi hakemustaan linjalta <b>%s</b> linjalle <b>%s</b>", ApplicationUtils.applicationLineUiValue(oldLine), ApplicationUtils.applicationLineUiValue(line));
ApplicationLogDAO applicationLogDAO = DAOFactory.getInstance().getApplicationLogDAO();
applicationLogDAO.create(application, ApplicationLogType.HTML, notification, null);
ApplicationUtils.sendNotifications(application, httpRequest, null, true, null, false);
}
if (referenceCodeModified) {
ApplicationUtils.sendApplicationModifiedMail(application, httpRequest, oldSurname);
}
}
if (formData.has("attachment-name") && formData.has("attachment-description")) {
ApplicationAttachmentDAO applicationAttachmentDAO = DAOFactory.getInstance().getApplicationAttachmentDAO();
if (JSONUtils.isArray(formData.get("attachment-name"))) {
JSONArray attachmentNames = formData.getJSONArray("attachment-name");
JSONArray attachmentDescriptions = formData.getJSONArray("attachment-description");
for (int i = 0; i < attachmentNames.size(); i++) {
String name = attachmentNames.getString(i);
String description = attachmentDescriptions.getString(i);
ApplicationAttachment applicationAttachment = applicationAttachmentDAO.findByApplicationIdAndName(applicationId, name);
if (applicationAttachment == null) {
logger.warning(String.format("Attachment %s for application %s not found", name, applicationId));
} else {
applicationAttachmentDAO.updateDescription(applicationAttachment, description);
}
}
} else {
String name = formData.getString("attachment-name");
String description = formData.getString("attachment-description");
ApplicationAttachment applicationAttachment = applicationAttachmentDAO.findByApplicationIdAndName(applicationId, name);
if (applicationAttachment == null) {
logger.warning(String.format("Attachment %s for application %s not found", name, applicationId));
} else {
applicationAttachmentDAO.updateDescription(applicationAttachment, description);
}
}
}
response.put("referenceCode", referenceCode);
return Response.ok(response).build();
} catch (JSONException e) {
logger.log(Level.SEVERE, String.format("Exception %s processing application json %s", e.getMessage(), object));
return Response.status(Status.BAD_REQUEST).build();
}
}
Aggregations