use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.
the class CoursePickerRESTService method listWorkspaces.
@GET
@Path("/workspaces/")
@RESTPermitUnimplemented
public Response listWorkspaces(@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("myWorkspaces") @DefaultValue("false") Boolean myWorkspaces, @QueryParam("orderBy") List<String> orderBy, @QueryParam("firstResult") @DefaultValue("0") Integer firstResult, @QueryParam("maxResults") @DefaultValue("50") Integer maxResults, @Context Request request) {
List<CoursePickerWorkspace> workspaces = new ArrayList<>();
boolean doMinVisitFilter = minVisits != null;
UserEntity userEntity = myWorkspaces ? sessionController.getLoggedUserEntity() : null;
List<WorkspaceEntity> workspaceEntities = null;
String schoolDataSourceFilter = null;
List<String> workspaceIdentifierFilters = null;
if (doMinVisitFilter) {
if (userEntity != null) {
workspaceEntities = workspaceVisitController.listWorkspaceEntitiesByMinVisitsOrderByLastVisit(userEntity, minVisits);
} else {
workspaceEntities = workspaceVisitController.listWorkspaceEntitiesByMinVisitsOrderByLastVisit(sessionController.getLoggedUserEntity(), minVisits);
}
} else {
if (userEntity != null) {
workspaceEntities = workspaceUserEntityController.listActiveWorkspaceEntitiesByUserEntity(userEntity);
}
}
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<WorkspaceAccess> accesses = new ArrayList<>(Arrays.asList(WorkspaceAccess.ANYONE));
if (sessionController.isLoggedIn()) {
accesses.add(WorkspaceAccess.LOGGED_IN);
accesses.add(WorkspaceAccess.MEMBERS_ONLY);
}
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> curriculumIdentifiers = null;
if (curriculumIds != null) {
curriculumIdentifiers = new ArrayList<>(curriculumIds.size());
for (String curriculumId : curriculumIds) {
SchoolDataIdentifier curriculumIdentifier = SchoolDataIdentifier.fromId(curriculumId);
if (curriculumIdentifier != null) {
curriculumIdentifiers.add(curriculumIdentifier);
} else {
return Response.status(Status.BAD_REQUEST).entity(String.format("Malformed curriculum identifier", curriculumId)).build();
}
}
}
searchResult = searchProvider.searchWorkspaces(schoolDataSourceFilter, subjects, workspaceIdentifierFilters, educationTypes, curriculumIdentifiers, searchString, accesses, sessionController.getLoggedUser(), includeUnpublished, firstResult, maxResults, sorts);
schoolDataBridgeSessionController.startSystemSession();
try {
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];
SchoolDataIdentifier workspaceIdentifier = new SchoolDataIdentifier(identifier, dataSource);
WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceByDataSourceAndIdentifier(workspaceIdentifier.getDataSource(), workspaceIdentifier.getIdentifier());
if (workspaceEntity != null) {
String name = (String) result.get("name");
String nameExtension = (String) result.get("nameExtension");
String description = (String) result.get("description");
boolean canSignup = getCanSignup(workspaceEntity);
boolean isCourseMember = getIsAlreadyOnWorkspace(workspaceEntity);
String educationTypeId = (String) result.get("educationTypeIdentifier");
String educationTypeName = null;
if (StringUtils.isNotBlank(educationTypeId)) {
EducationType educationType = null;
SchoolDataIdentifier educationTypeIdentifier = SchoolDataIdentifier.fromId(educationTypeId);
if (educationTypeIdentifier == null) {
logger.severe(String.format("Malformatted educationTypeIdentifier %s", educationTypeId));
} else {
educationType = courseMetaController.findEducationType(educationTypeIdentifier.getDataSource(), educationTypeIdentifier.getIdentifier());
}
if (educationType != null) {
educationTypeName = educationType.getName();
}
}
if (StringUtils.isNotBlank(name)) {
workspaces.add(createRestModel(workspaceEntity, name, nameExtension, description, educationTypeName, canSignup, isCourseMember));
} else {
logger.severe(String.format("Search index contains workspace %s that does not have a name", workspaceIdentifier));
}
} else {
logger.severe(String.format("Search index contains workspace %s that does not exits on the school data system", workspaceIdentifier));
}
}
}
}
} finally {
schoolDataBridgeSessionController.endSystemSession();
}
} 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<CoursePickerWorkspace>() {
@Override
public int compare(CoursePickerWorkspace workspace1, CoursePickerWorkspace 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();
}
use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.
the class UserGroupRESTService method searchUserGroups.
@GET
@Path("/groups")
@RESTPermitUnimplemented
public Response searchUserGroups(@QueryParam("userIdentifier") String userIdentifier, @QueryParam("searchString") String searchString, @QueryParam("firstResult") @DefaultValue("0") Integer firstResult, @QueryParam("maxResults") @DefaultValue("10") Integer maxResults) {
if (!sessionController.isLoggedIn()) {
return Response.status(Status.FORBIDDEN).build();
}
List<UserGroupEntity> entities = new ArrayList<>();
if (userIdentifier != null) {
SchoolDataIdentifier identifier = SchoolDataIdentifier.fromId(userIdentifier);
if (identifier == null) {
Response.status(Status.BAD_REQUEST).entity("Malformed userIdentifier").build();
}
UserEntity loggedUserEntity = sessionController.getLoggedUserEntity();
UserEntity userEntity = userEntityController.findUserEntityByUserIdentifier(identifier);
if (userEntity == null) {
return Response.status(Status.NOT_FOUND).build();
}
// Check for group-user-only roles - no shared groups, no rights
if (sessionController.hasEnvironmentPermission(RoleFeatures.ACCESS_ONLY_GROUP_STUDENTS) && !userGroupEntityController.haveSharedUserGroups(loggedUserEntity, userEntity)) {
return Response.status(Status.FORBIDDEN).build();
}
if (!(loggedUserEntity.getId().equals(userEntity.getId()) || sessionController.hasEnvironmentPermission(MuikkuPermissions.LIST_USER_USERGROUPS))) {
return Response.status(Status.FORBIDDEN).build();
}
if (identifier != null) {
entities = userGroupEntityController.listUserGroupsByUserIdentifier(identifier);
// For someone with the role feature the group entities are not necessarily accessible
if (sessionController.hasEnvironmentPermission(RoleFeatures.ACCESS_ONLY_GROUP_STUDENTS)) {
List<UserGroupEntity> guiderGroups = userGroupEntityController.listUserGroupsByUserEntity(loggedUserEntity);
Set<Long> guiderGroupIds = guiderGroups.stream().map(UserGroupEntity::getId).collect(Collectors.toSet());
entities = entities.stream().filter((UserGroupEntity uge) -> guiderGroupIds.contains(uge.getId())).collect(Collectors.toList());
}
}
} else {
SearchProvider elasticSearchProvider = getProvider("elastic-search");
if (elasticSearchProvider != null) {
String[] fields = new String[] { "name" };
SearchResult result = null;
if (StringUtils.isBlank(searchString)) {
result = elasticSearchProvider.matchAllSearch(firstResult, maxResults, UserGroup.class);
} else {
result = elasticSearchProvider.search(searchString, fields, firstResult, maxResults, UserGroup.class);
}
List<Map<String, Object>> results = result.getResults();
if (!results.isEmpty()) {
for (Map<String, Object> o : results) {
String[] id = ((String) o.get("id")).split("/", 2);
UserGroupEntity userGroupEntity = userGroupEntityController.findUserGroupEntityByDataSourceAndIdentifier(id[1], id[0]);
if (userGroupEntity != null) {
entities.add(userGroupEntity);
}
}
}
}
}
if (entities.isEmpty()) {
return Response.noContent().build();
} else {
List<fi.otavanopisto.muikku.rest.model.UserGroup> ret = new ArrayList<fi.otavanopisto.muikku.rest.model.UserGroup>();
for (UserGroupEntity entity : entities) {
Long userCount = userGroupEntityController.getGroupUserCount(entity);
UserGroup group = userGroupController.findUserGroup(entity);
if (group != null)
ret.add(new fi.otavanopisto.muikku.rest.model.UserGroup(entity.getId(), group.getName(), userCount));
else
logger.log(Level.WARNING, "Group not found");
}
return Response.ok(ret).build();
}
}
use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.
the class UserRESTService method searchStaffMembers.
@GET
@Path("/staffMembers")
@RESTPermit(handling = Handling.INLINE)
public Response searchStaffMembers(@QueryParam("searchString") String searchString, @QueryParam("properties") String properties, @QueryParam("workspaceEntityId") Long workspaceEntityId, @QueryParam("firstResult") @DefaultValue("0") Integer firstResult, @QueryParam("maxResults") @DefaultValue("10") Integer maxResults) {
if (!sessionController.isLoggedIn()) {
return Response.status(Status.FORBIDDEN).build();
}
List<fi.otavanopisto.muikku.rest.model.StaffMember> staffMembers = new ArrayList<>();
Set<Long> userGroupFilters = null;
Set<Long> workspaceFilters = workspaceEntityId == null ? null : Collections.singleton(workspaceEntityId);
List<SchoolDataIdentifier> userIdentifiers = null;
SearchProvider elasticSearchProvider = getProvider("elastic-search");
if (elasticSearchProvider != null) {
String[] fields;
if (StringUtils.isNumeric(searchString)) {
fields = new String[] { "firstName", "lastName", "userEntityId", "email" };
} else {
fields = new String[] { "firstName", "lastName", "email" };
}
List<EnvironmentRoleArchetype> nonStudentArchetypes = new ArrayList<>(Arrays.asList(EnvironmentRoleArchetype.values()));
nonStudentArchetypes.remove(EnvironmentRoleArchetype.STUDENT);
SearchResult result = elasticSearchProvider.searchUsers(searchString, fields, nonStudentArchetypes, userGroupFilters, workspaceFilters, userIdentifiers, false, false, false, firstResult, maxResults);
List<Map<String, Object>> results = result.getResults();
if (results != null && !results.isEmpty()) {
WorkspaceEntity workspaceEntity = workspaceEntityId == null ? null : workspaceEntityController.findWorkspaceEntityById(workspaceEntityId);
String[] propertyArray = StringUtils.isEmpty(properties) ? new String[0] : properties.split(",");
for (Map<String, Object> o : results) {
String studentId = (String) o.get("id");
if (StringUtils.isBlank(studentId)) {
logger.severe("Could not process user found from search index because it had a null id");
continue;
}
String[] studentIdParts = studentId.split("/", 2);
SchoolDataIdentifier studentIdentifier = studentIdParts.length == 2 ? new SchoolDataIdentifier(studentIdParts[0], studentIdParts[1]) : null;
if (studentIdentifier == null) {
logger.severe(String.format("Could not process user found from search index with id %s", studentId));
continue;
}
if (studentIdentifier.getIdentifier().startsWith("STUDENT-")) {
// the elasticsearch query returns both. We need to filter them after the fact.
continue;
}
String email = userEmailEntityController.getUserDefaultEmailAddress(studentIdentifier, false);
Long userEntityId = new Long((Integer) o.get("userEntityId"));
UserEntity userEntity = userEntityController.findUserEntityById(userEntityId);
Map<String, String> propertyMap = new HashMap<String, String>();
if (userEntity != null) {
for (int i = 0; i < propertyArray.length; i++) {
UserEntityProperty userEntityProperty = userEntityController.getUserEntityPropertyByKey(userEntity, propertyArray[i]);
propertyMap.put(propertyArray[i], userEntityProperty == null ? null : userEntityProperty.getValue());
}
}
if (workspaceEntity != null) {
WorkspaceUserEntity workspaceUserEntity = workspaceUserEntityController.findActiveWorkspaceUserByWorkspaceEntityAndUserEntity(workspaceEntity, userEntity);
if (workspaceUserEntity == null || workspaceUserEntity.getWorkspaceUserRole().getArchetype() != WorkspaceRoleArchetype.TEACHER) {
continue;
}
}
staffMembers.add(new fi.otavanopisto.muikku.rest.model.StaffMember(studentIdentifier.toId(), new Long((Integer) o.get("userEntityId")), (String) o.get("firstName"), (String) o.get("lastName"), email, propertyMap));
}
}
}
return Response.ok(staffMembers).build();
}
use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.
the class UserRESTService method searchStudents.
@GET
@Path("/students")
@RESTPermit(handling = Handling.INLINE)
public Response searchStudents(@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("userEntityId") Long userEntityId, @DefaultValue("false") @QueryParam("includeInactiveStudents") Boolean includeInactiveStudents, @DefaultValue("false") @QueryParam("includeHidden") Boolean includeHidden, @QueryParam("flags") Long[] flagIds) {
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();
}
List<Flag> flags = null;
if (flagIds != null && flagIds.length > 0) {
flags = new ArrayList<>(flagIds.length);
for (Long flagId : flagIds) {
Flag flag = flagController.findFlagById(flagId);
if (flag == null) {
return Response.status(Status.BAD_REQUEST).entity(String.format("Invalid flag id %d", flagId)).build();
}
if (!flagController.hasFlagPermission(flag, sessionController.getLoggedUser())) {
return Response.status(Status.FORBIDDEN).entity(String.format("You don't have permission to use flag %d", flagId)).build();
}
flags.add(flag);
}
}
List<fi.otavanopisto.muikku.rest.model.Student> students = new ArrayList<>();
UserEntity loggedUser = sessionController.getLoggedUserEntity();
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);
}
}
List<SchoolDataIdentifier> userIdentifiers = null;
if (flags != null) {
if (userIdentifiers == null) {
userIdentifiers = new ArrayList<>();
}
userIdentifiers.addAll(flagController.getFlaggedStudents(flags));
}
if (Boolean.TRUE.equals(includeInactiveStudents)) {
if (!sessionController.hasEnvironmentPermission(MuikkuPermissions.LIST_INACTIVE_STUDENTS)) {
if (userEntityId == null) {
return Response.status(Status.FORBIDDEN).build();
} else {
if (!sessionController.getLoggedUserEntity().getId().equals(userEntityId)) {
return Response.status(Status.FORBIDDEN).build();
}
}
}
}
if (Boolean.TRUE.equals(includeHidden)) {
if (!sessionController.hasEnvironmentPermission(MuikkuPermissions.LIST_HIDDEN_STUDENTS)) {
if (userEntityId == null) {
return Response.status(Status.FORBIDDEN).build();
} else {
if (!sessionController.getLoggedUserEntity().getId().equals(userEntityId)) {
return Response.status(Status.FORBIDDEN).build();
}
}
}
}
if (userEntityId != null) {
List<SchoolDataIdentifier> userEntityIdentifiers = new ArrayList<>();
UserEntity userEntity = userEntityController.findUserEntityById(userEntityId);
if (userEntity == null) {
return Response.status(Status.BAD_REQUEST).entity(String.format("Invalid userEntityId %d", userEntityId)).build();
}
List<UserSchoolDataIdentifier> schoolDataIdentifiers = userSchoolDataIdentifierController.listUserSchoolDataIdentifiersByUserEntity(userEntity);
for (UserSchoolDataIdentifier schoolDataIdentifier : schoolDataIdentifiers) {
userEntityIdentifiers.add(new SchoolDataIdentifier(schoolDataIdentifier.getIdentifier(), schoolDataIdentifier.getDataSource().getIdentifier()));
}
if (userIdentifiers == null) {
userIdentifiers = userEntityIdentifiers;
} else {
userIdentifiers.retainAll(userEntityIdentifiers);
}
}
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<>(myWorkspaceIds);
} else if (!CollectionUtils.isEmpty(workspaceIds)) {
// Defined workspaces
workspaceFilters = new HashSet<>(workspaceIds);
}
SearchProvider elasticSearchProvider = getProvider("elastic-search");
if (elasticSearchProvider != null) {
String[] fields = new String[] { "firstName", "lastName", "nickName", "email" };
SearchResult result = elasticSearchProvider.searchUsers(searchString, fields, Arrays.asList(EnvironmentRoleArchetype.STUDENT), userGroupFilters, workspaceFilters, userIdentifiers, includeInactiveStudents, includeHidden, false, firstResult, maxResults);
List<Map<String, Object>> results = result.getResults();
boolean hasImage = false;
if (results != null && !results.isEmpty()) {
for (Map<String, Object> o : results) {
String studentId = (String) o.get("id");
if (StringUtils.isBlank(studentId)) {
logger.severe("Could not process user found from search index because it had a null id");
continue;
}
String[] studentIdParts = studentId.split("/", 2);
SchoolDataIdentifier studentIdentifier = studentIdParts.length == 2 ? new SchoolDataIdentifier(studentIdParts[0], studentIdParts[1]) : null;
if (studentIdentifier == null) {
logger.severe(String.format("Could not process user found from search index with id %s", studentId));
continue;
}
UserEntity userEntity = userEntityController.findUserEntityByUserIdentifier(studentIdentifier);
String emailAddress = userEntity != null ? userEmailEntityController.getUserDefaultEmailAddress(userEntity, true) : null;
Date studyStartDate = getDateResult(o.get("studyStartDate"));
Date studyEndDate = getDateResult(o.get("studyEndDate"));
Date studyTimeEnd = getDateResult(o.get("studyTimeEnd"));
students.add(new fi.otavanopisto.muikku.rest.model.Student(studentIdentifier.toId(), (String) o.get("firstName"), (String) o.get("lastName"), (String) o.get("nickName"), (String) o.get("studyProgrammeName"), hasImage, (String) o.get("nationality"), (String) o.get("language"), (String) o.get("municipality"), (String) o.get("school"), emailAddress, studyStartDate, studyEndDate, studyTimeEnd, (String) o.get("curriculumIdentifier"), userEntity.getUpdatedByStudent()));
}
}
}
return Response.ok(students).build();
}
use of fi.otavanopisto.muikku.search.SearchProvider in project muikku by otavanopisto.
the class SearchPluginDescriptor method deinit.
@PreDestroy
public void deinit() {
Iterator<SearchProvider> searchProviderIterator = searchProviders.iterator();
while (searchProviderIterator.hasNext()) {
SearchProvider provider = searchProviderIterator.next();
logger.info("Deinitializing search provider: " + provider.getName());
provider.deinit();
}
Iterator<SearchIndexUpdater> updaterProviderIterator = searchIndexUpdaters.iterator();
while (updaterProviderIterator.hasNext()) {
SearchIndexUpdater updater = updaterProviderIterator.next();
logger.info("Deinitializing search index updater: " + updater.getName());
updater.deinit();
}
}
Aggregations