Search in sources :

Example 1 with OrganizationDAO

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

the class DebugDataViewController method process.

public void process(PageRequestContext requestContext) {
    StaffMemberDAO userDAO = DAOFactory.getInstance().getStaffMemberDAO();
    StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
    CourseDAO courseDAO = DAOFactory.getInstance().getCourseDAO();
    ModuleDAO moduleDAO = DAOFactory.getInstance().getModuleDAO();
    ProjectDAO projectDAO = DAOFactory.getInstance().getProjectDAO();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    CourseStateDAO courseStateDAO = DAOFactory.getInstance().getCourseStateDAO();
    ResourceCategoryDAO resourceCategoryDAO = DAOFactory.getInstance().getResourceCategoryDAO();
    MaterialResourceDAO materialResourceDAO = DAOFactory.getInstance().getMaterialResourceDAO();
    EducationalTimeUnitDAO educationalTimeUnitDAO = DAOFactory.getInstance().getEducationalTimeUnitDAO();
    OrganizationDAO organizationDAO = DAOFactory.getInstance().getOrganizationDAO();
    String type = requestContext.getRequest().getParameter("type");
    int count = Integer.parseInt(requestContext.getRequest().getParameter("count"));
    int start = 1;
    String s = requestContext.getRequest().getParameter("start");
    if (!StringUtils.isBlank(s)) {
        start = Integer.parseInt(s);
    }
    User user = userDAO.findById(requestContext.getLoggedUserId());
    if ("module".equals(type)) {
        for (int i = start; i < (start + count); i++) {
            EducationalTimeUnit etu = educationalTimeUnitDAO.findById(new Long(1));
            moduleDAO.create("Moduli " + i, null, null, new Double(10), etu, "KuvaustekstiƤ modulille " + i, null, user);
        }
    } else if ("course".equals(type)) {
        for (int i = start; i < (start + count); i++) {
            EducationalTimeUnit etu = educationalTimeUnitDAO.findById(new Long(1));
            CourseState courseState = courseStateDAO.findById(new Long(1));
            Organization organization = organizationDAO.findById(1L);
            courseDAO.create(moduleDAO.findById(new Long(1)), organization, "Kurssi " + i, "", courseState, null, null, null, null, null, new Double(10), etu, null, null, null, null, null, null, "KuvaustekstiƤ kurssille " + i, null, null, null, null, user);
        }
    } else if ("resource".equals(type)) {
        for (int i = start; i < (start + count); i++) {
            ResourceCategory resourceCategory = resourceCategoryDAO.findById(new Long(1));
            materialResourceDAO.create("Materiaaliresurssi " + i, resourceCategory, new Double(500));
        }
    } else if ("project".equals(type)) {
        for (int i = start; i < (start + count); i++) {
            EducationalTimeUnit etu = educationalTimeUnitDAO.findById(new Long(1));
            projectDAO.create("Projekti " + i, "KuvaustekstiƤ projektille " + i, new Double(10), etu, user);
        }
    } else if ("student".equals(type)) {
        for (int i = start; i < (start + count); i++) {
            Person person = personDAO.create(new Date(), "030310-123R", Sex.MALE, null, Boolean.FALSE);
            studentDAO.create(person, "Etunimi " + i, "Sukunimi " + i, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, false);
        }
    }
}
Also used : User(fi.otavanopisto.pyramus.domainmodel.users.User) Organization(fi.otavanopisto.pyramus.domainmodel.base.Organization) EducationalTimeUnitDAO(fi.otavanopisto.pyramus.dao.base.EducationalTimeUnitDAO) CourseDAO(fi.otavanopisto.pyramus.dao.courses.CourseDAO) ModuleDAO(fi.otavanopisto.pyramus.dao.modules.ModuleDAO) ResourceCategoryDAO(fi.otavanopisto.pyramus.dao.resources.ResourceCategoryDAO) ResourceCategory(fi.otavanopisto.pyramus.domainmodel.resources.ResourceCategory) Date(java.util.Date) StudentDAO(fi.otavanopisto.pyramus.dao.students.StudentDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) CourseStateDAO(fi.otavanopisto.pyramus.dao.courses.CourseStateDAO) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) MaterialResourceDAO(fi.otavanopisto.pyramus.dao.resources.MaterialResourceDAO) CourseState(fi.otavanopisto.pyramus.domainmodel.courses.CourseState) OrganizationDAO(fi.otavanopisto.pyramus.dao.base.OrganizationDAO) Person(fi.otavanopisto.pyramus.domainmodel.base.Person) ProjectDAO(fi.otavanopisto.pyramus.dao.projects.ProjectDAO) EducationalTimeUnit(fi.otavanopisto.pyramus.domainmodel.base.EducationalTimeUnit)

