Search in sources :

Example 31 with UserEntity

use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.

the class UserRESTService method searchUsers.

@GET
@Path("/users")
@RESTPermitUnimplemented
public Response searchUsers(@QueryParam("searchString") String searchString, @QueryParam("firstResult") @DefaultValue("0") Integer firstResult, @QueryParam("maxResults") @DefaultValue("10") Integer maxResults, @QueryParam("userGroupIds") List<Long> userGroupIds, @QueryParam("myUserGroups") Boolean myUserGroups, @QueryParam("workspaceIds") List<Long> workspaceIds, @QueryParam("myWorkspaces") Boolean myWorkspaces, @QueryParam("archetype") String archetype, @DefaultValue("false") @QueryParam("onlyDefaultUsers") Boolean onlyDefaultUsers) {
    if (!sessionController.isLoggedIn()) {
        return Response.status(Status.FORBIDDEN).build();
    }
    if (CollectionUtils.isNotEmpty(userGroupIds) && Boolean.TRUE.equals(myUserGroups))
        return Response.status(Status.BAD_REQUEST).build();
    if (CollectionUtils.isNotEmpty(workspaceIds) && Boolean.TRUE.equals(myWorkspaces))
        return Response.status(Status.BAD_REQUEST).build();
    UserEntity loggedUser = sessionController.getLoggedUserEntity();
    EnvironmentRoleArchetype roleArchetype = archetype != null ? EnvironmentRoleArchetype.valueOf(archetype) : null;
    Set<Long> userGroupFilters = null;
    Set<Long> workspaceFilters = null;
    if (!sessionController.hasEnvironmentPermission(RoleFeatures.ACCESS_ONLY_GROUP_STUDENTS)) {
        if ((myUserGroups != null) && myUserGroups) {
            userGroupFilters = new HashSet<Long>();
            // Groups where user is a member
            List<UserGroupEntity> userGroups = userGroupEntityController.listUserGroupsByUserIdentifier(sessionController.getLoggedUser());
            for (UserGroupEntity userGroup : userGroups) {
                userGroupFilters.add(userGroup.getId());
            }
        } else if (!CollectionUtils.isEmpty(userGroupIds)) {
            userGroupFilters = new HashSet<Long>();
            // Defined user groups
            userGroupFilters.addAll(userGroupIds);
        }
    } else {
        // User can only list users from his/her own user groups
        userGroupFilters = new HashSet<Long>();
        // Groups where user is a member and the ids of the groups
        List<UserGroupEntity> userGroups = userGroupEntityController.listUserGroupsByUserIdentifier(sessionController.getLoggedUser());
        Set<Long> accessibleUserGroupEntityIds = userGroups.stream().map(UserGroupEntity::getId).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(userGroupIds)) {
            // if there are specified user groups, they need to be subset of the groups that the user can access
            if (!CollectionUtils.isSubCollection(userGroupIds, accessibleUserGroupEntityIds))
                return Response.status(Status.BAD_REQUEST).build();
            userGroupFilters.addAll(userGroupIds);
        } else {
            userGroupFilters.addAll(accessibleUserGroupEntityIds);
        }
    }
    if ((myWorkspaces != null) && myWorkspaces) {
        // Workspaces where user is a member
        List<WorkspaceEntity> workspaces = workspaceUserEntityController.listWorkspaceEntitiesByUserEntity(loggedUser);
        Set<Long> myWorkspaceIds = new HashSet<Long>();
        for (WorkspaceEntity ws : workspaces) myWorkspaceIds.add(ws.getId());
        workspaceFilters = new HashSet<Long>(myWorkspaceIds);
    } else if (!CollectionUtils.isEmpty(workspaceIds)) {
        // Defined workspaces
        workspaceFilters = new HashSet<Long>(workspaceIds);
    }
    SearchProvider elasticSearchProvider = getProvider("elastic-search");
    if (elasticSearchProvider != null) {
        String[] fields = new String[] { "firstName", "lastName", "nickName", "email" };
        SearchResult result = elasticSearchProvider.searchUsers(searchString, fields, roleArchetype != null ? Arrays.asList(roleArchetype) : null, userGroupFilters, workspaceFilters, null, false, false, onlyDefaultUsers, firstResult, maxResults);
        List<Map<String, Object>> results = result.getResults();
        boolean hasImage = false;
        List<fi.otavanopisto.muikku.rest.model.User> ret = new ArrayList<fi.otavanopisto.muikku.rest.model.User>();
        if (!results.isEmpty()) {
            for (Map<String, Object> o : results) {
                String[] id = ((String) o.get("id")).split("/", 2);
                UserEntity userEntity = userEntityController.findUserEntityByDataSourceAndIdentifier(id[1], id[0]);
                if (userEntity != null) {
                    String emailAddress = userEmailEntityController.getUserDefaultEmailAddress(userEntity, true);
                    Date studyStartDate = getDateResult(o.get("studyStartDate"));
                    Date studyTimeEnd = getDateResult(o.get("studyTimeEnd"));
                    ret.add(new fi.otavanopisto.muikku.rest.model.User(userEntity.getId(), (String) o.get("firstName"), (String) o.get("lastName"), (String) o.get("nickName"), hasImage, (String) o.get("nationality"), (String) o.get("language"), (String) o.get("municipality"), (String) o.get("school"), emailAddress, studyStartDate, studyTimeEnd));
                }
            }
            return Response.ok(ret).build();
        } else
            return Response.noContent().build();
    }
    return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
