Search in sources :

Example 21 with HtmlMaterial

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

the class WorkspaceMaterialController method getMaterialHtml.

private String getMaterialHtml(Material material, DOMParser parser, Transformer transformer) throws WorkspaceMaterialException {
    try {
        if (material instanceof HtmlMaterial) {
            String html = ((HtmlMaterial) material).getHtml();
            if (html == null) {
                return null;
            }
            StringReader htmlReader = new StringReader(html);
            try {
                InputSource inputSource = new InputSource(htmlReader);
                parser.parse(inputSource);
                Document document = parser.getDocument();
                NodeList imgList = document.getElementsByTagName("img");
                for (int i = 0, l = imgList.getLength(); i < l; i++) {
                    Element img = (Element) imgList.item(i);
                    String imgClass = img.getAttribute("class");
                    img.setAttribute("class", imgClass == null ? "lazy" : imgClass + " lazy");
                    img.setAttribute("data-original", img.getAttribute("src"));
                    img.removeAttribute("src");
                }
                NodeList iframeList = document.getElementsByTagName("iframe");
                for (int i = iframeList.getLength() - 1; i >= 0; i--) {
                    Element iframe = (Element) iframeList.item(i);
                    iframe.setAttribute("data-url", iframe.getAttribute("src"));
                    iframe.removeAttribute("src");
                    if (iframe.hasAttribute("class")) {
                        iframe.setAttribute("class", iframe.getAttribute("class") + " lazyFrame");
                    } else {
                        iframe.setAttribute("class", "lazyFrame");
                    }
                }
                StringWriter writer = new StringWriter();
                NodeList bodyChildren = (NodeList) XPathFactory.newInstance().newXPath().evaluate("//body/*", document, XPathConstants.NODESET);
                for (int i = 0, l = bodyChildren.getLength(); i < l; i++) {
                    transformer.transform(new DOMSource(bodyChildren.item(i)), new StreamResult(writer));
                }
                return writer.getBuffer().toString();
            } finally {
                htmlReader.close();
            }
        }
        return null;
    } catch (IOException | XPathExpressionException | TransformerException | SAXException e) {
        throw new WorkspaceMaterialException(e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamResult(javax.xml.transform.stream.StreamResult) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) TransformerException(javax.xml.transform.TransformerException)

Example 22 with HtmlMaterial

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

the class WorkspaceMaterialController method ensureWorkspaceFrontPageExists.

public WorkspaceMaterial ensureWorkspaceFrontPageExists(WorkspaceEntity workspace) {
    WorkspaceFolder frontPageFolder = findWorkspaceFrontPageFolder(workspace);
    if (frontPageFolder == null) {
        frontPageFolder = createWorkspaceFrontPageFolder(workspace);
    }
    WorkspaceMaterial frontPageMaterial = null;
    List<WorkspaceMaterial> frontPageMaterials = listWorkspaceMaterialsByParent(frontPageFolder);
    if (frontPageMaterials.isEmpty()) {
        String title = localeController.getText(sessionController.getLocale(), "plugin.workspace.frontPage.title");
        String license = null;
        HtmlMaterial htmlMaterial = htmlMaterialController.createHtmlMaterial(title, "", "text/html", 0l, license);
        frontPageMaterial = createWorkspaceMaterial(frontPageFolder, htmlMaterial);
    } else {
        frontPageMaterial = frontPageMaterials.get(0);
    }
    return frontPageMaterial;
}
Also used : HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) WorkspaceFolder(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceFolder)

Example 23 with HtmlMaterial

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

the class CoOpsApiImpl method fileGet.

public File fileGet(String fileId, Long revisionNumber) throws CoOpsNotImplementedException, CoOpsNotFoundException, CoOpsUsageException, CoOpsInternalErrorException, CoOpsForbiddenException {
    HtmlMaterial htmlMaterial = findFile(fileId);
    if (htmlMaterial == null) {
        throw new CoOpsNotFoundException();
    }
    if (revisionNumber != null) {
        String data = htmlMaterialController.getRevisionHtml(htmlMaterial, revisionNumber);
        Map<String, String> properties = htmlMaterialController.getRevisionProperties(htmlMaterial, revisionNumber);
        return new File(revisionNumber, data, htmlMaterial.getContentType(), properties);
    } else {
        Long maxRevisionNumber = htmlMaterialController.lastHtmlMaterialRevision(htmlMaterial);
        String data = htmlMaterialController.getRevisionHtml(htmlMaterial, maxRevisionNumber);
        Map<String, String> properties = htmlMaterialController.getRevisionProperties(htmlMaterial, maxRevisionNumber);
        return new File(maxRevisionNumber, data, htmlMaterial.getContentType(), properties);
    }
}
Also used : CoOpsNotFoundException(fi.foyt.coops.CoOpsNotFoundException) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) File(fi.foyt.coops.model.File)

Example 24 with HtmlMaterial

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

the class CoOpsDocumentWebSocket method onOpen.

