Search in sources :

Example 11 with Material

use of fi.otavanopisto.muikku.plugins.material.model.Material in project muikku by otavanopisto.

the class DeusNexMachinaController method importResource.

private void importResource(WorkspaceNode importRoot, WorkspaceNode parent, Resource resource, DeusNexDocument deusNexDocument, List<WorkspaceNode> createdNodes) throws DeusNexException {
    WorkspaceNode node = findNode(parent, resource);
    if (resource.getType() == Type.FOLDER) {
        Folder folderResource = (Folder) resource;
        WorkspaceFolder folder = null;
        if (node instanceof WorkspaceFolder) {
            folder = (WorkspaceFolder) node;
        }
        if (folder == null) {
            folder = createFolder(parent, folderResource);
            try {
                setResourceWorkspaceNodeId(resource.getNo(), folder.getId());
            } catch (IOException e) {
                throw new DeusNexInternalException("Failed to store resourceNo lookup file", e);
            }
            createdNodes.add(folder);
        }
        for (Resource childResource : folderResource.getResources()) {
            importResource(importRoot, folder, childResource, deusNexDocument, createdNodes);
        }
    } else {
        if (node == null) {
            logger.fine("importing " + resource.getPath());
            Material material = createMaterial(importRoot, resource, deusNexDocument);
            if (material != null) {
                WorkspaceMaterialAssignmentType assignmentType = null;
                if (resource instanceof Query) {
                    switch(((Query) resource).getQueryType()) {
                        case "1":
                            assignmentType = WorkspaceMaterialAssignmentType.EXERCISE;
                            break;
                        case "2":
                            assignmentType = WorkspaceMaterialAssignmentType.EVALUATED;
                            break;
                    }
                } else if (material instanceof HtmlMaterial) {
                    assignmentType = determineEmbeddedAssignmentType((HtmlMaterial) material);
                }
                WorkspaceMaterial workspaceMaterial = workspaceMaterialController.createWorkspaceMaterial(parent, material, resource.getName(), assignmentType, WorkspaceMaterialCorrectAnswersDisplay.ALWAYS);
                try {
                    setResourceWorkspaceNodeId(resource.getNo(), workspaceMaterial.getId());
                } catch (IOException e) {
                    throw new DeusNexInternalException("Failed to store resourceNo lookup file", e);
                }
                if (resource instanceof ResourceContainer) {
                    List<Resource> childResources = ((ResourceContainer) resource).getResources();
                    if (childResources != null) {
                        for (Resource childResource : childResources) {
                            importResource(importRoot, workspaceMaterial, childResource, deusNexDocument, createdNodes);
                        }
                    }
                }
                if (resource.getHidden()) {
                    workspaceMaterialController.hideWorkspaceNode(workspaceMaterial);
                }
                createdNodes.add(workspaceMaterial);
            }
        } else {
            logger.info(node.getPath() + " already exists, skipping");
        }
    }
}
Also used : Query(fi.otavanopisto.muikku.plugins.dnm.parser.structure.model.Query) DeusNexInternalException(fi.otavanopisto.muikku.plugins.dnm.parser.DeusNexInternalException) Resource(fi.otavanopisto.muikku.plugins.dnm.parser.structure.model.Resource) Material(fi.otavanopisto.muikku.plugins.material.model.Material) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) BinaryMaterial(fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) IOException(java.io.IOException) WorkspaceMaterialAssignmentType(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialAssignmentType) WorkspaceFolder(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceFolder) Folder(fi.otavanopisto.muikku.plugins.dnm.parser.structure.model.Folder) WorkspaceNode(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceNode) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) WorkspaceFolder(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceFolder) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) ResourceContainer(fi.otavanopisto.muikku.plugins.dnm.parser.structure.model.ResourceContainer)

Example 12 with Material