Also used : User(fi.otavanopisto.muikku.schooldata.entity.User) EnvironmentUser(fi.otavanopisto.muikku.model.users.EnvironmentUser) EnvironmentRoleArchetype(fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UserGroupEntity(fi.otavanopisto.muikku.model.users.UserGroupEntity) SearchProvider(fi.otavanopisto.muikku.search.SearchProvider) SearchResult(fi.otavanopisto.muikku.search.SearchResult) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) WorkspaceUserEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity) Date(java.util.Date) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) RESTPermitUnimplemented(fi.otavanopisto.muikku.rest.RESTPermitUnimplemented) GET(javax.ws.rs.GET)

Example 32 with UserEntity

use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.

the class WorkspaceRESTService method listJournalEntries.

@GET
@Path("/workspaces/{WORKSPACEID}/journal")
@RESTPermit(handling = Handling.INLINE, requireLoggedIn = true)
public Response listJournalEntries(@PathParam("WORKSPACEID") Long workspaceEntityId, @QueryParam("userEntityId") Long userEntityId, @QueryParam("workspaceStudentId") String workspaceStudentId, @QueryParam("firstResult") @DefaultValue("0") Integer firstResult, @QueryParam("maxResults") @DefaultValue("25") Integer maxResults) {
    List<WorkspaceJournalEntry> entries = new ArrayList<>();
    List<WorkspaceJournalEntryRESTModel> result = new ArrayList<>();
    WorkspaceEntity workspaceEntity = workspaceController.findWorkspaceEntityById(workspaceEntityId);
    if (workspaceEntity == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    UserEntity userEntity = sessionController.getLoggedUserEntity();
    boolean canListAllEntries = sessionController.hasWorkspacePermission(MuikkuPermissions.LIST_ALL_JOURNAL_ENTRIES, workspaceEntity);
    if (workspaceStudentId == null && userEntityId == null && canListAllEntries) {
        List<WorkspaceUserEntity> workspaceUserEntities = workspaceUserEntityController.listActiveWorkspaceStudents(workspaceEntity);
        Set<UserEntity> userEntities = new HashSet<>();
        for (WorkspaceUserEntity workspaceUserEntity : workspaceUserEntities) {
            userEntities.add(workspaceUserEntity.getUserSchoolDataIdentifier().getUserEntity());
        }
        entries = workspaceJournalController.listEntriesForStudents(workspaceEntity, userEntities, firstResult, maxResults);
    } else {
        if (userEntityId != null) {
            // List by user entity (Muikku)
            if (!userEntityId.equals(userEntity.getId())) {
                if (canListAllEntries) {
                    userEntity = userEntityController.findUserEntityById(userEntityId);
                    if (userEntity == null) {
                        return Response.status(Status.NOT_FOUND).build();
                    }
                } else {
                    return Response.status(Status.FORBIDDEN).build();
                }
            }
        } else if (workspaceStudentId != null) {
            // List by workspace student (school data)
            SchoolDataIdentifier workspaceUserIdentifier = SchoolDataIdentifier.fromId(workspaceStudentId);
            if (workspaceUserIdentifier == null) {
                return Response.status(Status.BAD_REQUEST).entity("Invalid workspaceStudentId").build();
            }
            WorkspaceUserEntity workspaceUserEntity = workspaceUserEntityController.findWorkspaceUserEntityByWorkspaceUserIdentifierIncludeArchived(workspaceUserIdentifier);
            if (workspaceUserEntity == null) {
                return Response.status(Status.NOT_FOUND).build();
            }
            UserEntity userEntityFromWorkspaceUser = workspaceUserEntity.getUserSchoolDataIdentifier().getUserEntity();
            if (userEntityFromWorkspaceUser == null) {
                return Response.status(Status.NOT_FOUND).build();
            }
            if (!canListAllEntries) {
                if (!userEntity.getId().equals(userEntityFromWorkspaceUser.getId())) {
                    return Response.status(Status.FORBIDDEN).build();
                }
            } else {
                userEntity = userEntityFromWorkspaceUser;
            }
        }
        entries = workspaceJournalController.listEntriesByWorkspaceEntityAndUserEntity(workspaceEntity, userEntity, firstResult, maxResults);
    }
    for (WorkspaceJournalEntry entry : entries) {
        UserEntity entryUserEntity = userEntityController.findUserEntityById(entry.getUserEntityId());
        if (entryUserEntity != null) {
            User user = userController.findUserByUserEntityDefaults(entryUserEntity);
            if (user != null) {
                result.add(new WorkspaceJournalEntryRESTModel(entry.getId(), entry.getWorkspaceEntityId(), entry.getUserEntityId(), user.getFirstName(), user.getLastName(), entry.getHtml(), entry.getTitle(), entry.getCreated()));
            }
        }
    }
    return Response.ok(result).build();
}
Also used : WorkspaceJournalEntry(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceJournalEntry) SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) UserSchoolDataIdentifier(fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier) User(fi.otavanopisto.muikku.schooldata.entity.User) WorkspaceUser(fi.otavanopisto.muikku.schooldata.entity.WorkspaceUser) ArrayList(java.util.ArrayList) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) WorkspaceUserEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity) WorkspaceJournalEntryRESTModel(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceJournalEntryRESTModel) WorkspaceUserEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) GET(javax.ws.rs.GET)

