Example usage for javax.xml.transform OutputKeys METHOD

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

Introduction

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

Prototype

String METHOD

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

Click Source Link

Document

method = "xml" | "html" | "text" | expanded name.

Usage

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

/**
 * query to xml//from  w ww.  j  a  va  2 s .  c om
 * 
 * @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//from  w  ww . j  ava  2s .c o  m
 * @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:eu.europa.esig.dss.XmlDom.java

/**
 * This method writes formatted {@link org.w3c.dom.Node} to the outputStream.
 *
 * @param node/*from   ww w  .j a va2s.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);
    }

}

From source file:net.sf.joost.trax.TransformerImpl.java

/**
 * Setter for {@link Processor#outputProperties}
 *
 * @param oformat A <code>Properties</code> object, that replaces the
 *        current set of output properties.
 * @throws IllegalArgumentException/*w w w  . jav  a2 s. c o m*/
 */
public void setOutputProperties(Properties oformat) throws IllegalArgumentException {
    if (oformat == null) {
        processor.initOutputProperties(); // re-initialize
    } else {
        IllegalArgumentException iE;
        // check properties in oformat
        for (Enumeration e = oformat.keys(); e.hasMoreElements();) {
            Object propKey = e.nextElement();
            if (ignoredProperties.contains(propKey)) {
                if (log != null)
                    log.warn("Output property '" + propKey + "' is not supported and will be ignored");
                continue;
            }
            if (!supportedProperties.contains(propKey)) {
                iE = new IllegalArgumentException("Invalid output property '" + propKey + "'");
                if (log != null)
                    log.error(iE);
                throw iE;
            }
            String propVal = oformat.getProperty((String) propKey);
            if (OutputKeys.METHOD.equals(propKey) && !isValidOutputMethod(propVal)) {
                iE = new IllegalArgumentException(
                        "Unsupported output method " + oformat.getProperty((String) propKey));
                if (log != null)
                    log.error(iE);
                throw iE;
            }
        }
        processor.outputProperties = (Properties) oformat.clone();
    }
}

From source file:net.sourceforge.eclipsetrader.ats.Repository.java

protected void saveDocument(Document document, String path, String name) {
    try {/* w w w.j av a  2 s.com*/
        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4));
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4");
        DOMSource source = new DOMSource(document);

        File file = new File(Platform.getLocation().toFile(), path);
        file.mkdirs();
        file = new File(file, name);

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

From source file:com.amalto.workbench.utils.XSDGenerateHTML.java

/**
 * Handle a markup element by caching information in a map.
 * /*w w  w .  j  av a 2 s.c o m*/
 * @param markupMap the map to contain the markup.
 * @param markupElement the element specifying the markup.
 */
public void handleMarkup(Map markupMap, Element markupElement) {
    String keyList = markupElement.getAttribute("key"); //$NON-NLS-1$
    for (StringTokenizer stringTokenizer = new StringTokenizer(keyList); stringTokenizer.hasMoreTokens();) {
        String key = stringTokenizer.nextToken();
        String markup = markupElement.getAttribute("markup"); //$NON-NLS-1$
        if (markup.length() > 0) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();

                transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
                transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$

                for (Node grandChild = markupElement
                        .getFirstChild(); grandChild != null; grandChild = grandChild.getNextSibling()) {
                    if (grandChild.getNodeType() == Node.ELEMENT_NODE) {
                        transformer.transform(new DOMSource(grandChild), new StreamResult(out));
                    }
                }
                String serialization = out.toString();
                serialization = serialization.substring(serialization.indexOf("<div>")); //$NON-NLS-1$
                markupMap.put(key, markup + "@" + serialization); //$NON-NLS-1$
            } catch (Exception exception) {
                exception.printStackTrace(System.err);
            }
        }
    }
}

From source file:com.mediaworx.xmlutils.XmlHelper.java

/**
 * Converts the document to a formatted XML String (indentation level is 4) using the given encoding.
 * @param document      The document to be converted to String
 * @param cdataElements String array containing the names of all elements that are to be added within CDATA sections
 * @param encoding      encoding to be used (added in the XML declaration)
 * @return  the String representation of the given Document
 *///from   ww w.j  a v  a 2  s . co  m
public String getXmlStringFromDocument(Document document, String[] cdataElements, String encoding) {
    cleanEmptyTextNodes(document);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tf.newTransformer();
    } catch (TransformerConfigurationException e) {
        LOG.error("Exception configuring the XML transformer", e);
        return "";
    }
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    if (cdataElements != null && cdataElements.length > 0) {
        String cdataElementsJoined = StringUtils.join(cdataElements, ' ');
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataElementsJoined);
    }
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    OutputStream out = new ByteArrayOutputStream();
    try {
        transformer.transform(new DOMSource(document), new StreamResult(out));
    } catch (TransformerException e) {
        LOG.error("Exception transforming the XML document to String", e);
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            // it seems the output stream was closed already
            LOG.warn("Exception closing the output stream", e);
        }
    }
    StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"").append(encoding)
            .append("\"?>\n");
    xml.append(out.toString());
    return xml.toString();
}

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

/********** Uploading OpenRosa Surveys and Results **********/

public boolean parseAndPersistSurvey(InputStreamReader inputStreamReader, String contentType)
        throws IOException {
    String surveyString = parseMultipartEncodedFile(inputStreamReader, contentType, "filename");
    String surveyId = null;//from   ww w  . j  av a 2  s.c om
    String surveyIdOriginal = null;

    Document surveyDomDocument = null;
    ByteArrayInputStream streamToParse = new ByteArrayInputStream(surveyString.getBytes("UTF-8"));
    try {
        surveyDomDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(streamToParse);
    } catch (SAXException e) {
        e.printStackTrace();
        return false;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return false;
    } finally {
        streamToParse.close();
    }

    NodeList dataNodeList = surveyDomDocument.getElementsByTagName("data");
    if (dataNodeList.getLength() != 1) {
        return false; // there MUST be exactly 1 <data> node
    } else {
        Element dataElement = (Element) dataNodeList.item(0);
        Random rand = new Random(System.currentTimeMillis());
        int newId = rand.nextInt(Integer.MAX_VALUE);
        surveyId = String.valueOf(newId);
        surveyIdOriginal = dataElement.getAttribute("id");
        dataElement.setAttribute("id", String.valueOf(newId));
        StringWriter stringWriter = null;
        try {
            Source source = new DOMSource(surveyDomDocument);
            stringWriter = new StringWriter();
            Result result = new StreamResult(stringWriter);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "no");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.transform(source, result);
            surveyString = stringWriter.getBuffer().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            stringWriter.close();
        }
        log.info("========================");
        log.info("Original Survey Id: " + surveyIdOriginal);
        log.info("New Survey Id: " + surveyId);
        log.info("========================");
    }
    return persistSurvey(surveyString, surveyId, surveyIdOriginal);
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Utils.java

public static String documentToString(Document document) throws TransformerException {
    StringWriter sw = new StringWriter();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    transformer.transform(new DOMSource(document), new StreamResult(sw));

    return sw.toString();
}

From source file:com.bluexml.xforms.controller.FluxFacade.java

public static void prettyPrintDOM(Node node, OutputStream stream) throws TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.transform(new DOMSource(node), new StreamResult(stream));
}