Example 2 with OrganizationDAO

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

the class EditStudentGroupJSONRequestController method process.

/**
 * Processes the request to edit a student group.
 *
 * @param requestContext
 *          The JSON request context
 */
public void process(JSONRequestContext requestContext) {
    StaffMemberDAO staffMemberDAO = DAOFactory.getInstance().getStaffMemberDAO();
    StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
    StudentGroupDAO studentGroupDAO = DAOFactory.getInstance().getStudentGroupDAO();
    StudentGroupStudentDAO studentGroupStudentDAO = DAOFactory.getInstance().getStudentGroupStudentDAO();
    StudentGroupUserDAO studentGroupUserDAO = DAOFactory.getInstance().getStudentGroupUserDAO();
    TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
    OrganizationDAO organizationDAO = DAOFactory.getInstance().getOrganizationDAO();
    // StudentGroup basic information
    String name = requestContext.getString("name");
    String description = requestContext.getString("description");
    Date beginDate = requestContext.getDate("beginDate");
    String tagsText = requestContext.getString("tags");
    Boolean guidanceGroup = requestContext.getBoolean("guidanceGroup");
    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);
            }
        }
    }
    StudentGroup studentGroup = studentGroupDAO.findById(requestContext.getLong("studentGroupId"));
    User loggedUser = staffMemberDAO.findById(requestContext.getLoggedUserId());
    if (!UserUtils.canAccessOrganization(loggedUser, studentGroup.getOrganization())) {
        throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Can not access student group from another organization.");
    }
    // Version check
    Long version = requestContext.getLong("version");
    if (!studentGroup.getVersion().equals(version))
        throw new StaleObjectStateException(StudentGroup.class.getName(), studentGroup.getId());
    Organization organization = organizationDAO.findById(requestContext.getLong("organizationId"));
    if (!UserUtils.canAccessOrganization(loggedUser, organization)) {
        throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Invalid organization.");
    }
    studentGroupDAO.update(studentGroup, organization, name, description, beginDate, guidanceGroup, loggedUser);
    // Tags
    studentGroupDAO.setStudentGroupTags(studentGroup, tagEntities);
    // Personnel
    StudentGroupUser[] users = studentGroup.getUsers().toArray(new StudentGroupUser[0]);
    StudentGroupStudent[] students = studentGroup.getStudents().toArray(new StudentGroupStudent[0]);
    Set<Long> removables = studentGroup.getUsers().stream().map(StudentGroupUser::getId).collect(Collectors.toSet());
    int rowCount = requestContext.getInteger("usersTable.rowCount").intValue();
    for (int i = 0; i < rowCount; i++) {
        String colPrefix = "usersTable." + i;
        Long userId = requestContext.getLong(colPrefix + ".userId");
        Long studentGroupUserId = requestContext.getLong(colPrefix + ".studentGroupUserId");
        StaffMember staffMember = staffMemberDAO.findById(userId);
        if (!UserUtils.canAccessOrganization(loggedUser, staffMember.getOrganization())) {
            throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Can not access student group from another organization.");
        }
        if (studentGroupUserId == null) {
            // New User
            studentGroupUserDAO.create(studentGroup, staffMember, loggedUser);
        } else {
            // Old User, still in list
            removables.remove(studentGroupUserId);
        }
    }
    // Remove the ones that were deleted from group
    for (int i = 0; i < users.length; i++) {
        if (removables.contains(users[i].getId())) {
            studentGroupUserDAO.remove(studentGroup, users[i], loggedUser);
        }
    }
    // Students
    removables = studentGroup.getStudents().stream().map(StudentGroupStudent::getId).collect(Collectors.toSet());
    rowCount = requestContext.getInteger("studentsTable.rowCount");
    for (int i = 0; i < rowCount; i++) {
        String colPrefix = "studentsTable." + i;
        Long studentId = requestContext.getLong(colPrefix + ".studentId");
        Long studentGroupStudentId = requestContext.getLong(colPrefix + ".studentGroupStudentId");
        Student student = studentDAO.findById(studentId);
        if (!UserUtils.canAccessOrganization(loggedUser, student.getOrganization())) {
            throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Can not access student from another organization.");
        }
        if (studentGroupStudentId == null) {
            // New Student
            studentGroupStudentDAO.create(studentGroup, student, loggedUser);
        } else {
            // Old User, still in list, we'll update if the student has changed student group
            removables.remove(studentGroupStudentId);
            StudentGroupStudent sgStudent = studentGroupStudentDAO.findById(studentGroupStudentId);
            if (!sgStudent.getStudent().getId().equals(studentId)) {
                studentGroupStudentDAO.update(sgStudent, studentDAO.findById(studentId), loggedUser);
            }
        }
    }
    // Remove the ones that were deleted from group
    for (int i = 0; i < students.length; i++) {
        if (removables.contains(students[i].getId())) {
            studentGroupStudentDAO.remove(studentGroup, students[i], loggedUser);
        }
    }
    requestContext.setRedirectURL(requestContext.getReferer(true));
}
Also used : User(fi.otavanopisto.pyramus.domainmodel.users.User) StudentGroupUser(fi.otavanopisto.pyramus.domainmodel.students.StudentGroupUser) Organization(fi.otavanopisto.pyramus.domainmodel.base.Organization) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) StudentGroupStudent(fi.otavanopisto.pyramus.domainmodel.students.StudentGroupStudent) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) StudentGroupStudentDAO(fi.otavanopisto.pyramus.dao.students.StudentGroupStudentDAO) OrganizationDAO(fi.otavanopisto.pyramus.dao.base.OrganizationDAO) HashSet(java.util.HashSet) StudentGroupUserDAO(fi.otavanopisto.pyramus.dao.students.StudentGroupUserDAO) TagDAO(fi.otavanopisto.pyramus.dao.base.TagDAO) Student(fi.otavanopisto.pyramus.domainmodel.students.Student) StudentGroupStudent(fi.otavanopisto.pyramus.domainmodel.students.StudentGroupStudent) Date(java.util.Date) StudentGroupStudentDAO(fi.otavanopisto.pyramus.dao.students.StudentGroupStudentDAO) StudentDAO(fi.otavanopisto.pyramus.dao.students.StudentDAO) StudentGroupDAO(fi.otavanopisto.pyramus.dao.students.StudentGroupDAO) Tag(fi.otavanopisto.pyramus.domainmodel.base.Tag) StudentGroupUser(fi.otavanopisto.pyramus.domainmodel.students.StudentGroupUser) StaleObjectStateException(org.hibernate.StaleObjectStateException) StudentGroup(fi.otavanopisto.pyramus.domainmodel.students.StudentGroup)

