Search in sources :

Example 31 with PersonDAO

use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.

the class ApplicationUtils method createPyramusStudent.

public static Student createPyramusStudent(Application application, Person person, StaffMember staffMember) {
    PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
    AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
    EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
    ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
    SchoolDAO schoolDAO = DAOFactory.getInstance().getSchoolDAO();
    ApplicationAttachmentDAO applicationAttachmentDAO = DAOFactory.getInstance().getApplicationAttachmentDAO();
    UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
    StudentStudyPeriodDAO studentStudyPeriodDAO = DAOFactory.getInstance().getStudentStudyPeriodDAO();
    JSONObject formData = JSONObject.fromObject(application.getFormData());
    if (StringUtils.isNotBlank(getFormValue(formData, "field-nettilukio_compulsory_enddate"))) {
        try {
            new SimpleDateFormat("d.M.yyyy").parse(getFormValue(formData, "field-nettilukio_compulsory_enddate"));
        } catch (ParseException e) {
            logger.severe(String.format("Invalid compulsory end date format in application entity %d", application.getId()));
            return null;
        }
    }
    if (person == null) {
        String birthdayStr = getFormValue(formData, "field-birthday");
        String ssnEnd = getFormValue(formData, "field-ssn-end");
        try {
            Date birthday = StringUtils.isEmpty(birthdayStr) ? null : new SimpleDateFormat("d.M.yyyy").parse(birthdayStr);
            String ssn = StringUtils.isBlank(ssnEnd) ? null : ApplicationUtils.constructSSN(birthdayStr, ssnEnd);
            Sex sex = ApplicationUtils.resolveGender(getFormValue(formData, "field-sex"));
            person = personDAO.create(birthday, ssn, sex, null, Boolean.FALSE);
        } catch (ParseException e) {
            logger.severe(String.format("Invalid birthday format in application entity %d", application.getId()));
            return null;
        }
    }
    // Determine correct study programme
    StudyProgramme studyProgramme = ApplicationUtils.resolveStudyProgramme(getFormValue(formData, "field-line"), getFormValue(formData, "field-foreign-line"), EnumUtils.getEnum(AlternativeLine.class, getFormValue(formData, "field-nettilukio_alternativelines")));
    if (studyProgramme == null) {
        logger.severe(String.format("Unable to resolve study programme of application entity %d", application.getId()));
        return null;
    }
    // Study time end plus one year (for Internetix students)
    Date studyTimeEnd = null;
    if (StringUtils.equals(getFormValue(formData, "field-line"), "aineopiskelu")) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR, 1);
        studyTimeEnd = c.getTime();
    }
    // #868: Non-contract school information (for Internetix students, if exists)
    String additionalInfo = null;
    if (StringUtils.equals(getFormValue(formData, "field-line"), "aineopiskelu")) {
        String contractSchoolName = getFormValue(formData, "field-internetix-contract-school-name");
        String contractSchoolMunicipality = getFormValue(formData, "field-internetix-contract-school-municipality");
        String contractSchoolContact = getFormValue(formData, "field-internetix-contract-school-contact");
        if (!StringUtils.isAnyEmpty(contractSchoolName, contractSchoolMunicipality, contractSchoolContact)) {
            additionalInfo = String.format("<p><strong>Muun kuin sopimusoppilaitoksen yhteystiedot:</strong><br/>%s (%s)<br/>%s</p>", contractSchoolName, contractSchoolMunicipality, StringUtils.replace(contractSchoolContact, "\n", "<br/>"));
        }
    }
    Date studyStartDate = new Date();
    // Create student
    Student student = studentDAO.create(person, getFormValue(formData, "field-first-names"), getFormValue(formData, "field-last-name"), getFormValue(formData, "field-nickname"), additionalInfo, studyTimeEnd, ApplicationUtils.resolveStudentActivityType(getFormValue(formData, "field-job")), ApplicationUtils.resolveStudentExaminationType(getFormValue(formData, "field-internetix-contract-school-degree")), // student educational level (entity)
    null, // education (string)
    null, ApplicationUtils.resolveNationality(getFormValue(formData, "field-nationality")), ApplicationUtils.resolveMunicipality(getFormValue(formData, "field-municipality")), ApplicationUtils.resolveLanguage(getFormValue(formData, "field-language")), ApplicationUtils.resolveSchool(getFormValue(formData, "field-internetix-contract-school")), studyProgramme, // curriculum (TODO can this be resolved?)
    null, // previous studies (double)
    null, // study start date
    studyStartDate, // study end date
    null, // study end reason
    null, // study end text
    null, // archived
    Boolean.FALSE);
    userVariableDAO.createDefaultValueVariables(student);
    // StudyPeriods
    String compulsoryStudies = getFormValue(formData, "field-nettilukio_compulsory");
    if (StringUtils.isNotBlank(compulsoryStudies)) {
        if (StringUtils.equals(compulsoryStudies, "compulsory")) {
            studentStudyPeriodDAO.create(student, studyStartDate, null, StudentStudyPeriodType.COMPULSORY_EDUCATION);
            String compulsoryEndDateStr = getFormValue(formData, "field-nettilukio_compulsory_enddate");
            if (StringUtils.isNotBlank(compulsoryEndDateStr)) {
                try {
                    Date compulsoryEndDate = StringUtils.isEmpty(compulsoryEndDateStr) ? null : new SimpleDateFormat("d.M.yyyy").parse(compulsoryEndDateStr);
                    studentStudyPeriodDAO.create(student, compulsoryEndDate, null, StudentStudyPeriodType.NON_COMPULSORY_EDUCATION);
                } catch (ParseException e) {
                    logger.severe(String.format("Invalid compulsory end date format in application entity %d", application.getId()));
                    return null;
                }
            }
        } else if (StringUtils.equals(compulsoryStudies, "non_compulsory")) {
            studentStudyPeriodDAO.create(student, studyStartDate, null, StudentStudyPeriodType.NON_COMPULSORY_EDUCATION);
        }
    }
    // #1079: Aineopiskelu; yleissivistävä koulutustausta
    String internetixStudies = getFormValue(formData, "field-previous-studies-aineopiskelu");
    if (StringUtils.isNotBlank(internetixStudies)) {
        if (StringUtils.equals(internetixStudies, "perus")) {
            student = studentDAO.updateEducation(student, "Yleissivistävä koulutustausta: peruskoulu");
        } else if (StringUtils.equals(internetixStudies, "lukio")) {
            student = studentDAO.updateEducation(student, "Yleissivistävä koulutustausta: lukio");
        } else if (StringUtils.equals(internetixStudies, "ei")) {
            student = studentDAO.updateEducation(student, "Yleissivistävä koulutustausta: ei mitään");
        }
    }
    // Main contact type
    // Koti (unique)
    ContactType contactType = contactTypeDAO.findById(1L);
    // Attach email
    String email = StringUtils.lowerCase(StringUtils.trim(getFormValue(formData, "field-email")));
    logger.info(String.format("Attaching primary email %s", email));
    emailDAO.create(student.getContactInfo(), contactType, Boolean.TRUE, email);
    // Attach address
    addressDAO.create(student.getContactInfo(), contactType, String.format("%s %s", getFormValue(formData, "field-nickname"), getFormValue(formData, "field-last-name")), getFormValue(formData, "field-street-address"), getFormValue(formData, "field-zip-code"), getFormValue(formData, "field-city"), getFormValue(formData, "field-country"), Boolean.TRUE);
    // Attach phone
    phoneNumberDAO.create(student.getContactInfo(), contactType, Boolean.TRUE, getFormValue(formData, "field-phone"));
    // Guardian info (if email is present, all other fields are required and present, too)
    email = StringUtils.lowerCase(StringUtils.trim(getFormValue(formData, "field-underage-email")));
    if (!StringUtils.isBlank(email)) {
        // Attach email
        logger.info(String.format("Attaching guardian email %s", email));
        // Yhteyshenkilö (non-unique)
        contactType = contactTypeDAO.findById(5L);
        emailDAO.create(student.getContactInfo(), contactType, Boolean.FALSE, email);
        // Attach address
        addressDAO.create(student.getContactInfo(), contactType, String.format("%s %s", getFormValue(formData, "field-underage-first-name"), getFormValue(formData, "field-underage-last-name")), getFormValue(formData, "field-underage-street-address"), getFormValue(formData, "field-underage-zip-code"), getFormValue(formData, "field-underage-city"), getFormValue(formData, "field-underage-country"), Boolean.FALSE);
        // Attach phone
        phoneNumberDAO.create(student.getContactInfo(), contactType, Boolean.FALSE, getFormValue(formData, "field-underage-phone"));
    }
    // Contract school (Internetix students)
    String schoolId = getFormValue(formData, "field-internetix-contract-school");
    if (!NumberUtils.isNumber(schoolId)) {
        String customSchool = getFormValue(formData, "field-internetix-contract-school-name");
        if (!StringUtils.isBlank(customSchool)) {
            List<School> schools = schoolDAO.listByNameLowercaseAndArchived(customSchool, Boolean.FALSE);
            School school = schools.isEmpty() ? null : schools.get(0);
            if (school != null) {
                studentDAO.updateSchool(student, school);
                // #1003: add student to student group(s) based on school
                processSchoolStudentGroups(school, student);
            } else {
                String notification = "<b>Huom!</b> Opiskelijan ilmoittamaa oppilaitosta ei löydy vielä Pyramuksesta!";
                ApplicationLogDAO applicationLogDAO = DAOFactory.getInstance().getApplicationLogDAO();
                applicationLogDAO.create(application, ApplicationLogType.HTML, notification, null);
            }
        }
    }
    // Attachments
    List<ApplicationAttachment> attachments = applicationAttachmentDAO.listByApplicationId(application.getApplicationId());
    if (!attachments.isEmpty()) {
        String attachmentsFolder = SettingUtils.getSettingValue("applications.storagePath");
        if (StringUtils.isNotEmpty(attachmentsFolder)) {
            StudentFileDAO studentFileDAO = DAOFactory.getInstance().getStudentFileDAO();
            String applicationId = sanitizeFilename(application.getApplicationId());
            for (ApplicationAttachment attachment : attachments) {
                String attachmentFileName = sanitizeFilename(attachment.getName());
                try {
                    java.nio.file.Path path = Paths.get(attachmentsFolder, applicationId, attachmentFileName);
                    File file = path.toFile();
                    if (file.exists()) {
                        String fileId = null;
                        String contentType = Files.probeContentType(path);
                        byte[] data = FileUtils.readFileToByteArray(file);
                        if (PyramusFileUtils.isFileSystemStorageEnabled()) {
                            try {
                                fileId = PyramusFileUtils.generateFileId();
                                PyramusFileUtils.storeFile(student, fileId, data);
                                data = null;
                            } catch (IOException e) {
                                fileId = null;
                                logger.log(Level.WARNING, "Store user file to file system failed", e);
                            }
                        }
                        studentFileDAO.create(student, StringUtils.isBlank(attachment.getDescription()) ? attachmentFileName : attachment.getDescription(), attachmentFileName, fileId, // file type
                        null, contentType, data, staffMember);
                    }
                } catch (IOException e) {
                    logger.log(Level.WARNING, String.format("Exception processing attachment %s of application %d", attachment.getName(), application.getId()), e);
                }
            }
        }
    }
    return student;
}
Also used : ApplicationLogDAO(fi.otavanopisto.pyramus.dao.application.ApplicationLogDAO) PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) ContactType(fi.otavanopisto.pyramus.domainmodel.base.ContactType) StudyProgramme(fi.otavanopisto.pyramus.domainmodel.base.StudyProgramme) Sex(fi.otavanopisto.pyramus.domainmodel.students.Sex) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) School(fi.otavanopisto.pyramus.domainmodel.base.School) UserVariableDAO(fi.otavanopisto.pyramus.dao.users.UserVariableDAO) SchoolDAO(fi.otavanopisto.pyramus.dao.base.SchoolDAO) ContactTypeDAO(fi.otavanopisto.pyramus.dao.base.ContactTypeDAO) AddressDAO(fi.otavanopisto.pyramus.dao.base.AddressDAO) StudentStudyPeriodDAO(fi.otavanopisto.pyramus.dao.students.StudentStudyPeriodDAO) StudentFileDAO(fi.otavanopisto.pyramus.dao.file.StudentFileDAO) GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) ApplicationAttachmentDAO(fi.otavanopisto.pyramus.dao.application.ApplicationAttachmentDAO) IOException(java.io.IOException) Student(fi.otavanopisto.pyramus.domainmodel.students.Student) Date(java.util.Date) StudentDAO(fi.otavanopisto.pyramus.dao.students.StudentDAO) StudentGroupStudentDAO(fi.otavanopisto.pyramus.dao.students.StudentGroupStudentDAO) JSONObject(net.sf.json.JSONObject) ApplicationAttachment(fi.otavanopisto.pyramus.domainmodel.application.ApplicationAttachment) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Example 32 with PersonDAO