use of fi.otavanopisto.muikku.plugins.material.model.Material 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);
    }
}
Also used : WorkspaceFieldIOException(fi.otavanopisto.muikku.plugins.workspace.fieldio.WorkspaceFieldIOException) Material(fi.otavanopisto.muikku.plugins.material.model.Material) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) IOException(java.io.IOException) WorkspaceFieldIOException(fi.otavanopisto.muikku.plugins.workspace.fieldio.WorkspaceFieldIOException) Date(java.util.Date) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) QueryField(fi.otavanopisto.muikku.plugins.material.model.QueryField) WebSocketMessage(fi.otavanopisto.muikku.plugins.websocket.WebSocketMessage) WorkspaceMaterialField(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialField) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 13 with Material

use of fi.otavanopisto.muikku.plugins.material.model.Material in project muikku by otavanopisto.

the class WorkspaceBinaryMaterialServlet method process.

private void process(HttpServletRequest request, HttpServletResponse response, boolean serveContent) throws ServletException, IOException {
    String workspaceUrl = request.getParameter("workspaceUrlName");
    String materialPath = request.getParameter("workspaceMaterialUrlName");
    WorkspaceEntity workspaceEntity = workspaceController.findWorkspaceEntityByUrlName(workspaceUrl);
    if (workspaceEntity == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    WorkspaceMaterial workspaceMaterial = workspaceMaterialController.findWorkspaceMaterialByWorkspaceEntityAndPath(workspaceEntity, materialPath);
    if (workspaceMaterial == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    Material material = workspaceMaterialController.getMaterialForWorkspaceMaterial(workspaceMaterial);
    int materialSize = material instanceof BinaryMaterial ? ((BinaryMaterial) material).getContent().length : material instanceof HtmlMaterial ? ((HtmlMaterial) material).getHtml().length() : 0;
    String eTag = DigestUtils.md5Hex(material.getTitle() + ':' + material.getId() + ':' + materialSize + ':' + material.getVersion());
    response.setHeader("ETag", eTag);
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (!StringUtils.equals(ifNoneMatch, eTag)) {
        response.setStatus(HttpServletResponse.SC_OK);
        if (material instanceof BinaryMaterial) {
            BinaryMaterial binaryMaterial = (BinaryMaterial) material;
            byte[] data = binaryMaterial.getContent();
            // Byte range support
            List<Range> ranges = new ArrayList<Range>();
            String range = request.getHeader("Range");
            if (range != null) {
                if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
                    response.setHeader("Content-Range", "bytes */" + data.length);
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }
                for (String part : range.substring(6).split(",")) {
                    String startStr = StringUtils.substringBefore(part, "-");
                    String endStr = StringUtils.substringAfter(part, "-");
                    int start = NumberUtils.isDigits(startStr) ? NumberUtils.toInt(startStr) : -1;
                    int end = NumberUtils.isDigits(endStr) ? NumberUtils.toInt(endStr) : -1;
                    if (start == -1) {
                        start = data.length - end;
                        end = data.length - 1;
                    } else if (end == -1 || end > data.length - 1) {
                        end = data.length - 1;
                    }
                    if (start > end) {
                        response.setHeader("Content-Range", "bytes */" + data.length);
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return;
                    }
                    ranges.add(new Range(start, end, data.length));
                }
            }
            response.setHeader("Accept-Ranges", "bytes");
            response.setContentType(binaryMaterial.getContentType());
            try {
                if (ranges.isEmpty()) {
                    // Entire file
                    if (serveContent) {
                        response.setHeader("Content-Length", String.valueOf(data.length));
                        response.getOutputStream().write(data);
                    }
                } else if (ranges.size() == 1) {
                    // Single byte range
                    Range r = ranges.get(0);
                    response.setHeader("Content-Range", String.format("bytes %d-%d/%d", r.start, r.end, r.total));
                    response.setHeader("Content-Length", String.valueOf(r.length));
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                    if (serveContent) {
                        response.getOutputStream().write(data, r.start, r.length);
                    }
                } else {
                    // Multiple byte ranges
                    response.setContentType("multipart/byteranges; boundary=MULTIPART_BYTERANGES");
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                    if (serveContent) {
                        for (Range r : ranges) {
                            response.getOutputStream().println();
                            response.getOutputStream().println("--MULTIPART_BYTERANGES");
                            response.getOutputStream().println(String.format("Content-Type: %s", binaryMaterial.getContentType()));
                            response.getOutputStream().println(String.format("Content-Range: bytes %d-%d/%d", r.start, r.end, r.total));
                            response.getOutputStream().write(data, r.start, r.length);
                        }
                        response.getOutputStream().println();
                        response.getOutputStream().println("--MULTIPART_BYTERANGES--");
                    }
                }
            } finally {
                response.getOutputStream().flush();
            }
        } else if (material instanceof HtmlMaterial) {
            HtmlMaterial htmlMaterial = (HtmlMaterial) material;
            byte[] data = htmlMaterial.getHtml().getBytes("UTF-8");
            response.setContentLength(data.length);
            response.setContentType("text/html; charset=UTF-8");
            try {
                response.getOutputStream().write(data);
            } finally {
                response.getOutputStream().flush();
            }
        }
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }
}
Also used : WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) ArrayList(java.util.ArrayList) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) Material(fi.otavanopisto.muikku.plugins.material.model.Material) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) BinaryMaterial(fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial) BinaryMaterial(fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial)

