use of fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier in project muikku by otavanopisto.
the class PyramusUpdater method updatePerson.
@Lock(LockType.WRITE)
@AccessTimeout(value = 30000)
public void updatePerson(Person person) {
Long userEntityId = null;
String defaultIdentifier = null;
Long defaultUserId = person.getDefaultUserId();
UserRole defaultUserPyramusRole = null;
List<String> identifiers = new ArrayList<>();
List<String> removedIdentifiers = new ArrayList<>();
List<String> updatedIdentifiers = new ArrayList<>();
List<String> discoveredIdentifiers = new ArrayList<>();
Map<SchoolDataIdentifier, List<String>> emails = new HashMap<>();
// List all person's students and staffMembers
Student[] students = pyramusClient.get().get(String.format("/persons/persons/%d/students", person.getId()), Student[].class);
StaffMember[] staffMembers = pyramusClient.get().get(String.format("/persons/persons/%d/staffMembers", person.getId()), StaffMember[].class);
// If person does not have a defaultUserId specified, we try to guess something
if (defaultUserId == null) {
if ((staffMembers != null) && (staffMembers.length > 0)) {
// If person has a staffMember instance, lets use that one
defaultUserId = staffMembers[0].getId();
} else {
if (students != null) {
// Otherwise just use first non archived student (if any)
for (Student student : students) {
if (!student.getArchived()) {
defaultUserId = student.getId();
break;
}
}
}
}
}
if (students != null) {
// Iterate over all student instances
for (Student student : students) {
String identifier = identifierMapper.getStudentIdentifier(student.getId());
SchoolDataIdentifier schoolDataIdentifier = toIdentifier(identifier);
List<String> identifierEmails = new ArrayList<String>();
if (!student.getArchived()) {
// If student is not archived, add it to identifiers list
identifiers.add(identifier);
// If it's the specified defaultUserId, update defaultIdentifier and role accordingly
if ((defaultIdentifier == null) && student.getId().equals(defaultUserId)) {
defaultIdentifier = identifier;
defaultUserPyramusRole = UserRole.STUDENT;
}
// List emails and add all emails that are not specified non unique (e.g. contact persons) to the emails list
Email[] studentEmails = pyramusClient.get().get("/students/students/" + student.getId() + "/emails", Email[].class);
if (studentEmails != null) {
for (Email studentEmail : studentEmails) {
if (studentEmail.getContactTypeId() != null) {
ContactType contactType = pyramusClient.get().get("/common/contactTypes/" + studentEmail.getContactTypeId(), ContactType.class);
if (!contactType.getNonUnique() && !identifierEmails.contains(studentEmail.getAddress())) {
identifierEmails.add(studentEmail.getAddress());
}
} else {
logger.log(Level.WARNING, "ContactType of email is null - email is ignored");
}
}
}
} else {
// If the student instance if archived, we add it the the removed identifiers list
removedIdentifiers.add(identifier);
}
emails.put(schoolDataIdentifier, identifierEmails);
}
}
if (staffMembers != null) {
for (StaffMember staffMember : staffMembers) {
// Add staffMember identifier into the identifier list
String identifier = identifierMapper.getStaffIdentifier(staffMember.getId());
SchoolDataIdentifier schoolDataIdentifier = toIdentifier(identifier);
List<String> identifierEmails = new ArrayList<String>();
identifiers.add(identifier);
// If it's the specified defaultUserId, update defaultIdentifier and role accordingly
if ((defaultIdentifier == null) && staffMember.getId().equals(defaultUserId)) {
defaultIdentifier = identifier;
defaultUserPyramusRole = staffMember.getRole();
}
// List emails and add all emails that are not specified non unique (e.g. contact persons) to the emails list
Email[] staffMemberEmails = pyramusClient.get().get("/staff/members/" + staffMember.getId() + "/emails", Email[].class);
if (staffMemberEmails != null) {
for (Email staffMemberEmail : staffMemberEmails) {
if (staffMemberEmail.getContactTypeId() != null) {
ContactType contactType = pyramusClient.get().get("/common/contactTypes/" + staffMemberEmail.getContactTypeId(), ContactType.class);
if (!contactType.getNonUnique() && !identifierEmails.contains(staffMemberEmail.getAddress())) {
identifierEmails.add(staffMemberEmail.getAddress());
}
} else {
logger.log(Level.WARNING, "ContactType of email is null - email is ignored");
}
}
}
emails.put(schoolDataIdentifier, identifierEmails);
}
}
// Iterate over all discovered identifiers (students and staff members)
for (String identifier : identifiers) {
UserSchoolDataIdentifier userSchoolDataIdentifier = userSchoolDataIdentifierController.findUserSchoolDataIdentifierByDataSourceAndIdentifier(SchoolDataPyramusPluginDescriptor.SCHOOL_DATA_SOURCE, identifier);
if (userSchoolDataIdentifier == null) {
// If no user entity can be found by the identifier, add it the the discovered identities list
discoveredIdentifiers.add(identifier);
} else {
// user entity found with given identity, so we need to make sure they all belong to same user
UserEntity userEntity = userSchoolDataIdentifier.getUserEntity();
if (userEntityId == null) {
userEntityId = userEntity.getId();
} else if (!userEntityId.equals(userEntity.getId())) {
logger.warning(String.format("Person %d synchronization failed. Found two userEntitys bound to it (%d and %d)", person.getId(), userEntityId, userEntity.getId()));
return;
}
}
}
UserEntity userEntity = userEntityId != null ? userEntityController.findUserEntityById(userEntityId) : null;
if (userEntity != null) {
// User already exists in the system so we check which of the identifiers have been removed and which just updated
List<UserSchoolDataIdentifier> existingSchoolDataIdentifiers = userSchoolDataIdentifierController.listUserSchoolDataIdentifiersByUserEntity(userEntity);
for (UserSchoolDataIdentifier existingSchoolDataIdentifier : existingSchoolDataIdentifiers) {
if (existingSchoolDataIdentifier.getDataSource().getIdentifier().equals(SchoolDataPyramusPluginDescriptor.SCHOOL_DATA_SOURCE)) {
if (!identifiers.contains(existingSchoolDataIdentifier.getIdentifier())) {
if (!removedIdentifiers.contains(existingSchoolDataIdentifier.getIdentifier())) {
removedIdentifiers.add(existingSchoolDataIdentifier.getIdentifier());
}
} else if (!discoveredIdentifiers.contains(existingSchoolDataIdentifier.getIdentifier())) {
updatedIdentifiers.add(existingSchoolDataIdentifier.getIdentifier());
}
}
}
}
// Resolve the user's desired environment role
SchoolDataIdentifier environmentRoleIdentifier = null;
if (defaultUserPyramusRole != null) {
String roleIdentifier = identifierMapper.getEnvironmentRoleIdentifier(defaultUserPyramusRole);
environmentRoleIdentifier = new SchoolDataIdentifier(roleIdentifier, SchoolDataPyramusPluginDescriptor.SCHOOL_DATA_SOURCE);
}
// And finally fire the update event
fireSchoolDataUserUpdated(userEntityId, defaultIdentifier, removedIdentifiers, updatedIdentifiers, discoveredIdentifiers, emails, environmentRoleIdentifier);
}
use of fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier in project muikku by otavanopisto.
the class PyramusUpdater method identifierRemoved.
private void identifierRemoved(SchoolDataIdentifier identifier) {
UserSchoolDataIdentifier schoolDataIdentifier = userSchoolDataIdentifierController.findUserSchoolDataIdentifierByDataSourceAndIdentifier(identifier.getDataSource(), identifier.getIdentifier());
if (schoolDataIdentifier != null) {
UserEntity userEntity = schoolDataIdentifier.getUserEntity();
List<UserSchoolDataIdentifier> existingIdentifiers = userSchoolDataIdentifierController.listUserSchoolDataIdentifiersByUserEntity(userEntity);
SchoolDataIdentifier defaultIdentifier = null;
List<SchoolDataIdentifier> removedIdentifiers = Arrays.asList(identifier);
List<SchoolDataIdentifier> updatedIdentifiers = new ArrayList<>();
List<SchoolDataIdentifier> discoveredIdentifiers = new ArrayList<>();
Map<SchoolDataIdentifier, List<String>> emails = new HashMap<>();
for (SchoolDataIdentifier removedIdentifier : removedIdentifiers) {
emails.put(removedIdentifier, new ArrayList<String>());
}
for (UserSchoolDataIdentifier existingIdentifier : existingIdentifiers) {
if (!(existingIdentifier.getDataSource().getIdentifier().equals(identifier.getDataSource()) && existingIdentifier.getIdentifier().equals(identifier.getIdentifier()))) {
SchoolDataIdentifier updatedIdentifier = new SchoolDataIdentifier(existingIdentifier.getIdentifier(), existingIdentifier.getDataSource().getIdentifier());
updatedIdentifiers.add(updatedIdentifier);
emails.put(updatedIdentifier, userEmailEntityController.getUserEmailAddresses(updatedIdentifier));
}
}
SchoolDataIdentifier enivormentRoleIdentifier = getUserEntityEnvironmentRoleIdentifier(userEntity);
fireSchoolDataUserUpdated(userEntity.getId(), defaultIdentifier, removedIdentifiers, updatedIdentifiers, discoveredIdentifiers, emails, enivormentRoleIdentifier);
}
}
use of fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier in project muikku by otavanopisto.
the class UserRESTService method deleteFlag.
@DELETE
@Path("/flags/{ID}")
@RESTPermit(handling = Handling.INLINE, requireLoggedIn = true)
public Response deleteFlag(@PathParam("ID") long flagId) {
Flag flag = flagController.findFlagById(flagId);
if (flag == null) {
return Response.status(Status.NOT_FOUND).build();
}
boolean isOwner = false;
UserSchoolDataIdentifier ownerIdentifier = flag.getOwnerIdentifier();
SchoolDataIdentifier loggedIdentifier = sessionController.getLoggedUser();
if (loggedIdentifier == null) {
return Response.status(Status.BAD_REQUEST).entity("Must be logged in.").build();
}
UserSchoolDataIdentifier loggedUserIdentifier = userSchoolDataIdentifierController.findUserSchoolDataIdentifierBySchoolDataIdentifier(loggedIdentifier);
if (loggedUserIdentifier == null) {
return Response.status(Status.BAD_REQUEST).entity("No user school data identifier for logged user").build();
}
if (Objects.equals(ownerIdentifier.getIdentifier(), loggedUserIdentifier.getIdentifier()) && Objects.equals(ownerIdentifier.getDataSource().getIdentifier(), loggedUserIdentifier.getDataSource().getIdentifier())) {
isOwner = true;
}
if (!flagController.hasFlagPermission(flag, loggedIdentifier)) {
return Response.status(Status.FORBIDDEN).entity("You don't have the permission to delete this flag").build();
}
if (isOwner) {
flagController.deleteFlagCascade(flag);
return Response.noContent().build();
} else {
flagController.unshareFlag(flag, loggedUserIdentifier);
return Response.noContent().build();
}
}
use of fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier 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.model.users.UserSchoolDataIdentifier in project muikku by otavanopisto.
the class AcceptanceTestsRESTService method createCommunicatorMessage.
@POST
@Path("/communicator/messages")
@RESTPermit(handling = Handling.UNSECURED)
public Response createCommunicatorMessage(fi.otavanopisto.muikku.atests.CommunicatorMessage payload) {
UserEntity user = userEntityController.findUserEntityById(payload.getSenderId());
CommunicatorMessageId communicatorMessageId = communicatorController.createMessageId();
Set<Tag> tagList = parseTags(payload.getTags());
List<UserEntity> recipients = new ArrayList<UserEntity>();
for (Long recipientId : payload.getRecipientIds()) {
UserEntity recipient = userEntityController.findUserEntityById(recipientId);
if (recipient != null)
recipients.add(recipient);
}
for (Long groupId : payload.getRecipientGroupIds()) {
UserGroupEntity group = userGroupEntityController.findUserGroupEntityById(groupId);
List<UserGroupUserEntity> groupUsers = userGroupEntityController.listUserGroupUserEntitiesByUserGroupEntity(group);
for (UserGroupUserEntity groupUser : groupUsers) {
UserSchoolDataIdentifier userSchoolDataIdentifier = groupUser.getUserSchoolDataIdentifier();
UserEntity userEntity = userSchoolDataIdentifier.getUserEntity();
recipients.add(userEntity);
}
}
for (Long workspaceId : payload.getRecipientStudentsWorkspaceIds()) {
WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceEntityById(workspaceId);
List<WorkspaceUserEntity> workspaceUsers = workspaceUserEntityController.listActiveWorkspaceStudents(workspaceEntity);
for (WorkspaceUserEntity wosu : workspaceUsers) {
recipients.add(wosu.getUserSchoolDataIdentifier().getUserEntity());
}
}
for (Long workspaceId : payload.getRecipientTeachersWorkspaceIds()) {
WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceEntityById(workspaceId);
List<WorkspaceUserEntity> workspaceUsers = workspaceUserEntityController.listActiveWorkspaceStaffMembers(workspaceEntity);
for (WorkspaceUserEntity wosu : workspaceUsers) {
recipients.add(wosu.getUserSchoolDataIdentifier().getUserEntity());
}
}
CommunicatorMessageCategory categoryEntity = communicatorController.persistCategory(payload.getCategoryName());
fi.otavanopisto.muikku.plugins.communicator.model.CommunicatorMessage message = communicatorController.createMessage(communicatorMessageId, user, recipients, null, null, null, categoryEntity, payload.getCaption(), payload.getContent(), tagList);
Long communicatorMessageId2 = message.getCommunicatorMessageId().getId();
fi.otavanopisto.muikku.atests.CommunicatorMessage result = new fi.otavanopisto.muikku.atests.CommunicatorMessage(message.getId(), communicatorMessageId2, message.getSender(), payload.getCategoryName(), message.getCaption(), message.getContent(), message.getCreated(), payload.getTags(), payload.getRecipientIds(), payload.getRecipientGroupIds(), payload.getRecipientStudentsWorkspaceIds(), payload.getRecipientTeachersWorkspaceIds());
Map<String, Object> params = new HashMap<String, Object>();
params.put("sender", "Admin User");
params.put("subject", message.getCaption());
params.put("content", message.getContent());
params.put("url", "https://dev.muikku.fi/communicator");
notifierController.sendNotification(communicatorNewInboxMessageNotification, user, recipients, params);
return Response.ok(result).build();
}
Aggregations