use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.

the class GoogleOauthAuthorizationStrategy method processLogin.

private User processLogin(String externalId, String email) throws AuthenticationException {
    UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    // Trim the email address
    email = email != null ? email.trim() : null;
    Person emailPerson = personDAO.findByUniqueEmail(email);
    if (emailPerson == null) {
        throw new LocalUserMissingException(email);
    }
    UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndExternalId(getName(), externalId);
    if (userIdentification != null) {
        // User has identified by this auth source before
        if (!emailPerson.getId().equals(userIdentification.getPerson().getId())) {
            throw new AuthenticationException(AuthenticationException.EMAIL_BELONGS_TO_ANOTHER_PERSON);
        }
    } else {
        userIdentificationDAO.create(emailPerson, getName(), externalId);
    }
    return emailPerson.getDefaultUser();
}
Also used : PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) LocalUserMissingException(fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) Person(fi.otavanopisto.pyramus.domainmodel.base.Person) UserIdentification(fi.otavanopisto.pyramus.domainmodel.users.UserIdentification) UserIdentificationDAO(fi.otavanopisto.pyramus.dao.users.UserIdentificationDAO)

Example 33 with PersonDAO

use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.

the class ListExistingPersonsJSONRequestController method process.

public void process(JSONRequestContext requestContext) {
    try {
        Long applicationEntityId = Long.valueOf(requestContext.getRequest().getParameter("applicationEntityId"));
        ApplicationDAO applicationDAO = DAOFactory.getInstance().getApplicationDAO();
        Application application = applicationDAO.findById(applicationEntityId);
        if (application == null) {
            requestContext.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        JSONObject applicationData = JSONObject.fromObject(application.getFormData());
        String ssn = ApplicationUtils.constructSSN(applicationData.getString("field-birthday"), applicationData.getString("field-ssn-end"));
        String emailAddress = StringUtils.lowerCase(StringUtils.trim(applicationData.getString("field-email")));
        EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
        PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
        UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
        Map<Long, Person> existingPersons = new HashMap<>();
        // Persons with email
        List<Email> emails = emailDAO.listByAddressLowercase(emailAddress);
        for (Email email : emails) {
            if (email.getContactType() == null || Boolean.FALSE.equals(email.getContactType().getNonUnique())) {
                User user = userDAO.findByContactInfo(email.getContactInfo());
                if (user != null) {
                    Person person = user.getPerson();
                    if (person != null) {
                        existingPersons.put(person.getId(), person);
                    }
                }
            }
        }
        if (!StringUtils.isBlank(ssn)) {
            List<Person> persons = personDAO.listBySSNUppercase(ssn);
            for (Person person : persons) {
                existingPersons.put(person.getId(), person);
            }
            // Persons with SSN ("wrong" delimiter)
            char[] ssnChars = ssn.toCharArray();
            ssnChars[6] = ssnChars[6] == 'A' ? '-' : 'A';
            ssn = ssnChars.toString();
            persons = personDAO.listBySSNUppercase(ssn);
            for (Person person : persons) {
                existingPersons.put(person.getId(), person);
            }
        }
        List<Map<String, Object>> results = new ArrayList<>();
        if (!existingPersons.isEmpty()) {
            for (Person person : existingPersons.values()) {
                Map<String, Object> personInfo = new HashMap<>();
                personInfo.put("id", person.getId());
                personInfo.put("name", person.getDefaultUser() == null ? "???" : person.getDefaultUser().getFullName());
                results.add(personInfo);
            }
        }
        requestContext.addResponseParameter("persons", results);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error loading existing students", e);
    }
}
Also used : Email(fi.otavanopisto.pyramus.domainmodel.base.Email) User(fi.otavanopisto.pyramus.domainmodel.users.User) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ApplicationDAO(fi.otavanopisto.pyramus.dao.application.ApplicationDAO) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) JSONObject(net.sf.json.JSONObject) UserDAO(fi.otavanopisto.pyramus.dao.users.UserDAO) JSONObject(net.sf.json.JSONObject) Application(fi.otavanopisto.pyramus.domainmodel.application.Application) Person(fi.otavanopisto.pyramus.domainmodel.base.Person) HashMap(java.util.HashMap) Map(java.util.Map)