Example 3 with OrganizationDAO

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

the class SaveStudyProgrammesJSONRequestController method process.

public void process(JSONRequestContext jsonRequestContext) {
    StaffMemberDAO staffMemberDAO = DAOFactory.getInstance().getStaffMemberDAO();
    StudyProgrammeDAO studyProgrammeDAO = DAOFactory.getInstance().getStudyProgrammeDAO();
    StudyProgrammeCategoryDAO studyProgrammeCategoryDAO = DAOFactory.getInstance().getStudyProgrammeCategoryDAO();
    OrganizationDAO organizationDAO = DAOFactory.getInstance().getOrganizationDAO();
    StaffMember loggedUser = staffMemberDAO.findById(jsonRequestContext.getLoggedUserId());
    int rowCount = NumberUtils.createInteger(jsonRequestContext.getRequest().getParameter("studyProgrammesTable.rowCount")).intValue();
    for (int i = 0; i < rowCount; i++) {
        String colPrefix = "studyProgrammesTable." + i;
        boolean modified = jsonRequestContext.getInteger(colPrefix + ".modified") == 1;
        if (modified) {
            Long studyProgrammeId = jsonRequestContext.getLong(colPrefix + ".studyProgrammeId");
            String name = jsonRequestContext.getString(colPrefix + ".name");
            String code = jsonRequestContext.getString(colPrefix + ".code");
            Long categoryId = jsonRequestContext.getLong(colPrefix + ".category");
            Long organizationId = jsonRequestContext.getLong(colPrefix + ".organization");
            boolean hasEvaluationFees = StringUtils.equals("1", jsonRequestContext.getString(colPrefix + ".hasEvaluationFees"));
            StudyProgrammeCategory category = null;
            Organization organization = null;
            if (categoryId != null) {
                category = studyProgrammeCategoryDAO.findById(categoryId);
            }
            if (organizationId != null) {
                organization = organizationDAO.findById(organizationId);
            }
            if (!UserUtils.canAccessOrganization(loggedUser, organization)) {
                throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "No permission to assign organization to study programme.");
            }
            if (studyProgrammeId == -1) {
                studyProgrammeDAO.create(organization, name, category, code, hasEvaluationFees);
            } else {
                StudyProgramme studyProgramme = studyProgrammeDAO.findById(studyProgrammeId);
                if (!UserUtils.canAccessOrganization(loggedUser, studyProgramme.getOrganization())) {
                    throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Can not access study programme from another organization.");
                }
                studyProgrammeDAO.update(studyProgramme, organization, name, category, code, hasEvaluationFees);
            }
        }
    }
    jsonRequestContext.setRedirectURL(jsonRequestContext.getReferer(true));
}
Also used : Organization(fi.otavanopisto.pyramus.domainmodel.base.Organization) StudyProgramme(fi.otavanopisto.pyramus.domainmodel.base.StudyProgramme) StudyProgrammeCategory(fi.otavanopisto.pyramus.domainmodel.base.StudyProgrammeCategory) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) StudyProgrammeDAO(fi.otavanopisto.pyramus.dao.base.StudyProgrammeDAO) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) StudyProgrammeCategoryDAO(fi.otavanopisto.pyramus.dao.base.StudyProgrammeCategoryDAO) OrganizationDAO(fi.otavanopisto.pyramus.dao.base.OrganizationDAO)

