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.uzk.hki.da.metadata.XsltGenerator.java

/**
 * Instantiates a new xslt generator.//from w  w w  .  ja va2s . c  om
 *
 * @param xsltPath the xslt path to the edm mapping file
 * @param inputStream the input stream of the source metadata file
 * @throws FileNotFoundException 
 * @throws TransformerConfigurationException 
 */
public XsltGenerator(String xsltPath, InputStream inputStream)
        throws FileNotFoundException, TransformerConfigurationException {
    if (!new File(xsltPath).exists())
        throw new FileNotFoundException();

    try {
        String theString = IOUtils.toString(inputStream, "UTF-8");
        this.inputStream = new ByteArrayInputStream(theString.getBytes());

        xsltSource = new StreamSource(new FileInputStream(xsltPath));

        TransformerFactory transFact = TransformerFactory.newInstance(TRANSFORMER_FACTORY_CLASS, null);
        transFact.setErrorListener(new CutomErrorListener());

        transformer = null;
        transformer = transFact.newTransformer(xsltSource);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setErrorListener(new CutomErrorListener());

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ar.com.zauber.commons.web.transformation.processors.impl.XalanXSLTScraper.java

/**
 *
 * Propiedades que recibe un tranformer.
 * {@link javax.xml.transform.Transformer#setOutputProperties(Properties)}
 * utiliza estas opciones://from ww  w .j a va2 s . c  o  m
 *      javax.xml.transform.OutputKeys
 * @param node
 * @param model
 * @param writer
 * @param oformat siguiendo las specs linkeadas mas arriba
 *
 *
 * @throws TransformerFactoryConfigurationError
 */
public void scrap(final Node node, final Map<String, Object> model, final Writer writer, Properties oformat)
        throws TransformerFactoryConfigurationError {
    Validate.notNull(node);
    Validate.notNull(model);
    Validate.notNull(writer);
    try {
        final TransformerFactory factory = TransformerFactory.newInstance();
        final Transformer transformer = factory.newTransformer(xsltSource);
        Validate.notNull(transformer);
        for (final Entry<String, Object> entry : model.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
        Properties options;
        if (oformat != null) {
            options = new Properties(oformat);
        } else {
            options = new Properties();
        }
        if (encoding != null) {
            options.setProperty(OutputKeys.ENCODING, encoding);
        }
        transformer.setOutputProperties(options);
        transformer.transform(new DOMSource(node), new StreamResult(writer));
    } catch (TransformerException e) {
        throw new UnhandledException(e);
    }
}

From source file:com.idiominc.ws.opentopic.fo.i18n.PreprocessorTask.java

@Override
public void execute() throws BuildException {
    checkParameters();/* ww w. ja  va  2  s  .  c  om*/

    log("Processing " + input + " to " + output, Project.MSG_INFO);
    OutputStream out = null;
    try {
        final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder();
        documentBuilder.setEntityResolver(xmlcatalog);

        final Document doc = documentBuilder.parse(input);
        final Document conf = documentBuilder.parse(config);
        final MultilanguagePreprocessor preprocessor = new MultilanguagePreprocessor(new Configuration(conf));
        final Document document = preprocessor.process(doc);

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setURIResolver(xmlcatalog);
        final Transformer transformer;
        if (style != null) {
            log("Loading stylesheet " + style, Project.MSG_INFO);
            transformer = transformerFactory.newTransformer(new StreamSource(style));
        } else {
            transformer = transformerFactory.newTransformer();
        }
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        if (doc.getDoctype() != null) {
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doc.getDoctype().getPublicId());
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
        }

        out = new FileOutputStream(output);
        final StreamResult streamResult = new StreamResult(out);
        transformer.transform(new DOMSource(document), streamResult);
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Exception e) {
        throw new BuildException(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:de.tudarmstadt.ukp.shibhttpclient.Utils.java

public static String xmlToString(Element doc) {
    StringWriter sw = new StringWriter();
    try {//from  www .j a v  a 2s  .c  o m
        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.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        LOG.error("Unable to print message contents: ", e);
        return "<ERROR: " + e.getMessage() + ">";
    }
}

From source file:hu.bme.mit.sette.common.util.XmlUtils.java

/**
 * Transforms the specified XML document to the specified result.
 *
 * @param document//from   www  .  ja  va  2s . c o  m
 *            The XML document.
 * @param result
 *            The result.
 * @throws TransformerException
 *             If an unrecoverable error occurs during the course of the
 *             transformation.
 */
private static void transformXml(final Document document, final Result result) throws TransformerException {
    Validate.notNull(document, "The document must not be null");
    Validate.notNull(result, "The result must not be null");

    // write XML to stream
    Transformer transformer = TransformerFactory.newInstance().newTransformer();

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

    transformer.transform(new DOMSource(document), result);
}

From source file:com.seajas.search.attender.service.template.TemplateService.java

/**
 * Create a confirmation template result.
 * /*from  ww  w  .j  a va 2s  .  c  o m*/
 * @param language
 * @param queryString
 * @param subscriberUUID
 * @param profileUUID
 */
public TemplateResult createConfirmation(final String language, final String queryString,
        final String subscriberUUID, final String profileUUID) throws Exception {
    Template template = templateDAO.findTemplate(TemplateType.Confirmation, language);

    if (template == null) {
        logger.warn("Could not retrieve confirmation template for language " + language
                + " - falling back to the default language " + attenderService.getDefaultApplicationLanguage());

        template = templateDAO.findTemplate(TemplateType.Confirmation,
                attenderService.getDefaultApplicationLanguage());

        if (template == null) {
            logger.error("Could not retrieve fall-back confirmation template for language "
                    + attenderService.getDefaultApplicationLanguage() + " - not generating a template result");

            return null;
        }
    }

    try {
        // Plain text

        Transformer textTransformer = getTransformer(template, true);
        StringWriter textWriter = new StringWriter();

        textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        textTransformer.setParameter("subscriberUUID", subscriberUUID);
        textTransformer.setParameter("profileUUID", profileUUID);
        textTransformer.setParameter("queryString", queryString);
        textTransformer.transform(new DOMSource(), new StreamResult(textWriter));

        // HTML

        Transformer htmlTransformer = getTransformer(template, false);
        StringWriter htmlWriter = new StringWriter();

        htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        htmlTransformer.setParameter("subscriberUUID", subscriberUUID);
        htmlTransformer.setParameter("profileUUID", profileUUID);
        htmlTransformer.setParameter("queryString", queryString);
        htmlTransformer.transform(new DOMSource(), new StreamResult(htmlWriter));

        return new TemplateResult(textWriter.toString(), htmlWriter.toString());
    } catch (ScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new Exception(e);
    }
}

From source file:com.sun.portal.portletcontainer.admin.PortletRegistryHelper.java

public static synchronized void writeFile(Document document, File file) throws PortletRegistryException {
    FileOutputStream output = null;
    try {//from  w w w.ja  va  2  s  . c  om
        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, CharEncoding.UTF_8);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");

        DOMSource source = new DOMSource(document);
        // StreamResult result = new StreamResult(System.out);
        output = new FileOutputStream(file);
        StreamResult result = new StreamResult(output);
        transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
        throw new PortletRegistryException(tce);
    } catch (TransformerException te) {
        throw new PortletRegistryException(te);
    } catch (Exception e) {
        throw new PortletRegistryException(e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                SilverTrace.warn("portlet", PortletRegistryHelper.class.getSimpleName() + ".writeFile()",
                        "root.EX_NO_MESSAGE", ex);
            }
        }
    }
}

From source file:com.swordlord.gozer.renderer.fop.FopFactoryHelper.java

public void transform(String strSource, Result result)
        throws TransformerConfigurationException, TransformerException {
    StringReader sr = new StringReader(strSource);
    // Setup input stream
    Source src = new StreamSource(sr);

    try {/*from w ww .  ja  v  a2 s .c o  m*/
        // Setup JAXP using identity transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setErrorListener(new FopTransformerErrorListener());

        String strEncoding = getCharset();
        transformer.setOutputProperty(OutputKeys.ENCODING, strEncoding);

        //System.setProperty("java.awt.headless", "true");
        //LOG.info("Headless mode before FOPing: " + GraphicsEnvironment.isHeadless());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, result);
    } catch (TransformerConfigurationException e) {
        LOG.error(
                MessageFormat.format("FOP transformation finalisation crashed: {0}", e.getLocalizedMessage()));
        throw (e);
    } catch (TransformerException e) {
        LOG.error(
                MessageFormat.format("FOP transformation finalisation crashed: {0}", e.getLocalizedMessage()));
        throw (e);
    }
}

From source file:edu.harvard.i2b2.fhir.Utils.java

public static String getStringFromDocument(Document doc) {
    try {//ww w  .ja  v  a 2  s .com
        doc.normalize();
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        //
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        int indent = 2;
        if (indent > 0) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                    Integer.toString(indent));
        }
        //

        transformer.transform(domSource, result);
        return writer.toString();
    } catch (TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.openmrs.module.casereport.rest.v1_0.controller.CaseReportController.java

@RequestMapping(value = "/" + CaseReportConstants.MODULE_ID + "/{uuid}/document", method = RequestMethod.GET)
@ResponseBody/*from ww w.j  av a2  s. c om*/
public Object getSubmittedCDAContents(@PathVariable("uuid") String uuid) {

    CaseReport cr = service.getCaseReportByUuid(uuid);
    if (cr == null) {
        throw new ObjectNotFoundException();
    }

    SimpleObject so = new SimpleObject();
    String pnrDoc = DocumentUtil.getSubmittedDocumentContents(cr);
    Exception e = null;
    if (StringUtils.isNotBlank(pnrDoc)) {
        try {
            Object o = webServiceTemplate.getUnmarshaller().unmarshal(new StringSource(pnrDoc));
            byte[] bytes = ((JAXBElement<ProvideAndRegisterDocumentSetRequestType>) o).getValue().getDocument()
                    .get(0).getValue();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder db = factory.newDocumentBuilder();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            Document cdaDoc = db.parse(new ByteArrayInputStream(bytes));
            StringResult result = new StringResult();
            transformer.transform(new DOMSource(cdaDoc), result);
            so.add("contents", result.toString());

            return so;
        } catch (Exception ex) {
            e = ex;
        }
    }

    throw new APIException("casereport.error.submittedCDAdoc.fail", e);
}