use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.
the class SaveFieldAnswerWebSocketMessageHandler method handleMessage.
public void handleMessage(@Observes @MuikkuWebSocketEvent("workspace:field-answer-save") WebSocketMessageEvent event) {
// TODO: Localize error messages
WebSocketMessage webSocketMessage = event.getMessage();
ObjectMapper mapper = new ObjectMapper();
try {
SaveFieldAnswerWebSocketMessage message = mapper.readValue((String) webSocketMessage.getData(), SaveFieldAnswerWebSocketMessage.class);
Date now = new Date();
if (message.getMaterialId() == null) {
logger.log(Level.SEVERE, "Missing material id");
handleError("Missing material id", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
if (message.getWorkspaceMaterialId() == null) {
logger.log(Level.SEVERE, "Missing workspace material id");
handleError("Missing workspace material id", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
if (message.getUserEntityId() == null) {
logger.log(Level.SEVERE, String.format("Missing user entity id for ticket %s (field %s in workspace material %d)", event.getTicket(), message.getFieldName(), message.getWorkspaceMaterialId()));
handleError("Missing user entity id", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
Material material = materialController.findMaterialById(message.getMaterialId());
if (material == null) {
logger.log(Level.SEVERE, "Could not find material");
handleError("Could not find material", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
UserEntity userEntity = userEntityController.findUserEntityById(message.getUserEntityId());
if (userEntity == null) {
logger.log(Level.SEVERE, "Could not find user");
handleError("Could not find user", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
WorkspaceMaterial workspaceMaterial = workspaceMaterialController.findWorkspaceMaterialById(message.getWorkspaceMaterialId());
if (workspaceMaterial == null) {
logger.log(Level.SEVERE, "Could not find workspace material");
handleError("Could not find workspace material", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
if (!workspaceMaterial.getMaterialId().equals(material.getId())) {
logger.log(Level.SEVERE, "Invalid materialId or workspaceMaterialId");
handleError("Invalid materialId or workspaceMaterialId", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
QueryField queryField = queryFieldController.findQueryFieldByMaterialAndName(material, message.getFieldName());
if (queryField == null) {
logger.log(Level.SEVERE, "Could not find query field");
handleError("Could not find query field", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
WorkspaceMaterialField materialField = workspaceMaterialFieldController.findWorkspaceMaterialFieldByWorkspaceMaterialAndQueryFieldAndEmbedId(workspaceMaterial, queryField, message.getEmbedId());
if (materialField == null) {
materialField = workspaceMaterialFieldController.createWorkspaceMaterialField(workspaceMaterial, queryField, message.getEmbedId());
}
fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialReply reply = workspaceMaterialReplyController.findWorkspaceMaterialReplyByWorkspaceMaterialAndUserEntity(workspaceMaterial, userEntity);
if (reply == null) {
reply = workspaceMaterialReplyController.createWorkspaceMaterialReply(workspaceMaterial, WorkspaceMaterialReplyState.ANSWERED, userEntity, 1l, now, now);
} else {
workspaceMaterialReplyController.incWorkspaceMaterialReplyTries(reply);
}
if (workspaceMaterial.getAssignmentType() == WorkspaceMaterialAssignmentType.EVALUATED) {
switch(reply.getState()) {
case PASSED:
case FAILED:
case SUBMITTED:
handleError("Assignment is already submitted thus can not be modified", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
default:
break;
}
}
try {
workspaceMaterialFieldController.storeFieldValue(materialField, reply, message.getAnswer());
} catch (WorkspaceFieldIOException e) {
logger.log(Level.SEVERE, "Could not store field value", e);
handleError("Could not store field value", message.getEmbedId(), message.getMaterialId(), message.getFieldName(), message.getWorkspaceMaterialId(), message.getWorkspaceEntityId(), event.getTicket());
return;
}
message.setOriginTicket(event.getTicket());
String data = mapper.writeValueAsString(message);
webSocketMessenger.sendMessage("workspace:field-answer-saved", data, Arrays.asList(userEntity));
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to unmarshal SaveFieldAnswerWebSocketMessage", e);
}
}
use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.
the class ProfileBackingBean method init.
@RequestAction
@LoggedIn
public String init() {
UserEntity userEntity = sessionController.getLoggedUserEntity();
User user = userController.findUserByDataSourceAndIdentifier(sessionController.getLoggedUserSchoolDataSource(), sessionController.getLoggedUserIdentifier());
List<UserAddress> userAddresses = userController.listUserAddresses(user);
List<UserPhoneNumber> userPhoneNumbers = userController.listUserPhoneNumbers(user);
displayName = user.getNickName() == null ? user.getDisplayName() : String.format("%s %s (%s)", user.getNickName(), user.getLastName(), user.getStudyProgrammeName());
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.profile.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.profile.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.profile.studyTimeEndShort.d");
}
}
}
addresses = new ArrayList<>();
for (UserAddress userAddress : userAddresses) {
addresses.add(String.format("%s %s %s %s", userAddress.getStreet(), userAddress.getPostalCode(), userAddress.getCity(), userAddress.getCountry()));
}
phoneNumbers = new ArrayList<>();
for (UserPhoneNumber userPhoneNumber : userPhoneNumbers) {
phoneNumbers.add(userPhoneNumber.getNumber());
}
SchoolDataIdentifier identifier = new SchoolDataIdentifier(userEntity.getDefaultIdentifier(), userEntity.getDefaultSchoolDataSource().getIdentifier());
emails = userEmailEntityController.getUserEmailAddresses(identifier);
return null;
}
use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.
the class WorkspaceRESTService method getWorkspaceMaterialAnswers.
@GET
@Path("/workspaces/{WORKSPACEENTITYID}/materials/{WORKSPACEMATERIALID}/compositeMaterialReplies")
@RESTPermitUnimplemented
public Response getWorkspaceMaterialAnswers(@PathParam("WORKSPACEENTITYID") Long workspaceEntityId, @PathParam("WORKSPACEMATERIALID") Long workspaceMaterialId, @QueryParam("userEntityId") Long userEntityId) {
// TODO: Security
if (!sessionController.isLoggedIn()) {
return Response.status(Status.UNAUTHORIZED).entity("Not logged in").build();
}
// TODO Return everyone's answers
if (userEntityId == null) {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
UserEntity userEntity = userEntityController.findUserEntityById(userEntityId);
WorkspaceMaterial workspaceMaterial = workspaceMaterialController.findWorkspaceMaterialById(workspaceMaterialId);
if (workspaceMaterial == null) {
return Response.status(Status.NOT_FOUND).entity("Workspace material could not be found").build();
}
List<WorkspaceMaterialFieldAnswer> answers = new ArrayList<>();
try {
fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialReply reply = workspaceMaterialReplyController.findWorkspaceMaterialReplyByWorkspaceMaterialAndUserEntity(workspaceMaterial, userEntity);
if (reply != null) {
List<WorkspaceMaterialField> fields = workspaceMaterialFieldController.listWorkspaceMaterialFieldsByWorkspaceMaterial(workspaceMaterial);
for (WorkspaceMaterialField field : fields) {
String value = workspaceMaterialFieldController.retrieveFieldValue(field, reply);
Material material = field.getQueryField().getMaterial();
WorkspaceMaterialFieldAnswer answer = new WorkspaceMaterialFieldAnswer(workspaceMaterial.getId(), material.getId(), field.getEmbedId(), field.getQueryField().getName(), value);
answers.add(answer);
}
}
WorkspaceMaterialCompositeReply result = new WorkspaceMaterialCompositeReply(answers, reply != null ? reply.getState() : null, reply != null ? reply.getCreated() : null, reply != null ? reply.getLastModified() : null, reply != null ? reply.getSubmitted() : null, reply != null ? reply.getWithdrawn() : null);
return Response.ok(result).build();
} catch (WorkspaceFieldIOException e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Internal error occurred while retrieving field answers: " + e.getMessage()).build();
}
}
use of fi.otavanopisto.muikku.model.users.UserEntity in project muikku by otavanopisto.
the class WorkspaceRESTService method createWorkspaceMaterialReply.
@POST
// @Path ("/workspaces/{WORKSPACEENTITYID:[0-9]*}/materials/{WORKSPACEMATERIALID:[0-9]*}/replies")
@Path("/workspaces/{WORKSPACEENTITYID}/materials/{WORKSPACEMATERIALID}/replies")
@RESTPermitUnimplemented
public Response createWorkspaceMaterialReply(@PathParam("WORKSPACEENTITYID") Long workspaceEntityId, @PathParam("WORKSPACEMATERIALID") Long workspaceMaterialId, WorkspaceMaterialReply payload) {
if (payload == null) {
return Response.status(Status.BAD_REQUEST).entity("Payload is missing").build();
}
if (payload.getState() == null) {
return Response.status(Status.BAD_REQUEST).entity("State is missing").build();
}
UserEntity loggedUser = sessionController.getLoggedUserEntity();
if (loggedUser == null) {
return Response.status(Status.UNAUTHORIZED).entity("Unauthorized").build();
}
WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceEntityById(workspaceEntityId);
if (workspaceEntity == null) {
return Response.status(Status.NOT_FOUND).entity("Could not find workspace entity").build();
}
WorkspaceMaterial workspaceMaterial = workspaceMaterialController.findWorkspaceMaterialById(workspaceMaterialId);
if (workspaceMaterial == null) {
return Response.status(Status.NOT_FOUND).entity("Could not find workspace material").build();
}
WorkspaceRootFolder workspaceRootFolder = workspaceMaterialController.findWorkspaceRootFolderByWorkspaceNode(workspaceMaterial);
if (workspaceRootFolder == null) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Could not find workspace root folder").build();
}
if (!workspaceRootFolder.getWorkspaceEntityId().equals(workspaceEntity.getId())) {
return Response.status(Status.BAD_REQUEST).entity("Invalid workspace material id or workspace entity id").build();
}
fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialReply workspaceMaterialReply = workspaceMaterialReplyController.createWorkspaceMaterialReply(workspaceMaterial, payload.getState(), loggedUser);
return Response.ok(createRestModel(workspaceMaterialReply)).build();
}
use of fi.otavanopisto.muikku.model.users.UserEntity 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();
}
Aggregations