@OnOpen
public void onOpen(final Session client, EndpointConfig endpointConfig, @PathParam("HTMLMATERIALID") String htmlMaterialId, @PathParam("SESSIONID") String sessionId) throws IOException {
    synchronized (this) {
        // 
        // TODO: RequestScope is not available on the websockets, switch to ticket system
        // 
        // if (!sessionController.isLoggedIn()) {
        // client.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Permission denied"));
        // }
        // 
        // UserEntity userEntity = sessionController.getLoggedUserEntity();
        // 
        // EnvironmentUser environmentUser = environmentUserController.findEnvironmentUserByUserEntity(userEntity);
        // 
        // if (environmentUser.getRole() == null || environmentUser.getRole().getArchetype() == EnvironmentRoleArchetype.STUDENT) {
        // client.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Permission denied"));
        // }
        CoOpsSession session = coOpsSessionController.findSessionBySessionId(sessionId);
        if (session == null) {
            client.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Not Found"));
            return;
        }
        if (!session.getHtmlMaterial().getId().equals(NumberUtils.createLong(htmlMaterialId))) {
            client.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Session is associated with another fileId"));
            return;
        }
        Map<String, Session> sessions = fileClients.get(htmlMaterialId);
        if (sessions == null) {
            fileClients.put(htmlMaterialId, new HashMap<String, Session>());
        }
        fileClients.get(htmlMaterialId).put(client.getId(), client);
        coOpsSessionController.updateSessionType(session, CoOpsSessionType.WS);
        HtmlMaterial htmlMaterial = session.getHtmlMaterial();
        Long currentRevisionNumber = htmlMaterial.getRevisionNumber();
        if (session.getJoinRevision() < currentRevisionNumber) {
            ObjectMapper objectMapper = new ObjectMapper();
            List<Patch> patches;
            try {
                patches = coOpsApi.fileUpdate(session.getHtmlMaterial().getId().toString(), session.getSessionId(), session.getJoinRevision());
                for (Patch patch : patches) {
                    sendPatch(client, patch);
                }
            } catch (CoOpsInternalErrorException e) {
                client.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "Internal Error"));
            } catch (CoOpsUsageException e) {
                client.getAsyncRemote().sendText(objectMapper.writeValueAsString(new ErrorMessage("patchError", 400, e.getMessage())));
            } catch (CoOpsNotFoundException e) {
                client.getAsyncRemote().sendText(objectMapper.writeValueAsString(new ErrorMessage("patchError", 404, e.getMessage())));
            } catch (CoOpsForbiddenException e) {
                client.getAsyncRemote().sendText(objectMapper.writeValueAsString(new ErrorMessage("patchError", 500, e.getMessage())));
            }
        }
    }
}
Also used : CoOpsUsageException(fi.foyt.coops.CoOpsUsageException) CoOpsSession(fi.otavanopisto.muikku.plugins.material.coops.model.CoOpsSession) CoOpsForbiddenException(fi.foyt.coops.CoOpsForbiddenException) CloseReason(javax.websocket.CloseReason) CoOpsInternalErrorException(fi.foyt.coops.CoOpsInternalErrorException) CoOpsNotFoundException(fi.foyt.coops.CoOpsNotFoundException) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) ErrorMessage(fi.foyt.coops.extensions.websocket.ErrorMessage) Patch(fi.foyt.coops.model.Patch) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) CoOpsSession(fi.otavanopisto.muikku.plugins.material.coops.model.CoOpsSession) Session(javax.websocket.Session) OnOpen(javax.websocket.OnOpen)

Example 25 with HtmlMaterial

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

the class MaterialUnEmbedder method unembedHtmlMaterial.

