Search in sources :

Example 61 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project syncope by apache.

the class XMLContentExporter method export.

@Override
public void export(final String domain, final OutputStream os, final String uwfPrefix, final String gwfPrefix, final String awfPrefix) throws SAXException, TransformerConfigurationException {
    if (StringUtils.isNotBlank(uwfPrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(uwfPrefix);
    }
    if (StringUtils.isNotBlank(gwfPrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(gwfPrefix);
    }
    if (StringUtils.isNotBlank(awfPrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(awfPrefix);
    }
    StreamResult streamResult = new StreamResult(os);
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());
    DataSource dataSource = domainsHolder.getDomains().get(domain);
    if (dataSource == null) {
        throw new IllegalArgumentException("Could not find DataSource for domain " + domain);
    }
    String dbSchema = ApplicationContextProvider.getBeanFactory().getBean(domain + "DatabaseSchema", String.class);
    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);
        final DatabaseMetaData meta = conn.getMetaData();
        rs = meta.getTables(null, StringUtils.isBlank(dbSchema) ? null : dbSchema, null, new String[] { "TABLE" });
        final Set<String> tableNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            LOG.debug("Found table {}", tableName);
            if (isTableAllowed(tableName)) {
                tableNames.add(tableName);
            }
        }
        LOG.debug("Tables to be exported {}", tableNames);
        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(dbSchema, conn, tableNames)) {
            try {
                doExportTable(handler, dbSchema, conn, tableName, TABLES_TO_BE_FILTERED.get(tableName.toUpperCase()));
            } catch (Exception e) {
                LOG.error("Failure exporting table {}", tableName, e);
            }
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
        if (conn != null) {
            try {
                if (!conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                LOG.error("While releasing connection", e);
            }
        }
    }
    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) SQLException(java.sql.SQLException) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) Connection(java.sql.Connection) DatabaseMetaData(java.sql.DatabaseMetaData) SAXException(org.xml.sax.SAXException) SQLException(java.sql.SQLException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException) DataSource(javax.sql.DataSource) AttributesImpl(org.xml.sax.helpers.AttributesImpl) TreeSet(java.util.TreeSet) ResultSet(java.sql.ResultSet)

Example 62 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project spring-boot-quick by vector4wang.

the class TikaUtil method getHtmlHandler.

private static ContentHandler getHtmlHandler(Writer writer) throws TransformerConfigurationException {
    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
    handler.setResult(new StreamResult(writer));
    return new ContentHandlerDecorator(handler) {

        @Override
        public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException {
            if (XHTMLContentHandler.XHTML.equals(uri)) {
                uri = null;
            }
            if (!"head".equals(localName)) {
                if ("img".equals(localName)) {
                    AttributesImpl newAttrs;
                    if (atts instanceof AttributesImpl) {
                        newAttrs = (AttributesImpl) atts;
                    } else {
                        newAttrs = new AttributesImpl(atts);
                    }
                    for (int i = 0; i < newAttrs.getLength(); i++) {
                        if ("src".equals(newAttrs.getLocalName(i))) {
                            String src = newAttrs.getValue(i);
                            if (src.startsWith("embedded:")) {
                                String filename = src.substring(src.indexOf(':') + 1);
                                try {
                                    File img = imageParser.requestSave(filename);
                                    String newSrc = img.toURI().toString();
                                    newAttrs.setValue(i, newSrc);
                                } catch (IOException e) {
                                    System.err.println("Error creating temp image file " + filename);
                                // The html viewer will show a broken image too to alert them
                                }
                            }
                        }
                    }
                    super.startElement(uri, localName, name, newAttrs);
                } else {
                    super.startElement(uri, localName, name, atts);
                }
            }
        }

        @Override
        public void endElement(String uri, String localName, String name) throws SAXException {
            if (XHTMLContentHandler.XHTML.equals(uri)) {
                uri = null;
            }
            if (!"head".equals(localName)) {
                super.endElement(uri, localName, name);
            }
        }

        @Override
        public void startPrefixMapping(String prefix, String uri) {
        }

        @Override
        public void endPrefixMapping(String prefix) {
        }
    };
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) AttributesImpl(org.xml.sax.helpers.AttributesImpl) StreamResult(javax.xml.transform.stream.StreamResult) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) Attributes(org.xml.sax.Attributes) ContentHandlerDecorator(org.apache.tika.sax.ContentHandlerDecorator)

Example 63 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project jackrabbit by apache.

the class ExportDocViewTest method doTestExportDocView.

