Search in sources :

Example 1 with HtmlElementTransformation

use of org.ambraproject.wombat.freemarker.HtmlElementTransformation in project wombat by PLOS.

the class EditorialContentApiImpl method readHtml.

/**
 * {@inheritDoc}
 * <p/>
 * Applies transforms to HTML attributes and performs substitution of placeholder HTML elements with stored content
 */
@Override
public Reader readHtml(final SitePageContext sitePageContext, String pageType, String key, final Set<HtmlElementTransformation> transformations, final Collection<HtmlElementSubstitution> substitutions) throws IOException {
    Map<String, Object> pageConfig = sitePageContext.getSite().getTheme().getConfigMap(pageType);
    // TODO May want to support page versioning at some point using fetchHtmlDirective
    ContentKey version = ContentKey.createForLatestVersion(key);
    CacheKey cacheKey = CacheKey.create(pageType, key);
    Number cacheTtl = (Number) pageConfig.get("cacheTtl");
    if (cacheTtl != null) {
        cacheKey = cacheKey.addTimeToLive(cacheTtl.intValue());
    }
    String transformedHtml = requestCachedReader(cacheKey, version, new CacheDeserializer<Reader, String>() {

        @Override
        public String read(Reader htmlReader) throws IOException {
            // It would be nice to feed the reader directly into the parser, but Jsoup's API makes this awkward.
            // The whole document will be in memory anyway, so buffering it into a string is no great performance loss.
            String htmlString = IOUtils.toString(htmlReader);
            Document document = Jsoup.parseBodyFragment(htmlString);
            for (HtmlElementTransformation transformation : transformations) {
                transformation.apply(sitePageContext, siteSet, document);
            }
            for (HtmlElementSubstitution substitution : substitutions) {
                substitution.substitute(document);
            }
            // We want to return only the transformed snippet, so retrieve it from the body tag.
            return document.getElementsByTag("body").html();
        }
    });
    return new StringReader(transformedHtml);
}
Also used : Reader(java.io.Reader) StringReader(java.io.StringReader) HtmlElementTransformation(org.ambraproject.wombat.freemarker.HtmlElementTransformation) IOException(java.io.IOException) Document(org.jsoup.nodes.Document) StringReader(java.io.StringReader) CacheKey(org.ambraproject.wombat.util.CacheKey) HtmlElementSubstitution(org.ambraproject.wombat.freemarker.HtmlElementSubstitution)

Aggregations

IOException (java.io.IOException)1 Reader (java.io.Reader)1 StringReader (java.io.StringReader)1 HtmlElementSubstitution (org.ambraproject.wombat.freemarker.HtmlElementSubstitution)1 HtmlElementTransformation (org.ambraproject.wombat.freemarker.HtmlElementTransformation)1 CacheKey (org.ambraproject.wombat.util.CacheKey)1 Document (org.jsoup.nodes.Document)1