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:org.alloy.metal.xml.merge.ImportProcessor.java

public List<ResourceInputStream> extract(List<ResourceInputStream> sources) throws MergeException {
    try {/* w  ww .j av a 2s.co m*/
        DynamicResourceIterator resourceList = new DynamicResourceIterator();
        resourceList.addAll(sources);

        while (resourceList.hasNext()) {
            ResourceInputStream myStream = resourceList.nextResource();
            Document doc = builder.parse(myStream);
            NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET);
            int length = nodeList.getLength();
            for (int j = 0; j < length; j++) {
                Element element = (Element) nodeList.item(j);
                Resource resource = loader.getResource(element.getAttribute("resource"));
                ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(),
                        resource.getURL().toString());
                resourceList.addEmbeddedResource(ris);
                element.getParentNode().removeChild(element);
            }
            if (length > 0) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer xmlTransformer = tFactory.newTransformer();
                xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
                xmlTransformer.setOutputProperty(OutputKeys.ENCODING, _String.CHARACTER_ENCODING.toString());
                xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

                DOMSource source = new DOMSource(doc);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));
                StreamResult result = new StreamResult(writer);
                xmlTransformer.transform(source, result);

                byte[] itemArray = baos.toByteArray();

                resourceList.set(resourceList.getPosition() - 1, new ResourceInputStream(
                        new ByteArrayInputStream(itemArray), null, myStream.getNames()));
            } else {
                myStream.reset();
            }
        }

        return resourceList;
    } catch (Exception e) {
        throw new MergeException(e);
    }
}

From source file:com.alfaariss.oa.util.configuration.handler.dummy.DummyConfigurationHandler.java

/**
 * Save the configuration to the screen.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *///from w  w  w. ja  va2s .com
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(System.out));
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    }
}

From source file:org.lareferencia.backend.indexer.IntelligoIndexer.java

private Transformer buildTransformer() throws IndexerException {

    Transformer trf;//from   w w  w. java  2 s  .c o  m

    try {

        StreamSource stylesource = new StreamSource(stylesheet);
        trf = xformFactory.newTransformer(stylesource);

        trf = MedatadaDOMHelper.buildXSLTTransformer(stylesheet);
        trf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trf.setOutputProperty(OutputKeys.INDENT, "yes");
        trf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    } catch (TransformerConfigurationException e) {
        throw new IndexerException(e.getMessage(), e.getCause());
    }

    return trf;

}

From source file:org.syncope.core.scheduling.ReportJob.java

@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {

    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }//w w  w.ja v  a 2  s .c  o  m

    // 1. create execution
    ReportExec execution = new ReportExec();
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStartDate(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = transformerFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));

        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }

    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);

    ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext()
            .getBeanFactory();

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    StringWriter exceptionWriter = new StringWriter();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName());
        handler.startElement("", "", ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class reportletClass = null;
            try {
                reportletClass = Class.forName(reportletConf.getReportletClassName());
            } catch (ClassNotFoundException e) {
                LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e);

            }

            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass,
                        AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                autowired.setConf(reportletConf);

                // invoke reportlet
                try {
                    autowired.extract(handler);
                } catch (Exception e) {
                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable t = e instanceof ReportException ? e.getCause() : e;
                    exceptionWriter.write(t.getMessage() + "\n\n");
                    t.printStackTrace(new PrintWriter(exceptionWriter));
                    reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {

            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);

        exceptionWriter.write(e.getMessage() + "\n\n");
        e.printStackTrace(new PrintWriter(exceptionWriter));
        reportExecutionMessage.append(exceptionWriter.toString());

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            zos.close();
            baos.close();
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }

        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:me.cavar.pg2tei.TEIDoc.java

/**
 *
 * @param doc/*  w  w w . j  a  v  a2s  . c o  m*/
 * @return
 */
