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:de.betterform.agent.betty.Betty.java

protected String renderForm(Document document) throws Exception {
    // todo: determine from browser document
    String encoding = "UTF-8";

    LOGGER.debug("renderForm");
    // obtain transformer for stylesheet uri
    String stylesheetParameter = getParameter(XSLT_PARAMETER);
    if (stylesheetParameter == null || stylesheetParameter.length() == 0) {
        stylesheetParameter = XSLT_DEFAULT;
    }//from w  w w .ja  va2s  . c  o  m
    LOGGER.debug("stylesheetParameter: " + stylesheetParameter);
    URI stylesheetURI = new URI(getCodeBase().toString()).resolve(stylesheetParameter);
    LOGGER.debug("styleSheetURI: " + stylesheetURI);

    TransformerService transformerService = new CachingTransformerService(new FileResourceResolver());
    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    Transformer transformer = transformerService.getTransformer(stylesheetURI);

    // setup source and result objects
    Source documentSource = new DOMSource(document);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Result streamResult = new StreamResult(stream);

    // go
    transformer.setParameter("debug-enabled", String.valueOf(LOGGER.isDebugEnabled()));
    transformer.setParameter("betterform-pseudo-item", BETTERFORM_PSEUDO_ITEM);
    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    transformer.transform(documentSource, streamResult);

    String result = stream.toString(encoding);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("result >>>>>:" + result);
    }

    //        return result.substring(result.indexOf("<form"),result.lastIndexOf("</html>"));
    return result.substring(result.indexOf("<form"));
}

From source file:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java

protected void processTempFile(final File df, final String fileEncoding, final String xmlVersion,
        final String header, final String footer, final TDocument persistenceConfig, final Pair collectivite,
        final Pair codeBudget, final File originalFile, final int docCount, final boolean shouldDelete,
        final int progress) {
    try {/*from w  w w. ja  v  a  2  s.c om*/
        long startFile = System.currentTimeMillis();
        String data = FileUtils.readTextFile(df, fileEncoding);
        StringBuilder fullText = new StringBuilder();
        fullText.append("<?xml version=\"").append(xmlVersion).append("\" encoding=\"").append(fileEncoding)
                .append("\"?>");
        fullText.append(header).append(data).append(footer);
        String sFullText = fullText.toString();
        byte[] bData = sFullText.getBytes(fileEncoding);

        Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(bData));

        // il faut retrouver de quel etat est ce document
        // on cherche si la balise root contient un
        // dm.getEtatxxx().getBalise()
        EtatModel currentEtat = null;
        for (EtatModel em : dm.getEtats()) {
            String balise = em.getBalise();
            NodeList nl = doc.getElementsByTagName(balise);
            if (nl.getLength() > 0) {
                currentEtat = em;
                break;
            } else {
                nl = doc.getElementsByTagNameNS(em.getBaliseNamespace(), balise);
                if (nl.getLength() > 0) {
                    currentEtat = em;
                    break;
                }
            }
        }
        // traitement d'erreur, on n'arrive pas  identifier l'etat
        if (currentEtat == null) {
            StringWriter sw = new StringWriter();
            sw.append("Impossible de dterminer l'tat de ce document :\n");
            TransformerFactory errorTransFactory = FactoryProvider.getTransformerFactory();
            Transformer errorTransformer = errorTransFactory.newTransformer();
            errorTransformer.transform(new DOMSource(doc), new StreamResult(sw));
            sw.flush();
            sw.close();
            logger.error(sw.getBuffer().toString());
            return;
        }
        // apply before-import xslt
        if (persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile() != null) {
            Transformer trans = importXsltCache
                    .get(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile());
            if (trans == null) {
                TransformerFactory tf = FactoryProvider.getTransformerFactory();
                File directory = new File(currentEtat.getParent().getBaseDirectory());
                File xslFile = new File(directory,
                        persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile());
                trans = tf.newTransformer(new StreamSource(xslFile));
                importXsltCache.put(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile(), trans);
            }
            // important, maintenant que c'est mis en cache !
            trans.reset();
            if (codeBudget != null) {
                trans.setParameter("CodeBudget", codeBudget.key);
                trans.setParameter("LibelleBudget", codeBudget.libelle);
            }
            if (collectivite != null) {
                trans.setParameter("CodeCollectivite", collectivite.key);
                trans.setParameter("LibelleCollectivite", collectivite.libelle);
            }
            if (getManifeste() != null) {
                trans.setParameter("manifeste", new DOMSource(getManifeste()));
            }
            // on passe en parametre le nom du fichier
            trans.setParameter("file.name", originalFile.getName());

            trans.setOutputProperty(OutputKeys.ENCODING, fileEncoding);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            trans.transform(new StreamSource(new ByteArrayInputStream(sFullText.getBytes(fileEncoding))),
                    new StreamResult(baos));
            bData = baos.toByteArray();
        }
        importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm())
                .append(";XSL;").append(Long.toString(startFile)).append(";")
                .append(Long.toString(startFile = System.currentTimeMillis()));
        importTimingOS.println();

        String docName = StringUtilities.removeFileNameSuffix(originalFile.getName()) + "-" + docCount + "."
                + dm.getExtension();
        if (!isCancelled()) {
            try {
                if (!DataLayerManager.getImplementation().importElement(dm, currentEtat, codeBudget,
                        collectivite, originalFile.getName(), docName, bData, fileEncoding, getArchiveName(),
                        user)) {
                    logger.warn(DataLayerManager.getImplementation().getWarnings());
                    warningCount++;
                }
            } catch (DataAccessException daEx) {
                logger.error("importing element:", daEx);
                throw (Exception) daEx;
            } catch (DataConfigurationException dcEx) {
                logger.error("importing element:", dcEx);
                throw (Exception) dcEx.getCause();
            }
        }
        if (shouldDelete) {
            df.delete();
        }
        importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm())
                .append(";IDX;").append(Long.toString(startFile)).append(";")
                .append(Long.toString(startFile = System.currentTimeMillis()));
        importTimingOS.println();
        this.getImpSvcProvider().pushCurrentProgress(progress);
    } catch (Exception ex) {
        //TODO
    }
}

