Search in sources :

Example 1 with SafeContentHandler

use of org.apache.tika.sax.SafeContentHandler in project tika by apache.

the class FileResourceConsumer method getXMLifiedLogMsg.

/**
     * Use this for structured output that captures resourceId and other attributes.
     *
     * @param type entity name for exception
     * @param resourceId resourceId string
     * @param t throwable can be null
     * @param attrs (array of key0, value0, key1, value1, etc.)
     */
protected String getXMLifiedLogMsg(String type, String resourceId, Throwable t, String... attrs) {
    ContentHandler toXML = new ToXMLContentHandler();
    SafeContentHandler handler = new SafeContentHandler(toXML);
    AttributesImpl attributes = new AttributesImpl();
    attributes.addAttribute("", "resourceId", "resourceId", "", resourceId);
    for (int i = 0; i < attrs.length - 1; i++) {
        attributes.addAttribute("", attrs[i], attrs[i], "", attrs[i + 1]);
    }
    try {
        handler.startDocument();
        handler.startElement("", type, type, attributes);
        if (t != null) {
            StringWriter stackWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stackWriter);
            t.printStackTrace(printWriter);
            printWriter.flush();
            stackWriter.flush();
            char[] chars = stackWriter.toString().toCharArray();
            handler.characters(chars, 0, chars.length);
        }
        handler.endElement("", type, type);
        handler.endDocument();
    } catch (SAXException e) {
        LOG.warn("error writing xml stream for: {}", resourceId, t);
    }
    return handler.toString();
}
Also used : ToXMLContentHandler(org.apache.tika.sax.ToXMLContentHandler) AttributesImpl(org.xml.sax.helpers.AttributesImpl) StringWriter(java.io.StringWriter) SafeContentHandler(org.apache.tika.sax.SafeContentHandler) ToXMLContentHandler(org.apache.tika.sax.ToXMLContentHandler) SafeContentHandler(org.apache.tika.sax.SafeContentHandler) ContentHandler(org.xml.sax.ContentHandler) PrintWriter(java.io.PrintWriter) SAXException(org.xml.sax.SAXException)

Aggregations

PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 SafeContentHandler (org.apache.tika.sax.SafeContentHandler)1 ToXMLContentHandler (org.apache.tika.sax.ToXMLContentHandler)1 ContentHandler (org.xml.sax.ContentHandler)1 SAXException (org.xml.sax.SAXException)1 AttributesImpl (org.xml.sax.helpers.AttributesImpl)1