Example 14 with Material

use of fi.otavanopisto.muikku.plugins.material.model.Material 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();
    }
}
Also used : WorkspaceFieldIOException(fi.otavanopisto.muikku.plugins.workspace.fieldio.WorkspaceFieldIOException) ArrayList(java.util.ArrayList) WorkspaceMaterialCompositeReply(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceMaterialCompositeReply) Material(fi.otavanopisto.muikku.plugins.material.model.Material) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) WorkspaceUserEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) WorkspaceMaterialFieldAnswer(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceMaterialFieldAnswer) WorkspaceMaterialField(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialField) Path(javax.ws.rs.Path) RESTPermitUnimplemented(fi.otavanopisto.muikku.rest.RESTPermitUnimplemented) GET(javax.ws.rs.GET)

Example 15 with Material

use of fi.otavanopisto.muikku.plugins.material.model.Material in project muikku by otavanopisto.

the class DeusNexMachinaRESTService method cleanMaterials.

private void cleanMaterials(List<WorkspaceNode> nodes) {
    for (WorkspaceNode node : nodes) {
        if (node.getType() != WorkspaceNodeType.MATERIAL) {
            cleanMaterials(workspaceMaterialController.listWorkspaceNodesByParent(node));
        } else {
            WorkspaceMaterial workspaceMaterial = (WorkspaceMaterial) node;
            Material material = workspaceMaterialController.getMaterialForWorkspaceMaterial(workspaceMaterial);
            if ("html".equals(material.getType())) {
                logger.info("Cleaning html material " + material.getId());
                htmlMaterialCleaner.cleanMaterial((HtmlMaterial) material, workspaceMaterial);
            }
        }
    }
}
Also used : Material(fi.otavanopisto.muikku.plugins.material.model.Material) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) WorkspaceNode(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceNode) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial)

Aggregations

Material (fi.otavanopisto.muikku.plugins.material.model.Material)20 WorkspaceMaterial (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial)15 Path (javax.ws.rs.Path)10 HtmlMaterial (fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial)9 RESTPermitUnimplemented (fi.otavanopisto.muikku.rest.RESTPermitUnimplemented)7 WorkspaceNode (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceNode)6 GET (javax.ws.rs.GET)4 Produces (javax.ws.rs.Produces)4 WorkspaceEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceEntity)3 MaterialMeta (fi.otavanopisto.muikku.plugins.material.model.MaterialMeta)3 MaterialMetaKey (fi.otavanopisto.muikku.plugins.material.model.MaterialMetaKey)3 WorkspaceFieldIOException (fi.otavanopisto.muikku.plugins.workspace.fieldio.WorkspaceFieldIOException)3 WorkspaceFolder (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceFolder)3 RESTPermit (fi.otavanopisto.security.rest.RESTPermit)3 IOException (java.io.IOException)3 UserEntity (fi.otavanopisto.muikku.model.users.UserEntity)2 BinaryMaterial (fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial)2 WorkspaceMaterialField (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialField)2 ArrayList (java.util.ArrayList)2 DELETE (javax.ws.rs.DELETE)2