private void unembedHtmlMaterial(WorkspaceNode parent, WorkspaceMaterial workspaceMaterial, HtmlMaterial htmlMaterial) throws DeusNexInternalException, IOException {
    String html = htmlMaterial.getHtml();
    if (StringUtils.isNotBlank(html)) {
        InputStream is = null;
        logger.info("Unembedding html material " + htmlMaterial.getId());
        try {
            is = new ByteArrayInputStream(html.getBytes("UTF-8"));
            DocumentBuilder builder = DeusNexXmlUtils.createDocumentBuilder();
            Document document = builder.parse(is);
            if (document != null) {
                NodeList iframes = DeusNexXmlUtils.findNodesByXPath(document.getDocumentElement(), "//iframe[@data-type='embedded-document']");
                if (iframes.getLength() > 0) {
                    List<Document> splittedHtmlDocument = splitHtmlDocument(document);
                    for (int i = 0; i < splittedHtmlDocument.size(); i++) {
                        List<Long> pieceList = new ArrayList<Long>();
                        htmlMaterialPieces.put(htmlMaterial.getId(), pieceList);
                        HashMap<Long, WorkspaceMaterialAssignmentType> assignmentTypes = new HashMap<Long, WorkspaceMaterialAssignmentType>();
                        Document documentPiece = splittedHtmlDocument.get(i);
                        List<HtmlMaterial> pieceHtmlMaterials;
                        if (isEmbedPiece(documentPiece)) {
                            WorkspaceMaterialAssignmentType assignmentType = embeddedHtmlMaterialAssignmentType(documentPiece);
                            pieceHtmlMaterials = new ArrayList<HtmlMaterial>();
                            long embeddedHtmlMaterialId = embeddedHtmlMaterialId(documentPiece);
                            if (htmlMaterialPieces.containsKey(embeddedHtmlMaterialId)) {
                                for (Long htmlMaterialId : htmlMaterialPieces.get(embeddedHtmlMaterialId)) {
                                    logger.info("Existing html material " + htmlMaterialId + " embedded in " + htmlMaterial.getId());
                                    HtmlMaterial pieceHtmlMaterial = htmlMaterialController.findHtmlMaterialById(htmlMaterialId);
                                    pieceHtmlMaterials.add(pieceHtmlMaterial);
                                    pieceList.add(pieceHtmlMaterial.getId());
                                    assignmentTypes.put(pieceHtmlMaterial.getId(), assignmentType);
                                }
                            } else {
                                HtmlMaterial pieceHtmlMaterial = htmlMaterialController.findHtmlMaterialById(embeddedHtmlMaterialId);
                                logger.info("Existing html material " + embeddedHtmlMaterialId + " embedded in " + htmlMaterial.getId());
                                pieceHtmlMaterials.add(pieceHtmlMaterial);
                                pieceList.add(pieceHtmlMaterial.getId());
                                assignmentTypes.put(pieceHtmlMaterial.getId(), assignmentType);
                            }
                        } else {
                            String license = null;
                            HtmlMaterial pieceHtmlMaterial = htmlMaterialController.createHtmlMaterial(htmlMaterial.getTitle() + " (" + i + ")", DeusNexXmlUtils.serializeElement(documentPiece.getDocumentElement(), true, false, "xml"), "text/html; editor=CKEditor", 0l, license);
                            logger.info("New html material piece " + pieceHtmlMaterial.getId() + " split from " + htmlMaterial.getId());
                            pieceHtmlMaterials = new ArrayList<HtmlMaterial>();
                            pieceHtmlMaterials.add(pieceHtmlMaterial);
                            pieceList.add(pieceHtmlMaterial.getId());
                        }
                        for (HtmlMaterial pieceHtmlMaterial : pieceHtmlMaterials) {
                            WorkspaceNode newNode = workspaceMaterialController.createWorkspaceMaterial(parent, pieceHtmlMaterial, assignmentTypes.get(pieceHtmlMaterial.getId()), WorkspaceMaterialCorrectAnswersDisplay.ALWAYS);
                            workspaceMaterialController.moveAbove(newNode, workspaceMaterial);
                        }
                    }
                    workspaceMaterialController.deleteWorkspaceMaterial(workspaceMaterial, true);
                    htmlMaterialController.deleteHtmlMaterial(htmlMaterial);
                } else {
                    logger.info("Html material " + htmlMaterial.getId() + " has no embeds");
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Html material " + htmlMaterial.getId() + " unembed fail", e);
            throw new DeusNexInternalException("MaterialUnEmbedder:unembedHtmlMaterial", e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NodeList(org.w3c.dom.NodeList) DeusNexInternalException(fi.otavanopisto.muikku.plugins.dnm.parser.DeusNexInternalException) ArrayList(java.util.ArrayList) WorkspaceMaterialAssignmentType(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialAssignmentType) Document(org.w3c.dom.Document) WorkspaceNode(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceNode) XPathExpressionException(javax.xml.xpath.XPathExpressionException) TransformerException(javax.xml.transform.TransformerException) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) IOException(java.io.IOException) JsonGenerationException(org.codehaus.jackson.JsonGenerationException) DeusNexInternalException(fi.otavanopisto.muikku.plugins.dnm.parser.DeusNexInternalException) JsonParseException(org.codehaus.jackson.JsonParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) ByteArrayInputStream(java.io.ByteArrayInputStream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial)

Aggregations

HtmlMaterial (fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial)29 WorkspaceMaterial (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial)14 WorkspaceNode (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceNode)10 CoOpsNotFoundException (fi.foyt.coops.CoOpsNotFoundException)7 CoOpsUsageException (fi.foyt.coops.CoOpsUsageException)7 Material (fi.otavanopisto.muikku.plugins.material.model.Material)7 Path (javax.ws.rs.Path)7 CoOpsInternalErrorException (fi.foyt.coops.CoOpsInternalErrorException)6 WorkspaceFolder (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceFolder)5 IOException (java.io.IOException)5 CoOpsForbiddenException (fi.foyt.coops.CoOpsForbiddenException)4 CoOpsNotImplementedException (fi.foyt.coops.CoOpsNotImplementedException)4 File (fi.foyt.coops.model.File)4 WorkspaceEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceEntity)4 CoOpsSession (fi.otavanopisto.muikku.plugins.material.coops.model.CoOpsSession)4 WorkspaceMaterialContainsAnswersExeption (fi.otavanopisto.muikku.plugins.workspace.WorkspaceMaterialContainsAnswersExeption)4 RESTPermit (fi.otavanopisto.security.rest.RESTPermit)4 Patch (fi.foyt.coops.model.Patch)3 BinaryMaterial (fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial)3 WorkspaceMaterialAssignmentType (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialAssignmentType)3