PlainTextTransformer.java 2.49 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.cq.dam.cfm.ContentFragmentException
 *  org.apache.sling.xss.XSSAPI
 */
package com.adobe.cq.dam.cfm.impl.transformer;

import com.adobe.cq.dam.cfm.ContentFragmentException;
import com.adobe.cq.dam.cfm.impl.transformer.Transformer;
import org.apache.sling.xss.XSSAPI;

public class PlainTextTransformer
implements Transformer {
    @Override
    public String getContentType() {
        return "text/plain";
    }

    @Override
    public String fromHTML(String html) throws ContentFragmentException {
        html = html.replaceAll("[\\n\\r\\t]?", "");
        html = html.replaceAll("<br[^<>]*>", "\n");
        String text = html.replaceAll("</(p|h[123456]|div|pre|li|td|th|address|blockquote|center|caption)[^<>]*>", "\n\n");
        text = text.trim();
        text = text.replaceAll("</?[a-z][a-z0-9]*[^<>]*>", "");
        text = text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&amp;", "&").replaceAll("&nbsp;", " ");
        return text;
    }

    @Override
    public String toHTML(String formattedText, XSSAPI xss) throws ContentFragmentException {
        StringBuilder htmlBuilder = new StringBuilder((int)((double)formattedText.length() * 1.1));
        if (formattedText.length() == 0) {
            return "";
        }
        formattedText = formattedText.trim();
        int startPos = 0;
        do {
            int lfPos;
            String frag;
            if ((lfPos = formattedText.indexOf("\n\n", startPos)) > 0) {
                htmlBuilder.append("<p>");
                if (startPos != lfPos) {
                    frag = formattedText.substring(startPos, lfPos);
                    htmlBuilder.append(xss.encodeForHTML(frag));
                } else {
                    htmlBuilder.append("&nbsp;");
                }
                htmlBuilder.append("</p>\r");
                startPos = lfPos + 2;
                continue;
            }
            htmlBuilder.append("<p>");
            if (startPos < formattedText.length()) {
                frag = formattedText.substring(startPos);
                htmlBuilder.append(xss.encodeForHTML(frag));
            } else {
                htmlBuilder.append("&nbsp;");
            }
            htmlBuilder.append("</p>");
            startPos = -1;
        } while (startPos >= 0);
        String html = htmlBuilder.toString();
        html = html.replaceAll("\n", "<br>");
        return html.replaceAll("\r", "\n");
    }
}