Example 34 with PersonDAO

use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.

the class SaveKoskiOppijaBinaryRequestController method process.

public void process(BinaryRequestContext requestContext) {
    try {
        PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
        Long personId = requestContext.getLong("personId");
        if (personId == null) {
            logger.log(Level.WARNING, "Missing personId.");
            requestContext.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        Person person = personDAO.findById(personId);
        KoskiController koskiController = CDI.current().select(KoskiController.class).get();
        Oppija oppija = koskiController.personToOppija(person);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        String requestStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(oppija);
        requestContext.setResponseContent(requestStr.getBytes("UTF-8"), "application/json;charset=UTF-8");
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error loading person variables", e);
        throw new SmvcRuntimeException(e);
    }
}
Also used : PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) KoskiController(fi.otavanopisto.pyramus.koski.KoskiController) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) Oppija(fi.otavanopisto.pyramus.koski.model.Oppija) Person(fi.otavanopisto.pyramus.domainmodel.base.Person) SimpleDateFormat(java.text.SimpleDateFormat) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException)

Example 35 with PersonDAO

use of fi.otavanopisto.pyramus.dao.base.PersonDAO in project pyramus by otavanopisto.

the class CreateStudentJSONRequestController method process.

public void process(JSONRequestContext requestContext) {
    StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    StudentActivityTypeDAO activityTypeDAO = DAOFactory.getInstance().getStudentActivityTypeDAO();
    StudentExaminationTypeDAO examinationTypeDAO = DAOFactory.getInstance().getStudentExaminationTypeDAO();
    StudentEducationalLevelDAO educationalLevelDAO = DAOFactory.getInstance().getStudentEducationalLevelDAO();
    StudentStudyEndReasonDAO studyEndReasonDAO = DAOFactory.getInstance().getStudentStudyEndReasonDAO();
    UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
    LanguageDAO languageDAO = DAOFactory.getInstance().getLanguageDAO();
    MunicipalityDAO municipalityDAO = DAOFactory.getInstance().getMunicipalityDAO();
    NationalityDAO nationalityDAO = DAOFactory.getInstance().getNationalityDAO();
    SchoolDAO schoolDAO = DAOFactory.getInstance().getSchoolDAO();
    StudyProgrammeDAO studyProgrammeDAO = DAOFactory.getInstance().getStudyProgrammeDAO();
    AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
    ContactInfoDAO contactInfoDAO = DAOFactory.getInstance().getContactInfoDAO();
    EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
    PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
    TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
    ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
    CurriculumDAO curriculumDAO = DAOFactory.getInstance().getCurriculumDAO();
    StudentLodgingPeriodDAO lodgingPeriodDAO = DAOFactory.getInstance().getStudentLodgingPeriodDAO();
    StaffMemberDAO staffMemberDAO = DAOFactory.getInstance().getStaffMemberDAO();
    User loggedUser = staffMemberDAO.findById(requestContext.getLoggedUserId());
    Long personId = requestContext.getLong("personId");
    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, personId)) {
                throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.emailInUse"));
            }
        }
    }
    Date birthday = requestContext.getDate("birthday");
    String ssecId = requestContext.getString("ssecId");
    Sex sex = (Sex) requestContext.getEnum("gender", Sex.class);
    String basicInfo = requestContext.getString("basicInfo");
    Boolean secureInfo = requestContext.getBoolean("secureInfo");
    String firstName = StringUtils.trim(requestContext.getString("firstName"));
    String lastName = StringUtils.trim(requestContext.getString("lastName"));
    String nickname = StringUtils.trim(requestContext.getString("nickname"));
    String additionalInfo = requestContext.getString("additionalInfo");
    String otherContactInfo = requestContext.getString("otherContactInfo");
    String education = requestContext.getString("education");
    Double previousStudies = requestContext.getDouble("previousStudies");
    Date studyTimeEnd = requestContext.getDate("studyTimeEnd");
    Date studyStartTime = requestContext.getDate("studyStartDate");
    Date studyEndTime = requestContext.getDate("studyEndDate");
    String studyEndText = requestContext.getString("studyEndText");
    String tagsText = requestContext.getString("tags");
    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);
            }
        }
    }
    Long entityId = requestContext.getLong("language");
    Language language = entityId == null ? null : languageDAO.findById(entityId);
    entityId = requestContext.getLong("municipality");
    Municipality municipality = entityId == null ? null : municipalityDAO.findById(entityId);
    entityId = requestContext.getLong("activityType");
    StudentActivityType activityType = entityId == null ? null : activityTypeDAO.findById(entityId);
    entityId = requestContext.getLong("examinationType");
    StudentExaminationType examinationType = entityId == null ? null : examinationTypeDAO.findById(entityId);
    entityId = requestContext.getLong("educationalLevel");
    StudentEducationalLevel educationalLevel = entityId == null ? null : educationalLevelDAO.findById(entityId);
    entityId = requestContext.getLong("nationality");
    Nationality nationality = entityId == null ? null : nationalityDAO.findById(entityId);
    entityId = requestContext.getLong("school");
    School school = entityId != null && entityId > 0 ? schoolDAO.findById(entityId) : null;
    entityId = requestContext.getLong("studyProgramme");
    StudyProgramme studyProgramme = entityId != null && entityId > 0 ? studyProgrammeDAO.findById(entityId) : null;
    if (!UserUtils.canAccessOrganization(loggedUser, studyProgramme.getOrganization())) {
        throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Invalid studyprogramme.");
    }
    entityId = requestContext.getLong("studyEndReason");
    StudentStudyEndReason studyEndReason = entityId == null ? null : studyEndReasonDAO.findById(entityId);
    entityId = requestContext.getLong("curriculum");
    Curriculum curriculum = entityId == null ? null : curriculumDAO.findById(entityId);
    Person person = personId != null ? personDAO.findById(personId) : null;
    Person personBySSN = personDAO.findBySSN(ssecId);
    if (person == null) {
        if (personBySSN == null) {
            person = personDAO.create(birthday, ssecId, sex, basicInfo, secureInfo);
        } else {
            personDAO.update(personBySSN, birthday, ssecId, sex, basicInfo, secureInfo);
            person = personBySSN;
        }
    } else {
        personDAO.update(person, birthday, ssecId, sex, basicInfo, secureInfo);
    }
    Student student = studentDAO.create(person, firstName, lastName, nickname, additionalInfo, studyTimeEnd, activityType, examinationType, educationalLevel, education, nationality, municipality, language, school, studyProgramme, curriculum, previousStudies, studyStartTime, studyEndTime, studyEndReason, studyEndText, false);
    // Lodging periods
    Integer lodgingPeriodsCount = requestContext.getInteger("lodgingPeriodsTable.rowCount");
    if (lodgingPeriodsCount != null) {
        for (int i = 0; i < lodgingPeriodsCount; i++) {
            String colPrefix = "lodgingPeriodsTable." + i;
            Date begin = requestContext.getDate(colPrefix + ".begin");
            Date end = requestContext.getDate(colPrefix + ".end");
            lodgingPeriodDAO.create(student, begin, end);
        }
    }
    // Tags
    studentDAO.setStudentTags(student, tagEntities);
    if (person.getDefaultUser() == null) {
        personDAO.updateDefaultUser(person, student);
    }
    // Contact info
    contactInfoDAO.update(student.getContactInfo(), otherContactInfo);
    // Addresses
    int addressCount = requestContext.getInteger("addressTable.rowCount");
    for (int i = 0; i < addressCount; i++) {
        String colPrefix = "addressTable." + i;
        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 (hasAddress) {
            addressDAO.create(student.getContactInfo(), contactType, name, street, postal, city, country, defaultAddress);
        }
    }
    // Email addresses
    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"));
        if (StringUtils.isNotBlank(email)) {
            emailDAO.create(student.getContactInfo(), contactType, defaultAddress, email);
        }
    }
    // Phone numbers
    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");
        if (number != null) {
            phoneNumberDAO.create(student.getContactInfo(), contactType, defaultNumber, number);
        }
    }
    // Student variables, create the defaults first and modify if modified
    userVariableDAO.createDefaultValueVariables(student);
    Integer variableCount = requestContext.getInteger("variablesTable.rowCount");
    if (variableCount != null) {
        for (int i = 0; i < variableCount; i++) {
            String colPrefix = "variablesTable." + i;
            Long edited = requestContext.getLong(colPrefix + ".edited");
            if (Objects.equals(new Long(1), edited)) {
                String variableKey = requestContext.getRequest().getParameter(colPrefix + ".key");
                String variableValue = requestContext.getRequest().getParameter(colPrefix + ".value");
                userVariableDAO.setUserVariable(student, variableKey, variableValue);
            }
        }
    }
    // Contact information of a student won't be reflected to Person
    // used when searching students, so a manual re-index is needed
    personDAO.forceReindex(student.getPerson());
    String redirectURL = requestContext.getRequest().getContextPath() + "/students/editstudent.page?person=" + student.getPerson().getId();
    String refererAnchor = requestContext.getRefererAnchor();
    if (!StringUtils.isBlank(refererAnchor)) {
        redirectURL += "#" + refererAnchor;
    }
    requestContext.setRedirectURL(redirectURL);
}
Also used : ContactType(fi.otavanopisto.pyramus.domainmodel.base.ContactType) StudentStudyEndReason(fi.otavanopisto.pyramus.domainmodel.students.StudentStudyEndReason) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) StudentEducationalLevel(fi.otavanopisto.pyramus.domainmodel.students.StudentEducationalLevel) StudentLodgingPeriodDAO(fi.otavanopisto.pyramus.dao.students.StudentLodgingPeriodDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) MunicipalityDAO(fi.otavanopisto.pyramus.dao.base.MunicipalityDAO) StudentEducationalLevelDAO(fi.otavanopisto.pyramus.dao.students.StudentEducationalLevelDAO) HashSet(java.util.HashSet) Municipality(fi.otavanopisto.pyramus.domainmodel.base.Municipality) StudentExaminationType(fi.otavanopisto.pyramus.domainmodel.students.StudentExaminationType) LanguageDAO(fi.otavanopisto.pyramus.dao.base.LanguageDAO) NationalityDAO(fi.otavanopisto.pyramus.dao.base.NationalityDAO) StudentActivityTypeDAO(fi.otavanopisto.pyramus.dao.students.StudentActivityTypeDAO) Student(fi.otavanopisto.pyramus.domainmodel.students.Student) StudentDAO(fi.otavanopisto.pyramus.dao.students.StudentDAO) ContactInfoDAO(fi.otavanopisto.pyramus.dao.base.ContactInfoDAO) StudentActivityType(fi.otavanopisto.pyramus.domainmodel.students.StudentActivityType) Person(fi.otavanopisto.pyramus.domainmodel.base.Person) PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) User(fi.otavanopisto.pyramus.domainmodel.users.User) StudyProgramme(fi.otavanopisto.pyramus.domainmodel.base.StudyProgramme) Sex(fi.otavanopisto.pyramus.domainmodel.students.Sex) StudentStudyEndReasonDAO(fi.otavanopisto.pyramus.dao.students.StudentStudyEndReasonDAO) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) School(fi.otavanopisto.pyramus.domainmodel.base.School) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) Language(fi.otavanopisto.pyramus.domainmodel.base.Language) UserVariableDAO(fi.otavanopisto.pyramus.dao.users.UserVariableDAO) SchoolDAO(fi.otavanopisto.pyramus.dao.base.SchoolDAO) ContactTypeDAO(fi.otavanopisto.pyramus.dao.base.ContactTypeDAO) AddressDAO(fi.otavanopisto.pyramus.dao.base.AddressDAO) StudentExaminationTypeDAO(fi.otavanopisto.pyramus.dao.students.StudentExaminationTypeDAO) CurriculumDAO(fi.otavanopisto.pyramus.dao.base.CurriculumDAO) TagDAO(fi.otavanopisto.pyramus.dao.base.TagDAO) StudyProgrammeDAO(fi.otavanopisto.pyramus.dao.base.StudyProgrammeDAO) Date(java.util.Date) Nationality(fi.otavanopisto.pyramus.domainmodel.base.Nationality) Curriculum(fi.otavanopisto.pyramus.domainmodel.base.Curriculum) Tag(fi.otavanopisto.pyramus.domainmodel.base.Tag)