Example 33 with UserEntity

use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.

the class WorkspaceForumRESTService method getWorkspaceForumStatistics.

@GET
@Path("/workspaces/{WORKSPACEENTITYID}/forumStatistics")
@RESTPermit(handling = Handling.INLINE)
public Response getWorkspaceForumStatistics(@PathParam("WORKSPACEENTITYID") Long workspaceEntityId, @QueryParam("userIdentifier") String userId) {
    WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceEntityById(workspaceEntityId);
    if (workspaceEntity == null) {
        return Response.status(Status.NOT_FOUND).entity(String.format("Workspace entity %d could not be found", workspaceEntityId)).build();
    }
    SchoolDataIdentifier userIdentifier = null;
    if (StringUtils.isNotBlank(userId)) {
        userIdentifier = SchoolDataIdentifier.fromId(userId);
    }
    if (userIdentifier == null) {
        return Response.status(Status.NOT_IMPLEMENTED).entity("Listing forum statistics for all users is not implemented yet").build();
    }
    UserEntity userEntity = userEntityController.findUserEntityByUserIdentifier(userIdentifier);
    if (userEntity == null) {
        return Response.status(Status.BAD_REQUEST).entity("Invalid userIdentifier").build();
    }
    if (!sessionController.hasWorkspacePermission(ForumResourcePermissionCollection.FORUM_FINDWORKSPACE_USERSTATISTICS, workspaceEntity)) {
        return Response.status(Status.FORBIDDEN).build();
    }
    Long messageCount = forumController.countUserEntityWorkspaceMessages(workspaceEntity, userEntity);
    ForumMessage latestMessage = forumController.findUserEntitysLatestWorkspaceMessage(workspaceEntity, userEntity);
    return Response.ok(new WorkspaceForumUserStatisticsRESTModel(messageCount, latestMessage != null ? latestMessage.getCreated() : null)).build();
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) ForumMessage(fi.otavanopisto.muikku.plugins.forum.model.ForumMessage) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) Path(javax.ws.rs.Path) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) GET(javax.ws.rs.GET)

