Search in sources :

Example 61 with Content

use of org.jdom2.Content in project mycore by MyCoRe-Org.

the class MCRMetsCommands method validateSelectedMets.

@MCRCommand(syntax = "validate selected mets", help = "validates all mets.xml of selected derivates", order = 10)
public static void validateSelectedMets() {
    List<String> selectedObjectIDs = MCRObjectCommands.getSelectedObjectIDs();
    for (String objectID : selectedObjectIDs) {
        LOGGER.info("Validate mets.xml of {}", objectID);
        MCRPath metsFile = MCRPath.getPath(objectID, "/mets.xml");
        if (Files.exists(metsFile)) {
            try {
                MCRContent content = new MCRPathContent(metsFile);
                InputStream metsIS = content.getInputStream();
                METSValidator mv = new METSValidator(metsIS);
                List<ValidationException> validationExceptionList = mv.validate();
                if (validationExceptionList.size() > 0) {
                    invalidMetsQueue.add(objectID);
                }
                for (ValidationException validationException : validationExceptionList) {
                    LOGGER.error(validationException.getMessage());
                }
            } catch (IOException e) {
                LOGGER.error("Error while reading mets.xml of {}", objectID, e);
            } catch (JDOMException e) {
                LOGGER.error("Error while parsing mets.xml of {}", objectID, e);
            }
        }
    }
}
Also used : ValidationException(org.mycore.mets.validator.validators.ValidationException) InputStream(java.io.InputStream) MCRPathContent(org.mycore.common.content.MCRPathContent) METSValidator(org.mycore.mets.validator.METSValidator) IOException(java.io.IOException) MCRPath(org.mycore.datamodel.niofs.MCRPath) JDOMException(org.jdom2.JDOMException) MCRContent(org.mycore.common.content.MCRContent) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 62 with Content

use of org.jdom2.Content in project mycore by MyCoRe-Org.

the class MCRUserTransformer method getDocument.

private static Document getDocument(MCRUser user) {
    MCRJAXBContent<MCRUser> content = new MCRJAXBContent<>(JAXB_CONTEXT, user);
    try {
        Document userXML = content.asXML();
        sortAttributes(userXML);
        return userXML;
    } catch (SAXParseException | JDOMException | IOException e) {
        throw new MCRException("Exception while transforming MCRUser " + user.getUserID() + " to JDOM document.", e);
    }
}
Also used : MCRJAXBContent(org.mycore.common.content.MCRJAXBContent) MCRException(org.mycore.common.MCRException) SAXParseException(org.xml.sax.SAXParseException) MCRUser(org.mycore.user2.MCRUser) IOException(java.io.IOException) Document(org.jdom2.Document) JDOMException(org.jdom2.JDOMException)

Example 63 with Content

use of org.jdom2.Content in project ddf by codice.

the class OpenSearchSource method createResponseFromEntry.

/**
 * Creates a single response from input parameters. Performs XPath operations on the document to
 * retrieve data not passed in.
 *
 * @param entry a single Atom entry
 * @return single response
 */
private List<Result> createResponseFromEntry(SyndEntry entry) throws UnsupportedQueryException {
    String id = entry.getUri();
    if (StringUtils.isNotEmpty(id)) {
        id = id.substring(id.lastIndexOf(':') + 1);
    }
    List<SyndContent> contents = entry.getContents();
    List<SyndCategory> categories = entry.getCategories();
    List<Metacard> metacards = new ArrayList<>();
    List<Element> foreignMarkup = entry.getForeignMarkup();
    String relevance = "";
    for (Element element : foreignMarkup) {
        if (element.getName().equals("score")) {
            relevance = element.getContent(0).getValue();
        }
        metacards.addAll(processAdditionalForeignMarkups(element, id));
    }
    // added at a later date if we decide to include it
    for (SyndContent content : contents) {
        Metacard metacard = parseContent(content.getValue(), id);
        if (metacard != null) {
            metacard.setSourceId(this.shortname);
            String title = metacard.getTitle();
            if (StringUtils.isEmpty(title)) {
                metacard.setAttribute(new AttributeImpl(Core.TITLE, entry.getTitle()));
            }
            metacards.add(metacard);
        }
    }
    for (int i = 0; i < categories.size() && i < metacards.size(); i++) {
        SyndCategory category = categories.get(i);
        Metacard metacard = metacards.get(i);
        if (StringUtils.isBlank(metacard.getContentTypeName())) {
            metacard.setAttribute(new AttributeImpl(Metacard.CONTENT_TYPE, category.getName()));
        }
    }
    List<Result> results = new ArrayList<>();
    for (Metacard metacard : metacards) {
        ResultImpl result = new ResultImpl(metacard);
        if (StringUtils.isEmpty(relevance)) {
            LOGGER.debug("Couldn't find valid relevance. Setting relevance to 0");
            relevance = "0";
        }
        result.setRelevanceScore(new Double(relevance));
        results.add(result);
    }
    return results;
}
Also used : SyndCategory(com.rometools.rome.feed.synd.SyndCategory) Element(org.jdom2.Element) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) ArrayList(java.util.ArrayList) ResultImpl(ddf.catalog.data.impl.ResultImpl) Result(ddf.catalog.data.Result) Metacard(ddf.catalog.data.Metacard) SyndContent(com.rometools.rome.feed.synd.SyndContent)

