Example usage for javax.xml.transform OutputKeys ENCODING

List of usage examples for javax.xml.transform OutputKeys ENCODING

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys ENCODING.

Prototype

String ENCODING

To view the source code for javax.xml.transform OutputKeys ENCODING.

Click Source Link

Document

encoding = string.

Usage

From source file:com.google.enterprise.connector.salesforce.BaseTraversalManager.java

/**
 * Converts the <document></document> xml into a BaseSimpleDocument object
 * that we can send into a documentList object that ultimately gets returned
 * to the connector-manager/*from w w  w.  ja  va 2  s. co  m*/
 * 
 * @param inxml
 *            the xml form of and individual <document></document> object
 */

private BaseSimpleDocument convertXMLtoBaseDocument(Document doc) {
    try {

        HashMap hm_spi = new HashMap();
        HashMap hm_meta_tags = new HashMap();
        Map props = new HashMap();
        String content_value = "";

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        // TODO: figure out why the initial doc passed in to the method
        // doesn't have the stylesheet 'fully' applied
        // this is why we do the conversion back and forth below
        // because for some reason the doc->string->doc has the stylesheet
        // applied.
        String sdoc = Util.XMLDoctoString(doc);
        logger.log(Level.FINEST, "About to convert STORE XML to BaseDocument " + sdoc);
        doc = Util.XMLStringtoDoc(sdoc);

        NodeList nl_document = doc.getElementsByTagName("document");

        Node ndoc = nl_document.item(0);

        NodeList nl_doc_child = ndoc.getChildNodes();

        for (int j = 0; j < nl_doc_child.getLength(); j++) {
            Node cnode = nl_doc_child.item(j);
            String doc_child_node_name = cnode.getNodeName();

            if (doc_child_node_name.equalsIgnoreCase("spiheaders")) {
                NodeList nl_spi = cnode.getChildNodes();
                for (int k = 0; k < nl_spi.getLength(); k++) {
                    Node n_spi = nl_spi.item(k);
                    if (n_spi.getNodeType() == Node.ELEMENT_NODE) {
                        String spi_name = n_spi.getAttributes().getNamedItem("name").getNodeValue();
                        String spi_value = "";
                        if (n_spi.getFirstChild() != null) {
                            spi_value = n_spi.getFirstChild().getNodeValue();
                            logger.log(Level.FINEST, "Adding SPI " + spi_name + " " + spi_value);
                        }
                        hm_spi.put(spi_name, spi_value);
                    }
                }
            }

            if (doc_child_node_name.equalsIgnoreCase("metadata")) {
                NodeList nl_meta = cnode.getChildNodes();
                for (int k = 0; k < nl_meta.getLength(); k++) {
                    Node n_meta = nl_meta.item(k);
                    if (n_meta.getNodeType() == Node.ELEMENT_NODE) {
                        String meta_name = n_meta.getAttributes().getNamedItem("name").getNodeValue();
                        String meta_value = "";
                        if (n_meta.getFirstChild() != null) {
                            meta_value = n_meta.getFirstChild().getNodeValue();
                            logger.log(Level.FINEST, "Adding METATAG " + meta_name + " " + meta_value);
                        }
                        hm_meta_tags.put(meta_name, meta_value);
                    }
                }
            }

            if (doc_child_node_name.equalsIgnoreCase("content")) {
                content_value = cnode.getChildNodes().item(0).getNodeValue();
                String encoding_type = "";
                NamedNodeMap attribs = cnode.getAttributes();
                if (attribs.getLength() > 0) {
                    Node attrib = attribs.getNamedItem("encoding");
                    if (attrib != null)
                        encoding_type = attrib.getNodeValue();

                    if (encoding_type.equalsIgnoreCase("base64")
                            || encoding_type.equalsIgnoreCase("base64binary")) {
                        byte[] b = org.apache.commons.codec.binary.Base64
                                .decodeBase64(content_value.getBytes());
                        ByteArrayInputStream input1 = new ByteArrayInputStream(b);
                        logger.log(Level.FINEST, "Adding base64 encoded CONTENT " + content_value);
                        props.put(SpiConstants.PROPNAME_CONTENT, input1);
                    } else {
                        logger.log(Level.FINEST, "Adding Text/HTML CONTENT " + content_value);
                        props.put(SpiConstants.PROPNAME_CONTENT, content_value);
                    }
                } else {
                    logger.log(Level.FINEST, "Adding default Text/HTML CONTENT " + content_value);
                    props.put(SpiConstants.PROPNAME_CONTENT, content_value);
                }
            }
        }

        // the hashmap holding the spi headers
        Iterator itr_spi = hm_spi.keySet().iterator();

        while (itr_spi.hasNext()) {
            String key = (String) itr_spi.next();
            String value = (String) hm_spi.get(key);

            if (key.equals("DEFAULT_MIMETYPE"))
                props.put(SpiConstants.DEFAULT_MIMETYPE, value);

            if (key.equals("PROPNAME_ACTION"))
                props.put(SpiConstants.PROPNAME_ACTION, value);

            if (key.equals("PROPNAME_CONTENTURL"))
                props.put(SpiConstants.PROPNAME_CONTENTURL, value);

            if (key.equals("PROPNAME_DISPLAYURL"))
                props.put(SpiConstants.PROPNAME_DISPLAYURL, value);

            if (key.equals("PROPNAME_DOCID"))
                props.put(SpiConstants.PROPNAME_DOCID, value);

            if (key.equals("PROPNAME_ISPUBLIC"))
                props.put(SpiConstants.PROPNAME_ISPUBLIC, value);

            if (key.equals("PROPNAME_LASTMODIFIED"))
                props.put(SpiConstants.PROPNAME_LASTMODIFIED, value);

            if (key.equals("PROPNAME_MIMETYPE"))
                props.put(SpiConstants.PROPNAME_MIMETYPE, value);

            // if (key.equals("PROPNAME_SEARCHURL"))
            // props.put(SpiConstants.PROPNAME_SEARCHURL, value);

            // if (key.equals("PROPNAME_SECURITYTOKEN"))
            // props.put(SpiConstants.PROPNAME_SECURITYTOKEN, value);

        }

        // hashmap holding the custom metatags
        Iterator itr_meta = hm_meta_tags.keySet().iterator();

        while (itr_meta.hasNext()) {
            String key = (String) itr_meta.next();
            String value = (String) hm_meta_tags.get(key);
            props.put(key, value);
        }

        BaseSimpleDocument bsd = createSimpleDocument(new Date(), props);
        return bsd;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Error " + ex);
    }
    return null;

}