From source file:net.sf.joost.stx.Processor.java

/**
 * Initialize the output properties to the values specified in the
 * transformation sheet or to their default values, resp.
 *//*  w w  w.  j a va2 s  .  c o m*/
public void initOutputProperties() {
    outputProperties = new Properties();
    outputProperties.setProperty(OutputKeys.ENCODING, transformNode.outputEncoding);
    outputProperties.setProperty(OutputKeys.MEDIA_TYPE, "text/xml");
    outputProperties.setProperty(OutputKeys.METHOD, transformNode.outputMethod);
    outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    outputProperties.setProperty(OutputKeys.STANDALONE, "no");
    outputProperties.setProperty(OutputKeys.VERSION, "1.0");
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

private byte[] createRequestXml(String action, ImmutablePair<String, String>... params) {
    try {//  w w w . j a  va 2s  .c o m
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMessage = factory.createMessage();

        SOAPBodyElement actionElement = soapMessage.getSOAPBody().addBodyElement(new QName(null, action, "m"));
        actionElement.addNamespaceDeclaration("m", serviceType);

        for (Pair<String, String> param : params) {
            SOAPElement paramElement = actionElement.addChildElement(QName.valueOf(param.getKey()));
            paramElement.setValue(param.getValue());
        }

        soapMessage.getSOAPPart().setXmlStandalone(true);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(baos));

        return baos.toByteArray();
    } catch (IllegalArgumentException | SOAPException | TransformerException | DOMException e) {
        throw new IllegalStateException(e); // should never happen
    }
}

From source file:it.drwolf.ridire.session.async.Mapper.java

/**
 * Returns a transformer handler that serializes incoming SAX events to
 * XHTML or HTML (depending the given method) using the given output
 * encoding.//w  w w . ja v  a 2  s .  c  o m
 * 
 * @see <a
 *      href="https://issues.apache.org/jira/browse/TIKA-277">TIKA-277</a>
 * @param method
 *            "xml" or "html"
 * @param encoding
 *            output encoding, or <code>null</code> for the platform default
 * @param writer
 * @return {@link System#out} transformer handler
 * @throws TransformerConfigurationException
 *             if the transformer can not be created
 */