Example 64 with Content

use of org.jdom2.Content in project jPOS by jpos.

the class FSDMsgTest method testPackToBDStoLong.

@Test
public void testPackToBDStoLong() throws Throwable {
    Element schema = createSchema();
    appendField(schema, "name", "B", "DS", 8);
    FSDMsg fSDMsg = new FSDMsg(SCHEMA_PREFIX);
    fSDMsg.set("name", ISOUtil.hexString("Test message".getBytes()));
    try {
        fSDMsg.packToBytes();
        fail("FSDMsg.packToBytes() should throw RuntimeException when content is too long");
    } catch (RuntimeException ex) {
    }
}
Also used : Element(org.jdom2.Element) Test(org.junit.jupiter.api.Test)

Example 65 with Content

use of org.jdom2.Content in project hippo by NHS-digital-website.

the class RssModifier method modifyEntry.

@Override
public void modifyEntry(final HstRequestContext context, final Item entry, final HippoBean bean) {
    String scope = "";
    String requestPath = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
    SimpleDateFormat lastUpdatedDateFormat = new SimpleDateFormat("dd MMM yyyy");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    if (bean instanceof Blog) {
        try {
            requestPath = context.getBaseURL().getRequestPath();
            final String statement = "/jcr:root/content/documents/corporate-website/feeds//*[@jcr:primaryType='feed:rss20descriptor']";
            Session session = context.getSession();
            final Query q = session.getWorkspace().getQueryManager().createQuery(statement, Query.XPATH);
            final NodeIterator nodes = q.execute().getNodes();
            while (nodes.hasNext()) {
                Node node = nodes.nextNode();
                scope = node.getProperty("feed:scope").getString();
                if (requestPath.contains("/" + scope)) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        final Blog blogBean = (Blog) bean;
        final Date lastUpdated = blogBean.getLastModified();
        if (lastUpdated != null) {
            HstLink hstLink = context.getHstLinkCreator().create(bean, context);
            String blogPath = bean.getPath();
            if (hstLink != null && (StringUtils.isNotBlank(scope) && blogPath.contains("/" + scope)) || requestPath.contains("all-blog")) {
                List<Element> foreignMarkup = entry.getForeignMarkup();
                foreignMarkup.add(getElement("title", blogBean.getTitle()));
                Element lmElement = new Element("author");
                String emailAddress = "enquiries@nhsdigital.nhs.uk";
                StringBuilder strPerson = new StringBuilder();
                if (blogBean.getAuthors() != null && blogBean.getAuthors().size() > 0) {
                    Person person = (Person) blogBean.getAuthors().get(0);
                    if (person.getRoles() != null && person.getRoles().getContactdetails() != null) {
                        final ContactDetail contactdetails = person.getRoles().getContactdetails();
                        if (StringUtils.isBlank(contactdetails.getEmailaddress())) {
                            strPerson.append(emailAddress);
                        } else {
                            strPerson.append(contactdetails.getEmailaddress());
                        }
                        strPerson.append(" (" + contactdetails.getName() + ")");
                    }
                } else {
                    strPerson.append(emailAddress);
                    if (StringUtils.isNotBlank(blogBean.getAuthorName())) {
                        strPerson.append(" (" + blogBean.getAuthorName() + ")");
                    } else {
                        strPerson.append("(NHS Digital)");
                    }
                }
                lmElement.addContent(StringUtils.isNotBlank(strPerson.toString()) ? strPerson.toString() : "enquiries@nhsdigital.nhs.uk (NHS Digital)");
                foreignMarkup.add(lmElement);
                String category = blogBean.getCategories();
                if (StringUtils.isNotBlank(category)) {
                    foreignMarkup.add(getElement("category", category));
                }
                foreignMarkup.add(getElement("description", blogBean.getAllDescription()));
                Element guid = getElement("guid", blogBean.getGuid());
                guid.setAttribute("isPermaLink", "false");
                foreignMarkup.add(guid);
                foreignMarkup.add(getElement("pubDate", dateFormat.format(lastUpdated)));
                foreignMarkup.add(getElement("link", hstLink.toUrlForm(context, true)));
                Element source = getElement("source", "NHS Digital");
                source.setAttribute("url", "https://digital.nhs.uk");
                foreignMarkup.add(source);
                final HippoGalleryImageSetBean image = blogBean.getLeadImage();
                if (image != null) {
                    hstLink = context.getHstLinkCreator().create(image, context);
                    if (hstLink != null) {
                        foreignMarkup = entry.getForeignMarkup();
                        String imageUrl = hstLink.toUrlForm(context, true);
                        final Element element = getImageElement(imageUrl);
                        foreignMarkup.add(element);
                    }
                }
            }
        }
    } else if (bean instanceof News) {
        final News newsBean = (News) bean;
        List<Element> foreignMarkup = entry.getForeignMarkup();
        foreignMarkup.add(getElement("title", newsBean.getTitle()));
        ContactDetail contactDetail = newsBean.getMediacontact();
        String author = "NHS Digital";
        String emailAddress = "enquiries@nhsdigital.nhs.uk";
        if (contactDetail != null && StringUtils.isNotBlank(contactDetail.getName())) {
            author = contactDetail.getName();
            emailAddress = contactDetail.getEmailaddress();
        }
        foreignMarkup.add(getElement("author", (emailAddress + " (" + author + ")")));
        StringBuilder content = new StringBuilder();
        for (HippoBean sre : newsBean.getSections()) {
            String tempContent = new String();
            if (sre instanceof Section) {
                tempContent = ((Section) sre).getHtmlJson();
            } else if (sre instanceof EmphasisBox) {
                tempContent = ((EmphasisBox) sre).getBodyJson();
            } else if (sre instanceof Expander) {
                tempContent = ((Expander) sre).getContent().getContent();
            } else if (sre instanceof Quote) {
                tempContent = ((Quote) sre).getQuote().getContent();
            }
            content.append(tempContent);
        }
        foreignMarkup.add(getElement("description", content.toString()));
        String category = getNewsCategory(newsBean);
        if (StringUtils.isNotBlank(category)) {
            foreignMarkup.add(getElement("category", category));
        }
        Element guid = getElement("guid", newsBean.getCanonicalUUID());
        guid.setAttribute("isPermaLink", "false");
        foreignMarkup.add(guid);
        String formatted = dateFormat.format(newsBean.getLastModified());
        foreignMarkup.add(getElement("pubDate", formatted));
        HstLink hstLink = context.getHstLinkCreator().create(bean, context);
        String urlNews = hstLink.toUrlForm(context, true);
        foreignMarkup.add(getElement("link", urlNews));
        String tempUrl = urlNews.substring(0, urlNews.indexOf(context.getBaseURL().getHostName()));
        String finalUrl = tempUrl + context.getBaseURL().getHostName() + context.getBaseURL().getContextPath() + context.getHstLinkCreator().getBinariesPrefix();
        final LeadImageSection leadimagesection = newsBean.getLeadimagesection();
        if (leadimagesection != null && leadimagesection.getLeadImage() != null) {
            String imageUrl = finalUrl + leadimagesection.getLeadImage().getCanonicalHandlePath();
            Element imageElement = getImageElement(imageUrl);
            foreignMarkup.add(imageElement);
        }
        Element source = getElement("source", "NHS Digital");
        source.setAttribute("url", "https://digital.nhs.uk");
        foreignMarkup.add(source);
    } else if (bean instanceof Publication) {
        List<Element> foreignMarkup = entry.getForeignMarkup();
        final Publication publicationBean = (Publication) bean;
        String docPath = bean.getPath();
        if (docPath.contains("/publication-system/")) {
            foreignMarkup.add(getElement("title", publicationBean.getTitle()));
            foreignMarkup.add(getElement("author", "enquiries@nhsdigital.nhs.uk (NHS Digital)"));
            StringBuilder description = new StringBuilder();
            for (uk.nhs.digital.ps.beans.structuredText.Element tempDesc : publicationBean.getSummary().getElements()) {
                description.append(tempDesc);
            }
            foreignMarkup.add(getElement("description", description.toString()));
            String category = getCategory(publicationBean);
            if (StringUtils.isNotBlank(category)) {
                foreignMarkup.add(getElement("category", category));
            }
            Element guid = getElement("guid", publicationBean.getCanonicalUUID());
            guid.setAttribute("isPermaLink", "false");
            foreignMarkup.add(guid);
            String formatted = dateFormat.format(publicationBean.getLastModified());
            foreignMarkup.add(getElement("pubDate", formatted));
            HstLink hstLink = context.getHstLinkCreator().create(bean, context);
            String url = hstLink.toUrlForm(context, true);
            foreignMarkup.add(getElement("link", url));
            String tempUrl1 = url.substring(0, url.indexOf(context.getBaseURL().getHostName()));
            String finalUrl = tempUrl1 + context.getBaseURL().getHostName() + context.getBaseURL().getContextPath() + context.getHstLinkCreator().getBinariesPrefix();
            for (Infographic test : publicationBean.getKeyFactInfographics()) {
                if (test.getIcon() != null) {
                    foreignMarkup.add(getImageElement(finalUrl + test.getIcon().getCanonicalHandlePath()));
                }
            }
            Element source = getElement("source", "NHS Digital");
            source.setAttribute("url", "https://digital.nhs.uk");
            foreignMarkup.add(source);
        }
    } else if (bean instanceof CyberAlert) {
        List<Element> foreignMarkup = entry.getForeignMarkup();
        final CyberAlert cyberAlertBean = (CyberAlert) bean;
        foreignMarkup.add(getElement("title", cyberAlertBean.getThreatId() + " - " + cyberAlertBean.getTitle()));
        foreignMarkup.add(getElement("category", cyberAlertBean.getSeverity()));
        foreignMarkup.add(getElement("author", "enquiries@nhsdigital.nhs.uk (NHS Digital)"));
        foreignMarkup.add(getElement("description", "<p>Severity: " + cyberAlertBean.getSeverity() + "</p>" + " " + cyberAlertBean.getSummary().getContent() + "<p> " + cyberAlertBean.getShortsummary() + "</p><p> Updated: " + lastUpdatedDateFormat.format(cyberAlertBean.getLastModified()) + "</p>"));
        Element guid = getElement("guid", cyberAlertBean.getCanonicalUUID());
        guid.setAttribute("isPermaLink", "false");
        foreignMarkup.add(guid);
        String pubDate = dateFormat.format(cyberAlertBean.getPublishedDate().getTime());
        foreignMarkup.add(getElement("pubDate", pubDate));
        HstLink hstLink = context.getHstLinkCreator().create(bean, context);
        String url = hstLink.toUrlForm(context, true);
        foreignMarkup.add(getElement("link", url));
    }
}
Also used : HstQuery(org.hippoecm.hst.content.beans.query.HstQuery) Query(javax.jcr.query.Query) Node(javax.jcr.Node) HstLink(org.hippoecm.hst.core.linking.HstLink) Element(org.jdom2.Element) HippoBean(org.hippoecm.hst.content.beans.standard.HippoBean) NodeIterator(javax.jcr.NodeIterator) HippoGalleryImageSetBean(org.hippoecm.hst.content.beans.standard.HippoGalleryImageSetBean) Publication(uk.nhs.digital.ps.beans.Publication) FilterException(org.hippoecm.hst.content.beans.query.exceptions.FilterException) QueryException(org.hippoecm.hst.content.beans.query.exceptions.QueryException) SimpleDateFormat(java.text.SimpleDateFormat) Session(javax.jcr.Session)

Aggregations

Element (org.jdom2.Element)77 Document (org.jdom2.Document)27 IOException (java.io.IOException)18 JDOMException (org.jdom2.JDOMException)16 File (java.io.File)11 MCRException (org.mycore.common.MCRException)11 Content (org.jdom2.Content)10 MCRContent (org.mycore.common.content.MCRContent)10 MCRJDOMContent (org.mycore.common.content.MCRJDOMContent)10 XMLOutputter (org.jdom2.output.XMLOutputter)9 SAXBuilder (org.jdom2.input.SAXBuilder)8 ArrayList (java.util.ArrayList)7 Test (org.junit.Test)7 Attribute (org.jdom2.Attribute)6 MCRPath (org.mycore.datamodel.niofs.MCRPath)6 SAXException (org.xml.sax.SAXException)6 JsonElement (com.google.gson.JsonElement)5 Color (java.awt.Color)4 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)4 MCRObject (org.mycore.datamodel.metadata.MCRObject)4