From source file:com.ToResultSet.java

public static String getDocumentAsXml(Document doc)
        throws TransformerConfigurationException, TransformerException {
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    // we want to pretty format the XML output
    // note : this is broken in jdk1.5 beta!
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    ////from   ww  w  .j a  v a 2 s  .com
    java.io.StringWriter sw = new java.io.StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);
    return sw.toString();
}

From source file:com.legstar.cob2xsd.Cob2Xsd.java

/**
 * Serialize the XML Schema to a string.
 * <p/>//from  w  w  w  . j  a  v  a 2  s. c om
 * If we are provided with an XSLT customization file then we transform the
 * XMLSchema.
 * 
 * @param xsd the XML Schema before customization
 * @return a string serialization of the customized XML Schema
 * @throws XsdGenerationException if customization fails
 */
public String xsdToString(final XmlSchema xsd) throws XsdGenerationException {

    if (_log.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        xsd.write(writer);
        debug("6. Writing XML Schema: ", writer.toString());
    }

    String errorMessage = "Customizing XML Schema failed.";
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        try {
            tFactory.setAttribute("indent-number", "4");
        } catch (IllegalArgumentException e) {
            _log.debug("Unable to set indent-number on transfomer factory", e);
        }
        StringWriter writer = new StringWriter();
        Source source = new DOMSource(xsd.getAllSchemas()[0]);
        Result result = new StreamResult(writer);
        Transformer transformer;
        String xsltFileName = getModel().getCustomXsltFileName();
        if (xsltFileName == null || xsltFileName.trim().length() == 0) {
            transformer = tFactory.newTransformer();
        } else {
            Source xsltSource = new StreamSource(new File(xsltFileName));
            transformer = tFactory.newTransformer(xsltSource);
        }
        transformer.setOutputProperty(OutputKeys.ENCODING, getModel().getXsdEncoding());
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "no");

        transformer.transform(source, result);
        writer.flush();

        return writer.toString();
    } catch (TransformerConfigurationException e) {
        _log.error(errorMessage, e);
        throw new XsdGenerationException(e);
    } catch (TransformerFactoryConfigurationError e) {
        _log.error(errorMessage, e);
        throw new XsdGenerationException(e);
    } catch (TransformerException e) {
        _log.error(errorMessage, e);
        throw new XsdGenerationException(e);
    }
}

From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java

