Search in sources :

Example 1 with SearchProvider

use of fi.otavanopisto.muikku.search.SearchProvider 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 2 with SearchProvider

use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.

the class TranscriptOfRecordsController method listWorkspaceIdentifiersBySubjectIdentifierAndCourseNumber.

public List<VopsWorkspace> listWorkspaceIdentifiersBySubjectIdentifierAndCourseNumber(String schoolDataSource, String subjectIdentifier, int courseNumber) {
    List<VopsWorkspace> retval = new ArrayList<>();
    SearchProvider searchProvider = getProvider("elastic-search");
    if (searchProvider != null) {
        SearchResult sr = searchProvider.searchWorkspaces(schoolDataSource, subjectIdentifier, courseNumber);
        List<Map<String, Object>> results = sr.getResults();
        for (Map<String, Object> result : results) {
            String searchId = (String) result.get("id");
            if (StringUtils.isNotBlank(searchId)) {
                String[] id = searchId.split("/", 2);
                if (id.length == 2) {
                    String dataSource = id[1];
                    String identifier = id[0];
                    String educationTypeId = (String) result.get("educationSubtypeIdentifier");
                    String name = (String) result.get("name");
                    String description = (String) result.get("description");
                    @SuppressWarnings("unchecked") ArrayList<String> curriculums = (ArrayList<String>) result.get("curriculumIdentifiers");
                    SchoolDataIdentifier workspaceIdentifier = new SchoolDataIdentifier(identifier, dataSource);
                    SchoolDataIdentifier educationSubtypeIdentifier = SchoolDataIdentifier.fromId(educationTypeId);
                    Set<SchoolDataIdentifier> curriculumIdentifiers = new HashSet<>();
                    for (String curriculum : curriculums) {
                        curriculumIdentifiers.add(SchoolDataIdentifier.fromId(curriculum));
                    }
                    retval.add(new VopsWorkspace(workspaceIdentifier, educationSubtypeIdentifier, curriculumIdentifiers, name, description));
                }
            }
        }
    }
    return retval;
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) ArrayList(java.util.ArrayList) SearchProvider(fi.otavanopisto.muikku.search.SearchProvider) SearchResult(fi.otavanopisto.muikku.search.SearchResult) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 3 with SearchProvider

use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.

the class SearchPluginDescriptor method init.

@Override
public void init() {
    Iterator<SearchIndexUpdater> updaterIterator = searchIndexUpdaters.iterator();
    while (updaterIterator.hasNext()) {
        SearchIndexUpdater updater = updaterIterator.next();
        logger.info("Initializing search index updater: " + updater.getName());
        updater.init();
    }
    Iterator<SearchProvider> providerIterator = searchProviders.iterator();
    while (providerIterator.hasNext()) {
        SearchProvider provider = providerIterator.next();
        logger.info("Initializing search provider: " + provider.getName());
        provider.init();
    }
}
Also used : SearchProvider(fi.otavanopisto.muikku.search.SearchProvider) SearchIndexUpdater(fi.otavanopisto.muikku.search.SearchIndexUpdater)

Example 4 with SearchProvider

use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.

the class UserSeekerResultProvider method search.

@Override
public List<SeekerResult> search(String searchTerm) {
    if (!sessionController.isLoggedIn())
        return null;
    SearchProvider elasticSearchProvider = getProvider("elastic-search");
    if (elasticSearchProvider != null) {
        String[] fields = new String[] { "firstName", "lastName", "nickName" };
        SearchResult result = elasticSearchProvider.search(searchTerm, fields, 0, 10, User.class);
        return searchResultProcessor.process(result);
    }
    return null;
}
Also used : SearchProvider(fi.otavanopisto.muikku.search.SearchProvider) SearchResult(fi.otavanopisto.muikku.search.SearchResult)

Example 5 with SearchProvider

use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.

the class WorkspaceRESTService method listWorkspaces.