private TransformerHandler getTransformerHandler(String method, String encoding, Writer writer)
        throws TransformerConfigurationException {
    SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    if (encoding != null) {
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encoding);
    }
    handler.setResult(new StreamResult(writer));
    return handler;
}

From source file:com.adaptris.util.XmlUtils.java

private void serialize(DOMSource doc, StreamResult result, String encoding)
        throws TransformerFactoryConfigurationError, TransformerException {
    String enc = defaultIfEmpty(encoding, DEFAULT_XML_CHARSET);
    Transformer serializer = TransformerFactory.newInstance().newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, enc);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    serializer.transform(doc, result);//from ww  w.j a va  2  s . com
}

From source file:com.marklogic.xcc.ContentFactory.java

static byte[] bytesFromW3cNode(Node node) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Result rslt = new StreamResult(bos);
    Source src = new DOMSource(node);
    Transformer transformer;//from ww  w.ja  v a 2s.c  o  m

    try {
        transformer = getTransformerFactory().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(src, rslt);
    } catch (TransformerException e) {
        throw new RuntimeException("Cannot serialize Node: " + e, e);
    }

    return bos.toByteArray();
}

From source file:com.hp.mqm.atrf.App.java

private void convertToXml(List<TestRunResultEntity> runResults, StreamResult result, boolean formatXml) {

    try {//from  w  w  w.j a  v a  2 s.c o  m
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("test_result");
        doc.appendChild(rootElement);

        Element testRuns = doc.createElement("test_runs");
        rootElement.appendChild(testRuns);

        for (TestRunResultEntity runResult : runResults) {
            Element testRun = doc.createElement("test_run");
            testRuns.appendChild(testRun);

            testRun.setAttribute("module", runResult.getModule());
            testRun.setAttribute("package", runResult.getPackageValue());
            testRun.setAttribute("class", runResult.getClassValue());
            testRun.setAttribute("name", runResult.getTestName());

            testRun.setAttribute("duration", runResult.getDuration());
            testRun.setAttribute("status", runResult.getStatus());
            testRun.setAttribute("started", runResult.getStartedTime());
            testRun.setAttribute("external_report_url", runResult.getExternalReportUrl());
            testRun.setAttribute("run_name", runResult.getRunName());

            Element testFields = doc.createElement("test_fields");
            testRun.appendChild(testFields);

            if (StringUtils.isNotEmpty(runResult.getTestingToolType())) {
                Element testField = doc.createElement("test_field");
                testFields.appendChild(testField);
                testField.setAttribute("type", "Testing_Tool_Type");
                testField.setAttribute("value", runResult.getTestingToolType());
            }

            if (OCTANE_RUN_FAILED_STATUS.equals(runResult.getStatus())) {
                Element error = doc.createElement("error");
                testRun.appendChild(error);

                error.setAttribute("type", "Error");
                error.setAttribute("message",
                        "For more details , goto ALM run : " + runResult.getExternalReportUrl());
            }
        }

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        if (formatXml) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        DOMSource source = new DOMSource(doc);

        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Transforms (serializes) XML DOM document to string.
 *
 * @param doc/*w  ww. j a v  a  2s.co  m*/
 *            document to transform to string
 * @return XML string representation of document
 * @throws javax.xml.transform.TransformerException
 *             If an exception occurs while transforming XML DOM document to string
 */
public static String documentToString(Node doc) throws TransformerException {
    StringWriter sw = new StringWriter();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // NON-NLS
    transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NON-NLS
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NON-NLS
    transformer.setOutputProperty(OutputKeys.ENCODING, UTF8);

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

    return sw.toString();
    // NOTE: if return as single line
    // return sw.toString().replaceAll("\n|\r", ""); // NON-NLS
}

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

public static byte[] transformDomToByteArray(final Document documentDom) {

    try {//from   www  .  j av  a2s. c  o m

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final String xmlEncoding = documentDom.getXmlEncoding();
        if (StringUtils.isNotBlank(xmlEncoding)) {
            transformer.setOutputProperty(OutputKeys.ENCODING, xmlEncoding);
        }
        final DOMSource source = new DOMSource(documentDom);

        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final StreamResult streamResult = new StreamResult(byteArrayOutputStream);
        transformer.transform(source, streamResult);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return byteArray;
    } catch (final TransformerException e) {
        throw new DSSException(e);
    }
}