Example 4 with OrganizationDAO

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

the class CreateUserJSONRequestController method process.

/**
 * Processes the request to create a new user. Simply gathers the fields submitted from the
 * web page and adds the user to the database.
 *
 * @param requestContext The JSON request context
 */
public void process(JSONRequestContext requestContext) {
    StaffMemberDAO userDAO = DAOFactory.getInstance().getStaffMemberDAO();
    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();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
    OrganizationDAO organizationDAO = DAOFactory.getInstance().getOrganizationDAO();
    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"));
            }
        }
    }
    // Fields from the web page
    String firstName = requestContext.getString("firstName");
    String lastName = requestContext.getString("lastName");
    String title = requestContext.getString("title");
    Role role = Role.getRole(requestContext.getInteger("role"));
    String tagsText = requestContext.getString("tags");
    String username = requestContext.getString("username");
    String password = requestContext.getString("password1");
    String password2 = requestContext.getString("password2");
    Long organizationId = requestContext.getLong("organizationId");
    User loggedUser = userDAO.findById(requestContext.getLoggedUserId());
    Organization organization = organizationId != null ? organizationDAO.findById(organizationId) : null;
    if (!UserUtils.canAccessOrganization(loggedUser, organization)) {
        throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Invalid organization.");
    }
    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);
            }
        }
    }
    // User
    Person person = personId != null ? personDAO.findById(personId) : personDAO.create(null, null, null, null, Boolean.FALSE);
    StaffMember user = userDAO.create(organization, firstName, lastName, role, person, false);
    if (title != null)
        userDAO.updateTitle(user, title);
    if (person.getDefaultUser() == null) {
        personDAO.updateDefaultUser(person, user);
    }
    if (AuthenticationProviderVault.getInstance().hasInternalStrategies()) {
        boolean usernameBlank = StringUtils.isBlank(username);
        boolean passwordBlank = StringUtils.isBlank(password);
        // TODO: Support multiple internal authentication sources
        if (!usernameBlank) {
            // #921: Check username
            InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
            InternalAuth internalAuth = internalAuthDAO.findByUsername(username);
            if (internalAuth != null) {
                throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.usernameInUse"));
            }
            InternalAuthenticationProvider internalAuthenticationProvider = AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders().get(0);
            if (!passwordBlank) {
                if (!password.equals(password2))
                    throw new SmvcRuntimeException(PyramusStatusCode.PASSWORD_MISMATCH, "Passwords don't match");
            }
            String externalId = internalAuthenticationProvider.createCredentials(username, password);
            userIdentificationDAO.create(person, internalAuthenticationProvider.getName(), externalId);
        }
    }
    // Tags
    userDAO.updateTags(user, tagEntities);
    // 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(user.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(user.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(user.getContactInfo(), contactType, defaultNumber, number);
        }
    }
    // Redirect to the Edit User view
    requestContext.setRedirectURL(requestContext.getRequest().getContextPath() + "/users/edituser.page?userId=" + user.getId());
}
Also used : PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) ContactType(fi.otavanopisto.pyramus.domainmodel.base.ContactType) User(fi.otavanopisto.pyramus.domainmodel.users.User) Organization(fi.otavanopisto.pyramus.domainmodel.base.Organization) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) InternalAuthenticationProvider(fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider) ContactTypeDAO(fi.otavanopisto.pyramus.dao.base.ContactTypeDAO) InternalAuth(fi.otavanopisto.pyramus.domainmodel.users.InternalAuth) OrganizationDAO(fi.otavanopisto.pyramus.dao.base.OrganizationDAO) AddressDAO(fi.otavanopisto.pyramus.dao.base.AddressDAO) UserIdentificationDAO(fi.otavanopisto.pyramus.dao.users.UserIdentificationDAO) HashSet(java.util.HashSet) TagDAO(fi.otavanopisto.pyramus.dao.base.TagDAO) UserRole(fi.otavanopisto.pyramus.framework.UserRole) Role(fi.otavanopisto.pyramus.domainmodel.users.Role) InternalAuthDAO(fi.otavanopisto.pyramus.dao.users.InternalAuthDAO) Tag(fi.otavanopisto.pyramus.domainmodel.base.Tag) Person(fi.otavanopisto.pyramus.domainmodel.base.Person)