private void save() {
    try {/*from  ww  w. j  a v  a2s.c  o m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        for (Iterator iter = currencies.iterator(); iter.hasNext();) {
            Element node = document.createElement("currency"); //$NON-NLS-1$
            node.appendChild(document.createTextNode((String) iter.next()));
            root.appendChild(node);
        }

        for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
            String symbol = (String) iter.next();
            Element node = document.createElement("conversion"); //$NON-NLS-1$
            node.setAttribute("symbol", symbol); //$NON-NLS-1$
            node.setAttribute("ratio", String.valueOf(map.get(symbol))); //$NON-NLS-1$
            saveHistory(node, symbol);
            root.appendChild(node);
        }

        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMSource source = new DOMSource(document);

        File file = new File(Platform.getLocation().toFile(), "currencies.xml"); //$NON-NLS-1$

        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        out.close();
    } catch (Exception e) {
        logger.error(e, e);
    }
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createModuleDef(ArrayList list, String classname) {
    String result = "";
    try {/*w  ww .j  a  v  a 2s .  c  o  m*/

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile()));
        //Document doc = docBuilder.newDocument();
        NodeList modules = doc.getElementsByTagName("modules");
        Node modulesNode = modules.item(0);
        Element module_ex = doc.getElementById(classname);
        if (module_ex != null) {
            modulesNode.removeChild(module_ex);
        }
        Element module = doc.createElement("module");
        Element property_list = doc.createElement("property-list");
        module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname);
        module.setAttribute("type", "pojo");
        module.setAttribute("id", classname);
        for (int cnt = 0; cnt < list.size(); cnt++) {
            Element propertyNode = doc.createElement("property");
            Hashtable mapObj = (Hashtable) list.get(cnt);

            propertyNode.setAttribute("name", mapObj.get("name").toString());
            propertyNode.setAttribute("type", mapObj.get("type").toString().toLowerCase());
            property_list.appendChild(propertyNode);

        }

        module.appendChild(property_list);
        modulesNode.appendChild(module);
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/module.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);
        //       result  = sw.toString();

    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    } finally {
        // System.out.println(result);
        // return result;
    }
}

From source file:com.messagehub.samples.servlet.KafkaServlet.java

public String toPrettyString(String xml, int indent) {
    try {//from  w w  w  . j av a  2 s . c om
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java

/**
 * query to xml/*w  w w  .  j a  v  a 2  s  . c  o  m*/
 * 
 * @param userDB
 * @param strQuery
 * @param listParam
 */
@SuppressWarnings("deprecation")
public static String selectToXML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam)
        throws Exception {
    final StringWriter stWriter = new StringWriter();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();
    final Element results = doc.createElement("Results");
    doc.appendChild(results);

    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
    QueryRunner qr = new QueryRunner(client.getDataSource());
    qr.query(strQuery, listParam.toArray(), new ResultSetHandler<Object>() {

        @Override
        public Object handle(ResultSet rs) throws SQLException {
            ResultSetMetaData metaData = rs.getMetaData();

            while (rs.next()) {
                Element row = doc.createElement("Row");
                results.appendChild(row);
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i) == null ? "" : rs.getObject(i);
                    Element node = doc.createElement(columnName);
                    node.appendChild(doc.createTextNode(value.toString()));
                    row.appendChild(node);
                }
            }

            return stWriter.toString();
        }
    });

    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setAttribute("indent-number", 4);

    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1");
    StreamResult sr = new StreamResult(stWriter);
    transformer.transform(domSource, sr);

    return stWriter.toString();
}

From source file:com.aurel.track.report.datasource.faqs.FaqsDatasource.java

/**
 * @param items/*w ww. ja v  a2s . com*/
 * @return
 */
public static void convertToXml(OutputStream outputStream, Document dom) {
    Transformer transformer = null;
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD XHTML 1.0 Transitional//EN");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
    } catch (TransformerConfigurationException e) {
        LOGGER.error(
                "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage());
        return;
    }
    try {
        transformer.transform(new DOMSource(dom), new StreamResult(outputStream));
    } catch (TransformerException e) {
        LOGGER.error("Transform failed with TransformerException: " + e.getMessage());
    }
}

From source file:org.apache.syncope.core.util.ImportExport.java

public void export(final OutputStream os) throws SAXException, TransformerConfigurationException {

    StreamResult streamResult = new StreamResult(os);
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();//from ww w  .ja  va 2 s  .c  om

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    final Connection conn = DataSourceUtils.getConnection(dataSource);

    ResultSet rs = null;

    try {
        final DatabaseMetaData meta = conn.getMetaData();

        final String schema = readSchema();

        rs = meta.getTables(null, schema, null, new String[] { "TABLE" });

        final Set<String> tableNames = new HashSet<String>();

        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");

            // these tables must be ignored
            if (!tableName.toUpperCase().startsWith("QRTZ_")
                    && !tableName.toUpperCase().startsWith("LOGGING_")) {
                tableNames.add(tableName);
            }
        }

        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames, schema)) {
            doExportTable(handler, conn, tableName);
        }
    } 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);
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}

From source file:eu.europa.esig.dss.XmlDom.java

/**
 * This method writes formatted {@link org.w3c.dom.Node} to the outputStream.
 *
 * @param node/*from  w  w  w .j a  v a 2 s.c o m*/
 * @param out
 */
private static void printDocument(final Node node, final OutputStream out, final boolean raw) {

    try {

        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        if (!raw) {

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
        }
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        final DOMSource xmlSource = new DOMSource(node);
        final OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        final StreamResult outputTarget = new StreamResult(writer);
        transformer.transform(xmlSource, outputTarget);
    } catch (Exception e) {
        throw new DSSException(e);
    }

}