Example 34 with UserEntity

use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.

the class TranscriptOfRecordsFileUploadServlet method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (!sessionController.isLoggedIn()) {
        sendResponse(resp, "Must be logged in", HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    if (!sessionController.hasEnvironmentPermission(TranscriptofRecordsPermissions.TRANSCRIPT_OF_RECORDS_FILE_UPLOAD)) {
        sendResponse(resp, "Insufficient permissions", HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    Part userIdentifierPart = req.getPart("userIdentifier");
    if (userIdentifierPart == null) {
        sendResponse(resp, "Missing userIdentifier", HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    String userIdentifier = "";
    try (InputStream is = userIdentifierPart.getInputStream()) {
        userIdentifier = IOUtils.toString(is, StandardCharsets.UTF_8);
    }
    SchoolDataIdentifier schoolDataIdentifier = SchoolDataIdentifier.fromId(userIdentifier);
    if (schoolDataIdentifier == null) {
        sendResponse(resp, "Invalid userIdentifier", HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    UserEntity userEntity = userEntityController.findUserEntityByUserIdentifier(schoolDataIdentifier);
    if (userEntity == null) {
        sendResponse(resp, "User entity not found", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Part titlePart = req.getPart("title");
    if (titlePart == null) {
        sendResponse(resp, "Missing title", HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    String title = "";
    try (InputStream is = titlePart.getInputStream()) {
        title = IOUtils.toString(is, StandardCharsets.UTF_8);
    }
    Part descriptionPart = req.getPart("description");
    if (descriptionPart == null) {
        sendResponse(resp, "Missing description", HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    String description = "";
    try (InputStream is = descriptionPart.getInputStream()) {
        description = IOUtils.toString(is, StandardCharsets.UTF_8);
    }
    Part uploadPart = req.getPart("upload");
    if (uploadPart == null) {
        sendResponse(resp, "Missing file", HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    String contentType = uploadPart.getContentType();
    long fileSizeLimit = systemSettingsController.getUploadFileSizeLimit();
    if (uploadPart.getSize() > fileSizeLimit) {
        sendResponse(resp, "File too large", HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    }
    try (InputStream is = uploadPart.getInputStream()) {
        TranscriptOfRecordsFile file = transcriptOfRecordsFileController.attachFile(userEntity, is, contentType, title, description);
        String result = (new ObjectMapper()).writeValueAsString(file);
        sendResponse(resp, result, HttpServletResponse.SC_OK);
    }
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) Part(javax.servlet.http.Part) InputStream(java.io.InputStream) TranscriptOfRecordsFile(fi.otavanopisto.muikku.plugins.transcriptofrecords.model.TranscriptOfRecordsFile) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 35 with UserEntity

use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.

the class TranscriptofRecordsBackingBean method init.

@RequestAction
public String init() {
    if (!sessionController.hasEnvironmentPermission(TranscriptofRecordsPermissions.TRANSCRIPT_OF_RECORDS_VIEW)) {
        return NavigationRules.ACCESS_DENIED;
    }
    Map<String, Grade> grades = new HashMap<>();
    List<GradingScale> gradingScales = gradingController.listGradingScales();
    for (GradingScale gradingScale : gradingScales) {
        List<GradingScaleItem> scaleItems = gradingController.listGradingScaleItems(gradingScale);
        for (GradingScaleItem scaleItem : scaleItems) {
            String id = StringUtils.join(new String[] { gradingScale.getSchoolDataSource(), gradingScale.getIdentifier(), scaleItem.getSchoolDataSource(), scaleItem.getIdentifier() }, '-');
            String grade = scaleItem.getName();
            String scale = gradingScale.getName();
            Boolean passing = scaleItem.isPassingGrade();
            grades.put(id, new Grade(grade, scale, passing));
        }
    }
    try {
        this.grades = new ObjectMapper().writeValueAsString(grades);
    } catch (JsonProcessingException e) {
        logger.log(Level.SEVERE, "Failed to serialize grades", e);
        return NavigationRules.INTERNAL_ERROR;
    }
    UserEntity loggedEntity = sessionController.getLoggedUserEntity();
    User user = userController.findUserByDataSourceAndIdentifier(sessionController.getLoggedUserSchoolDataSource(), sessionController.getLoggedUserIdentifier());
    studyStartDate = user.getStudyStartDate();
    studyTimeEnd = user.getStudyTimeEnd();
    studyTimeLeftStr = "";
    if (studyTimeEnd != null) {
        OffsetDateTime now = OffsetDateTime.now();
        Locale locale = sessionController.getLocale();
        if (now.isBefore(studyTimeEnd)) {
            long studyTimeLeftYears = now.until(studyTimeEnd, ChronoUnit.YEARS);
            now = now.plusYears(studyTimeLeftYears);
            if (studyTimeLeftYears > 0) {
                studyTimeLeftStr += studyTimeLeftYears + " " + localeController.getText(locale, "plugin.records.studyTimeEndShort.y");
            }
            long studyTimeLeftMonths = now.until(studyTimeEnd, ChronoUnit.MONTHS);
            now = now.plusMonths(studyTimeLeftMonths);
            if (studyTimeLeftMonths > 0) {
                if (studyTimeLeftStr.length() > 0)
                    studyTimeLeftStr += " ";
                studyTimeLeftStr += studyTimeLeftMonths + " " + localeController.getText(locale, "plugin.records.studyTimeEndShort.m");
            }
            long studyTimeLeftDays = now.until(studyTimeEnd, ChronoUnit.DAYS);
            now = now.plusDays(studyTimeLeftDays);
            if (studyTimeLeftDays > 0) {
                if (studyTimeLeftStr.length() > 0)
                    studyTimeLeftStr += " ";
                studyTimeLeftStr += studyTimeLeftDays + " " + localeController.getText(locale, "plugin.records.studyTimeEndShort.d");
            }
        }
    }
    List<TranscriptOfRecordsFile> transcriptOfRecordsFiles;
    if (loggedEntity != null) {
        transcriptOfRecordsFiles = transcriptOfRecordsFileController.listFiles(loggedEntity);
    } else {
        transcriptOfRecordsFiles = Collections.emptyList();
    }
    try {
        files = new ObjectMapper().writeValueAsString(transcriptOfRecordsFiles);
    } catch (JsonProcessingException e) {
        logger.log(Level.SEVERE, "Failed to serialize files", e);
        return NavigationRules.INTERNAL_ERROR;
    }
    return null;
}
Also used : Locale(java.util.Locale) GradingScale(fi.otavanopisto.muikku.schooldata.entity.GradingScale) User(fi.otavanopisto.muikku.schooldata.entity.User) HashMap(java.util.HashMap) GradingScaleItem(fi.otavanopisto.muikku.schooldata.entity.GradingScaleItem) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) OffsetDateTime(java.time.OffsetDateTime) TranscriptOfRecordsFile(fi.otavanopisto.muikku.plugins.transcriptofrecords.model.TranscriptOfRecordsFile) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RequestAction(org.ocpsoft.rewrite.annotation.RequestAction)

Aggregations

UserEntity (fi.otavanopisto.muikku.model.users.UserEntity)163 Path (javax.ws.rs.Path)101 RESTPermit (fi.otavanopisto.security.rest.RESTPermit)88 WorkspaceUserEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity)65 GET (javax.ws.rs.GET)58 SchoolDataIdentifier (fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier)54 WorkspaceEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceEntity)50 User (fi.otavanopisto.muikku.schooldata.entity.User)36 ArrayList (java.util.ArrayList)35 UserSchoolDataIdentifier (fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier)27 POST (javax.ws.rs.POST)26 Date (java.util.Date)24 CommunicatorMessageId (fi.otavanopisto.muikku.plugins.communicator.model.CommunicatorMessageId)22 HashMap (java.util.HashMap)20 WorkspaceMaterial (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial)18 EnvironmentUser (fi.otavanopisto.muikku.model.users.EnvironmentUser)14 CommunicatorMessage (fi.otavanopisto.muikku.plugins.communicator.model.CommunicatorMessage)14 RESTPermitUnimplemented (fi.otavanopisto.muikku.rest.RESTPermitUnimplemented)13 UserGroupEntity (fi.otavanopisto.muikku.model.users.UserGroupEntity)12 PUT (javax.ws.rs.PUT)12