Example 5 with OrganizationDAO

use of fi.otavanopisto.pyramus.dao.base.OrganizationDAO 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));
}
Also used : PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) Organization(fi.otavanopisto.pyramus.domainmodel.base.Organization) ContactType(fi.otavanopisto.pyramus.domainmodel.base.ContactType) Email(fi.otavanopisto.pyramus.domainmodel.base.Email) Address(fi.otavanopisto.pyramus.domainmodel.base.Address) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) UserVariableDAO(fi.otavanopisto.pyramus.dao.users.UserVariableDAO) InternalAuthenticationProvider(fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider) ContactTypeDAO(fi.otavanopisto.pyramus.dao.base.ContactTypeDAO) InternalAuth(fi.otavanopisto.pyramus.domainmodel.users.InternalAuth) OrganizationDAO(fi.otavanopisto.pyramus.dao.base.OrganizationDAO) AddressDAO(fi.otavanopisto.pyramus.dao.base.AddressDAO) UserIdentificationDAO(fi.otavanopisto.pyramus.dao.users.UserIdentificationDAO) HashSet(java.util.HashSet) TagDAO(fi.otavanopisto.pyramus.dao.base.TagDAO) HttpSession(javax.servlet.http.HttpSession) UserRole(fi.otavanopisto.pyramus.framework.UserRole) Role(fi.otavanopisto.pyramus.domainmodel.users.Role) InternalAuthDAO(fi.otavanopisto.pyramus.dao.users.InternalAuthDAO) PhoneNumber(fi.otavanopisto.pyramus.domainmodel.base.PhoneNumber) Tag(fi.otavanopisto.pyramus.domainmodel.base.Tag) UserIdentification(fi.otavanopisto.pyramus.domainmodel.users.UserIdentification)

Aggregations

OrganizationDAO (fi.otavanopisto.pyramus.dao.base.OrganizationDAO)20 Organization (fi.otavanopisto.pyramus.domainmodel.base.Organization)19 StaffMemberDAO (fi.otavanopisto.pyramus.dao.users.StaffMemberDAO)16 StaffMember (fi.otavanopisto.pyramus.domainmodel.users.StaffMember)14 Tag (fi.otavanopisto.pyramus.domainmodel.base.Tag)10 SmvcRuntimeException (fi.internetix.smvc.SmvcRuntimeException)8 StudentDAO (fi.otavanopisto.pyramus.dao.students.StudentDAO)7 StringAttributeComparator (fi.otavanopisto.pyramus.util.StringAttributeComparator)7 TagDAO (fi.otavanopisto.pyramus.dao.base.TagDAO)6 EducationTypeDAO (fi.otavanopisto.pyramus.dao.base.EducationTypeDAO)5 EducationalTimeUnitDAO (fi.otavanopisto.pyramus.dao.base.EducationalTimeUnitDAO)5 SubjectDAO (fi.otavanopisto.pyramus.dao.base.SubjectDAO)5 CourseDAO (fi.otavanopisto.pyramus.dao.courses.CourseDAO)5 CourseStateDAO (fi.otavanopisto.pyramus.dao.courses.CourseStateDAO)5 CourseTypeDAO (fi.otavanopisto.pyramus.dao.courses.CourseTypeDAO)5 ModuleDAO (fi.otavanopisto.pyramus.dao.modules.ModuleDAO)5 EducationType (fi.otavanopisto.pyramus.domainmodel.base.EducationType)5 Student (fi.otavanopisto.pyramus.domainmodel.students.Student)5 CurriculumDAO (fi.otavanopisto.pyramus.dao.base.CurriculumDAO)4 EducationSubtypeDAO (fi.otavanopisto.pyramus.dao.base.EducationSubtypeDAO)4