Aggregations

PersonDAO (fi.otavanopisto.pyramus.dao.base.PersonDAO)47 Person (fi.otavanopisto.pyramus.domainmodel.base.Person)42 Student (fi.otavanopisto.pyramus.domainmodel.students.Student)25 StudentDAO (fi.otavanopisto.pyramus.dao.students.StudentDAO)21 StaffMemberDAO (fi.otavanopisto.pyramus.dao.users.StaffMemberDAO)17 StaffMember (fi.otavanopisto.pyramus.domainmodel.users.StaffMember)14 User (fi.otavanopisto.pyramus.domainmodel.users.User)14 HashMap (java.util.HashMap)12 EmailDAO (fi.otavanopisto.pyramus.dao.base.EmailDAO)11 ContactTypeDAO (fi.otavanopisto.pyramus.dao.base.ContactTypeDAO)10 UserVariableDAO (fi.otavanopisto.pyramus.dao.users.UserVariableDAO)10 ContactType (fi.otavanopisto.pyramus.domainmodel.base.ContactType)10 StudyProgramme (fi.otavanopisto.pyramus.domainmodel.base.StudyProgramme)10 UserDAO (fi.otavanopisto.pyramus.dao.users.UserDAO)9 Language (fi.otavanopisto.pyramus.domainmodel.base.Language)9 Municipality (fi.otavanopisto.pyramus.domainmodel.base.Municipality)9 Nationality (fi.otavanopisto.pyramus.domainmodel.base.Nationality)9 School (fi.otavanopisto.pyramus.domainmodel.base.School)9 PhoneNumberDAO (fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO)8 StudyProgrammeDAO (fi.otavanopisto.pyramus.dao.base.StudyProgrammeDAO)8