/**
 * Tests session.exportDocView with the different argument possibilities.
 * The flag withHandler decides if the method requiring a ContentHandler as
 * argument is called. The class org.apache.xml.serialize.XMLSerializer is
 * taken as ContentHandler in this case. In both cases ( export with a
 * ContentHandler and export with Stream) the test node is exported to the
 * file defined in the setUp. This exported file is parsed using
 * javax.xml.transform package and the receiving document is compared with
 * the test node and its properties and child nodes in the repository.
 *
 * @param withHandler boolean, decides to call method requiring a
 *                    ContentHandler as argument
 * @param skipBinary
 * @param noRecurse
 */
public void doTestExportDocView(boolean withHandler, boolean skipBinary, boolean noRecurse) throws RepositoryException, IOException, SAXException, TransformerException {
    this.skipBinary = skipBinary;
    this.noRecurse = noRecurse;
    this.withHandler = withHandler;
    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
    try {
        if (withHandler) {
            SAXTransformerFactory stf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            TransformerHandler th = stf.newTransformerHandler();
            th.setResult(new StreamResult(os));
            session.exportDocumentView(testPath, th, skipBinary, noRecurse);
        } else {
            session.exportDocumentView(testPath, os, skipBinary, noRecurse);
        }
    } finally {
        os.close();
    }
    // build the DOM tree
    InputStream in = new BufferedInputStream(new FileInputStream(file));
    doc = readDocument(in);
    compareTree();
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) StreamResult(javax.xml.transform.stream.StreamResult) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) BufferedOutputStream(java.io.BufferedOutputStream) FileInputStream(java.io.FileInputStream)

Example 64 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project jackrabbit by apache.

the class ResultHelper method needsXmlnsAttributes.

/**
 * Probes the available XML serializer for xmlns support. Used to set
 * the value of the {@link #NEEDS_XMLNS_ATTRIBUTES} flag.
 *
 * @return whether the XML serializer needs explicit xmlns attributes
 */
private static boolean needsXmlnsAttributes() {
    try {
        StringWriter writer = new StringWriter();
        TransformerHandler probe = FACTORY.newTransformerHandler();
        probe.setResult(new StreamResult(writer));
        probe.startDocument();
        probe.startPrefixMapping("p", "uri");
        probe.startElement("uri", "e", "p:e", new AttributesImpl());
        probe.endElement("uri", "e", "p:e");
        probe.endPrefixMapping("p");
        probe.endDocument();
        return writer.toString().indexOf("xmlns") == -1;
    } catch (Exception e) {
        throw new UnsupportedOperationException("XML serialization fails");
    }
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) AttributesImpl(org.xml.sax.helpers.AttributesImpl) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SAXException(org.xml.sax.SAXException)

Example 65 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project jackrabbit by apache.

the class ResultHelper method getResult.

/**
 * In case the underlying XML library doesn't properly handle xmlns attributes
 * this method creates new content handler dealing with the misbehavior and
 * returns an new instance of SAXResult. Otherwise the passed result
 * is returned back.
 *
 * @param result
 * @return A instance of <code>Result</code> that properly handles xmlns attributes.
 * @throws SAXException
 */
public static Result getResult(Result result) throws SAXException {
    try {
        TransformerHandler handler = FACTORY.newTransformerHandler();
        handler.setResult(result);
        // Specify the output properties to avoid surprises especially in
        // character encoding or the output method (might be html for some
        // documents!)
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        if (NEEDS_XMLNS_ATTRIBUTES) {
            // so we need to do it explicitly with this wrapper
            return new SAXResult(new SerializingContentHandler(handler));
        } else {
            return result;
        }
    } catch (TransformerConfigurationException e) {
        throw new SAXException("Failed to initialize XML serializer", e);
    }
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) Transformer(javax.xml.transform.Transformer) SAXResult(javax.xml.transform.sax.SAXResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SAXException(org.xml.sax.SAXException)

Aggregations

TransformerHandler (javax.xml.transform.sax.TransformerHandler)84 StreamResult (javax.xml.transform.stream.StreamResult)57 SAXTransformerFactory (javax.xml.transform.sax.SAXTransformerFactory)51 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)33 Transformer (javax.xml.transform.Transformer)29 IOException (java.io.IOException)23 SAXException (org.xml.sax.SAXException)22 AttributesImpl (org.xml.sax.helpers.AttributesImpl)17 StringWriter (java.io.StringWriter)13 SAXResult (javax.xml.transform.sax.SAXResult)13 File (java.io.File)11 XMLReader (org.xml.sax.XMLReader)11 FileOutputStream (java.io.FileOutputStream)10 Test (org.junit.Test)10 InputStream (java.io.InputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 OutputStream (java.io.OutputStream)8 ContentHandler (org.xml.sax.ContentHandler)8 InputSource (org.xml.sax.InputSource)8 Metadata (org.apache.tika.metadata.Metadata)7