public String getTEIXMLString(Document doc) {
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans;
    StringWriter strw = new StringWriter();
    StreamResult result = new StreamResult(strw);
    try {
        trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        // create string from xml tree
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(TEIDoc.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
        Logger.getLogger(TEIDoc.class.getName()).log(Level.SEVERE, null, ex);
    }
    return strw.toString();
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Convert a Document into a String/*from   w  ww.j a v  a2s  .co  m*/
 *
 * @param document           the Document to be converted to String
 * @param omitXmlDeclaration set to true if you'd like to omit the XML declaration, false otherwise
 * @return the String converted from a Document
 *
 */
public static String convertDocumentToString(Document document, boolean omitXmlDeclaration) {
    try {
        StringWriter stringWriter = new StringWriter();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        if (omitXmlDeclaration) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        } else {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        }
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (TransformerException e) {
        logger.error("Transformer Exception when attempting to convert a document to a string. ");
    }
    return null;
}

From source file:net.sf.joost.emitter.StreamEmitter.java

/**
 * Creates an emitter using a given <code>OutputStream</code> and a set
 * of output properties. The value of the <code>OutputKeys.ENCODING</code>
 * property defines the encoding for to used. The value of the
 * <code>OutputKeys.METHOD</code> property determines the returned
 * emitter object.//from w  w  w  . j  a va 2 s  . com
 * @param out An <code>OutputStream</code> for receiving the output.
 * @param outputProperties The set of output properties to be used.
 * @return a proper stream emitter object
 * @throws UnsupportedEncodingException When <code>outputProperties</code>
 * specifies an unsupported output encoding
 */
public static StreamEmitter newEmitter(OutputStream out, Properties outputProperties)
        throws UnsupportedEncodingException {
    String encoding = null;
    if (outputProperties != null)
        encoding = outputProperties.getProperty(OutputKeys.ENCODING);
    if (encoding != null)
        encoding = encoding.toUpperCase();
    else
        encoding = DEFAULT_ENCODING;

    OutputStreamWriter writer;
    try {
        writer = new OutputStreamWriter(out, encoding);
    } catch (java.io.UnsupportedEncodingException e) {
        String msg = "Unsupported encoding " + encoding + ", using " + DEFAULT_ENCODING;
        if (log != null)
            log.warn(msg);
        else
            System.err.println("Warning: " + msg);
        writer = new OutputStreamWriter(out, DEFAULT_ENCODING);
    }

    return newEmitter(new BufferedWriter(writer), encoding, outputProperties);
}

From source file:uk.ac.diamond.shibbolethecpauthclient.Utils.java

/**
 * Helper method that turns the message into a formatted XML string.
 * /*from   www . j  a  v a2s  . c  om*/
 * @param doc
 *The XML document to turn into a formatted XML string
 * 
 * @return The XML string
 */
static String xmlToString(Element doc) {

    StringWriter sw = new StringWriter();
    try {
        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:net.sf.joost.trax.TransformerImpl.java

/**
 * Constructor/*from www  .j  av a 2s  .  c  o  m*/
 *
 * @param processor A <code>Processor</code> object.
 */
protected TransformerImpl(Processor processor) {
    this.processor = processor;

    // set tracing manager on processor object
    if (processor instanceof DebugProcessor) {
        DebugProcessor dbp = (DebugProcessor) processor;
        dbp.setTraceManager(traceManager);
        dbp.setTransformer(this);

        Emitter emitter = processor.getEmitter();
        if (emitter instanceof DebugEmitter) {
            ((DebugEmitter) emitter).setTraceManager(traceManager);
        }
    }
    supportedProperties.add(OutputKeys.ENCODING);
    supportedProperties.add(OutputKeys.MEDIA_TYPE);
    supportedProperties.add(OutputKeys.METHOD);
    supportedProperties.add(OutputKeys.OMIT_XML_DECLARATION);
    supportedProperties.add(OutputKeys.STANDALONE);
    supportedProperties.add(OutputKeys.VERSION);
    supportedProperties.add(TrAXConstants.OUTPUT_KEY_SUPPORT_DISABLE_OUTPUT_ESCAPING);

    ignoredProperties.add(OutputKeys.CDATA_SECTION_ELEMENTS);
    ignoredProperties.add(OutputKeys.DOCTYPE_PUBLIC);
    ignoredProperties.add(OutputKeys.DOCTYPE_SYSTEM);
    ignoredProperties.add(OutputKeys.INDENT);
}

From source file:com.action.ExportAction.java

public String exportXMLAction() {
    try {/* ww  w .ja va2s  . c  o  m*/
        //document
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Element reportsElement = document.createElement("project");//
        reportsElement.setAttribute("date", (new Date()).toString());
        document.appendChild(reportsElement);
        System.out.println("exportXMLAction:" + tableCode);
        String[] ids = tableCode.split(",");
        for (String id : ids) {
            System.out.println("id:" + id);
            List<JQ_zhibiao_entity> list = Export.getDuizhaoByJqTbCode(id);
            document = Export.exportXML(reportsElement, document, list, id);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        PrintWriter pw = new PrintWriter(new FileOutputStream(realPath + "test.xml"));
        StreamResult result = new StreamResult(pw);
        transformer.transform(source, result);
        pw.close();
    } catch (Exception e) {
        ActionContext.getContext().put("message", "??" + e);
        return ERROR;
    }
    return SUCCESS;
}