@GET
@Path("/workspaces/")
@RESTPermit(handling = Handling.INLINE)
public Response listWorkspaces(@QueryParam("userId") Long userEntityId, @QueryParam("userIdentifier") String userId, @QueryParam("includeInactiveWorkspaces") @DefaultValue("false") Boolean includeInactiveWorkspaces, @QueryParam("search") String searchString, @QueryParam("subjects") List<String> subjects, @QueryParam("educationTypes") List<String> educationTypeIds, @QueryParam("curriculums") List<String> curriculumIds, @QueryParam("minVisits") Long minVisits, @QueryParam("includeUnpublished") @DefaultValue("false") Boolean includeUnpublished, @QueryParam("orderBy") List<String> orderBy, @QueryParam("firstResult") @DefaultValue("0") Integer firstResult, @QueryParam("maxResults") @DefaultValue("50") Integer maxResults, @Context Request request) {
    List<fi.otavanopisto.muikku.plugins.workspace.rest.model.Workspace> workspaces = new ArrayList<>();
    boolean doMinVisitFilter = minVisits != null;
    UserEntity userEntity = userEntityId != null ? userEntityController.findUserEntityById(userEntityId) : null;
    List<WorkspaceEntity> workspaceEntities = null;
    String schoolDataSourceFilter = null;
    List<String> workspaceIdentifierFilters = null;
    SchoolDataIdentifier userIdentifier = SchoolDataIdentifier.fromId(userId);
    if (userIdentifier != null) {
        if (doMinVisitFilter && userEntity == null) {
            userEntity = userEntityController.findUserEntityByUserIdentifier(userIdentifier);
        }
    }
    if (includeInactiveWorkspaces && userIdentifier == null) {
        return Response.status(Status.BAD_REQUEST).entity("includeInactiveWorkspaces works only with userIdentifier parameter").build();
    }
    if (includeInactiveWorkspaces && doMinVisitFilter) {
        return Response.status(Status.BAD_REQUEST).entity("includeInactiveWorkspaces cannot be used with doMinVisitFilter").build();
    }
    if (doMinVisitFilter) {
        if (!sessionController.isLoggedIn()) {
            return Response.status(Status.UNAUTHORIZED).entity("You need to be logged in to filter by visit count").build();
        }
        UserEntity loggedUserEntity = sessionController.getLoggedUserEntity();
        workspaceEntities = workspaceVisitController.listEnrolledWorkspaceEntitiesByMinVisitsOrderByLastVisit(loggedUserEntity, minVisits);
    } else {
        if (userIdentifier != null) {
            if (includeInactiveWorkspaces) {
                workspaceEntities = workspaceUserEntityController.listWorkspaceEntitiesByUserIdentifier(userIdentifier);
            } else {
                workspaceEntities = workspaceUserEntityController.listActiveWorkspaceEntitiesByUserIdentifier(userIdentifier);
            }
        } else if (userEntity != null) {
            workspaceEntities = workspaceUserEntityController.listActiveWorkspaceEntitiesByUserEntity(userEntity);
        } else {
            if (!sessionController.hasEnvironmentPermission(MuikkuPermissions.LIST_ALL_WORKSPACES)) {
                return Response.status(Status.FORBIDDEN).build();
            }
            workspaceEntities = Boolean.TRUE.equals(includeUnpublished) ? workspaceController.listWorkspaceEntities() : workspaceController.listPublishedWorkspaceEntities();
        }
    }
    Iterator<SearchProvider> searchProviderIterator = searchProviders.iterator();
    if (searchProviderIterator.hasNext()) {
        SearchProvider searchProvider = searchProviderIterator.next();
        SearchResult searchResult = null;
        if (workspaceEntities != null) {
            workspaceIdentifierFilters = new ArrayList<>();
            for (WorkspaceEntity workspaceEntity : workspaceEntities) {
                if (schoolDataSourceFilter == null) {
                    schoolDataSourceFilter = workspaceEntity.getDataSource().getIdentifier();
                }
                workspaceIdentifierFilters.add(workspaceEntity.getIdentifier());
            }
        }
        List<Sort> sorts = null;
        if (orderBy != null && orderBy.contains("alphabet")) {
            sorts = new ArrayList<>();
            sorts.add(new Sort("name.untouched", Sort.Order.ASC));
        }
        List<SchoolDataIdentifier> educationTypes = null;
        if (educationTypeIds != null) {
            educationTypes = new ArrayList<>(educationTypeIds.size());
            for (String educationTypeId : educationTypeIds) {
                SchoolDataIdentifier educationTypeIdentifier = SchoolDataIdentifier.fromId(educationTypeId);
                if (educationTypeIdentifier != null) {
                    educationTypes.add(educationTypeIdentifier);
                } else {
                    return Response.status(Status.BAD_REQUEST).entity(String.format("Malformed education type identifier", educationTypeId)).build();
                }
            }
        }
        List<SchoolDataIdentifier> curriculums = null;
        if (curriculumIds != null) {
            curriculums = new ArrayList<>(curriculumIds.size());
            for (String curriculumId : curriculumIds) {
                SchoolDataIdentifier curriculumIdentifier = SchoolDataIdentifier.fromId(curriculumId);
                if (curriculumIdentifier != null) {
                    curriculums.add(curriculumIdentifier);
                } else {
                    return Response.status(Status.BAD_REQUEST).entity(String.format("Malformed curriculum identifier", curriculumId)).build();
                }
            }
        }
        searchResult = searchProvider.searchWorkspaces(schoolDataSourceFilter, subjects, workspaceIdentifierFilters, educationTypes, curriculums, searchString, null, null, includeUnpublished, firstResult, maxResults, sorts);
        List<Map<String, Object>> results = searchResult.getResults();
        for (Map<String, Object> result : results) {
            String searchId = (String) result.get("id");
            if (StringUtils.isNotBlank(searchId)) {
                String[] id = searchId.split("/", 2);
                if (id.length == 2) {
                    String dataSource = id[1];
                    String identifier = id[0];
                    WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceByDataSourceAndIdentifier(dataSource, identifier);
                    if (workspaceEntity != null) {
                        String name = (String) result.get("name");
                        String description = (String) result.get("description");
                        String nameExtension = (String) result.get("nameExtension");
                        String subjectIdentifier = (String) result.get("subjectIdentifier");
                        Object curriculumIdentifiersObject = result.get("curriculumIdentifiers");
                        Set<String> curriculumIdentifiers = new HashSet<String>();
                        if (curriculumIdentifiersObject instanceof Collection) {
                            Collection<?> curriculumIdentifierCollection = (Collection<?>) curriculumIdentifiersObject;
                            for (Object o : curriculumIdentifierCollection) {
                                if (o instanceof String)
                                    curriculumIdentifiers.add((String) o);
                                else
                                    logger.warning("curriculumIdentifier not of type String");
                            }
                        }
                        if (StringUtils.isNotBlank(name)) {
                            workspaces.add(createRestModel(workspaceEntity, name, nameExtension, description, curriculumIdentifiers, subjectIdentifier));
                        }
                    }
                }
            }
        }
    } else {
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
    if (workspaces.isEmpty()) {
        return Response.noContent().build();
    }
    if (orderBy.contains("lastVisit")) {
        Collections.sort(workspaces, new Comparator<fi.otavanopisto.muikku.plugins.workspace.rest.model.Workspace>() {

            @Override
            public int compare(fi.otavanopisto.muikku.plugins.workspace.rest.model.Workspace workspace1, fi.otavanopisto.muikku.plugins.workspace.rest.model.Workspace workspace2) {
                if (workspace1.getLastVisit() == null || workspace2.getLastVisit() == null) {
                    return 0;
                }
                if (workspace1.getLastVisit().before(workspace2.getLastVisit())) {
                    return 1;
                }
                if (workspace1.getLastVisit().after(workspace2.getLastVisit())) {
                    return -1;
                }
                return 0;
            }
        });
    }
    return Response.ok(workspaces).build();
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) UserSchoolDataIdentifier(fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier) ArrayList(java.util.ArrayList) Sort(fi.otavanopisto.muikku.search.SearchProvider.Sort) HashSet(java.util.HashSet) 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) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap) Workspace(fi.otavanopisto.muikku.schooldata.entity.Workspace) Path(javax.ws.rs.Path) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) GET(javax.ws.rs.GET)

Aggregations

SearchProvider (fi.otavanopisto.muikku.search.SearchProvider)11 SearchResult (fi.otavanopisto.muikku.search.SearchResult)9 ArrayList (java.util.ArrayList)8 Map (java.util.Map)8 UserEntity (fi.otavanopisto.muikku.model.users.UserEntity)7 SchoolDataIdentifier (fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier)7 GET (javax.ws.rs.GET)7 Path (javax.ws.rs.Path)7 WorkspaceEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceEntity)6 WorkspaceUserEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity)6 HashMap (java.util.HashMap)6 UserSchoolDataIdentifier (fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier)5 RESTPermit (fi.otavanopisto.security.rest.RESTPermit)4 HashSet (java.util.HashSet)4 UserGroupEntity (fi.otavanopisto.muikku.model.users.UserGroupEntity)3 RESTPermitUnimplemented (fi.otavanopisto.muikku.rest.RESTPermitUnimplemented)3 EnvironmentRoleArchetype (fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype)2 Flag (fi.otavanopisto.muikku.model.users.Flag)2 User (fi.otavanopisto.muikku.schooldata.entity.User)2 SearchIndexUpdater (fi.otavanopisto.muikku.search.SearchIndexUpdater)2