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.opendatakit.services.utilities.EncryptionUtils.java

private static boolean writeSubmissionManifest(EncryptedFormInformation formInfo, File submissionXml,
        File submissionXmlEnc, List<MimeFile> mediaFiles) {

    FileOutputStream out = null;/*from   ww w .  j  ava2 s  .c  o m*/
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document d = db.newDocument();
        d.setXmlStandalone(true);
        Element e = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, DATA);
        e.setPrefix(null);
        e.setAttribute(ID, formInfo.tableId);
        e.setAttribute(ENCRYPTED, "yes");
        d.appendChild(e);

        Element c;
        c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY);
        Text txtNode;
        txtNode = d.createTextNode(formInfo.base64RsaEncryptedSymmetricKey);
        c.appendChild(txtNode);
        e.appendChild(c);

        c = d.createElementNS(XML_OPENROSA_NAMESPACE, META);
        c.setPrefix("orx");
        {
            Element instanceTag = d.createElementNS(XML_OPENROSA_NAMESPACE, INSTANCE_ID);
            txtNode = d.createTextNode(formInfo.instanceId);
            instanceTag.appendChild(txtNode);
            c.appendChild(instanceTag);
        }
        e.appendChild(c);

        for (MimeFile file : mediaFiles) {
            c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA);
            Element fileTag = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, FILE);
            txtNode = d.createTextNode(file.file.getName());
            fileTag.appendChild(txtNode);
            c.appendChild(fileTag);
            e.appendChild(c);
        }

        c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE);
        txtNode = d.createTextNode(submissionXmlEnc.getName());
        c.appendChild(txtNode);
        e.appendChild(c);

        c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE);
        txtNode = d.createTextNode(formInfo.getBase64EncryptedElementSignature());
        c.appendChild(txtNode);
        e.appendChild(c);

        out = new FileOutputStream(submissionXml);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        Properties outFormat = new Properties();
        outFormat.setProperty(OutputKeys.INDENT, "no");
        outFormat.setProperty(OutputKeys.METHOD, "xml");
        outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        outFormat.setProperty(OutputKeys.VERSION, "1.0");
        outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperties(outFormat);

        DOMSource domSource = new DOMSource(d.getDocumentElement());
        StreamResult result = new StreamResult(out);
        transformer.transform(domSource, result);

        out.flush();
        out.close();
    } catch (FileNotFoundException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (UnsupportedEncodingException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (IOException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (TransformerConfigurationException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (TransformerException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (ParserConfigurationException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return true;
}

From source file:org.openestate.io.core.XmlUtils.java

/**
 * Write a {@link Document} to an {@link OutputStream}.
 *
 * @param doc/*from  www. jav a2  s  .co m*/
 * the document to write
 *
 * @param output
 * the output, where the document is written to
 *
 * @param prettyPrint
 * if pretty printing is enabled for the generated XML code
 *
 * @throws TransformerException
 * if XML transformation failed
 */
public static void write(Document doc, OutputStream output, boolean prettyPrint) throws TransformerException {
    XmlUtils.clean(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, (prettyPrint) ? "yes" : "no");
    if (prettyPrint) {
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    }
    transformer.transform(new DOMSource(doc), new StreamResult(output));
}

From source file:org.openestate.io.core.XmlUtils.java

/**
 * Write a {@link Document} to a {@link Writer}.
 *
 * @param doc/*  w  w  w.  j ava2s .c o m*/
 * the document to write
 *
 * @param output
 * the output, where the document is written to
 *
 * @param prettyPrint
 * if pretty printing is enabled for the generated XML code
 *
 * @throws TransformerException
 * if XML transformation failed
 */
public static void write(Document doc, Writer output, boolean prettyPrint) throws TransformerException {
    XmlUtils.clean(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, (prettyPrint) ? "yes" : "no");
    if (prettyPrint) {
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    }
    transformer.transform(new DOMSource(doc), new StreamResult(output));
}

From source file:org.openhealthtools.openatna.jaxb21.JaxbIOFactory.java

private StreamResult transform(Document doc, OutputStream out) throws IOException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;/*from w ww. j  a  va 2  s .c  om*/
    try {
        t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    } catch (TransformerConfigurationException tce) {
        assert (false);
    }
    DOMSource doms = new DOMSource(doc);
    StreamResult sr = new StreamResult(out);
    try {
        t.transform(doms, sr);
    } catch (TransformerException te) {
        throw new IOException(te.getMessage());
    }
    return sr;
}

From source file:org.openmrs.module.drawing.obs.handler.DrawingHandler.java

public void saveAnnotation(Obs obs, ImageAnnotation annotation, boolean delete) {
    try {/*w  ww .  j  a  v  a  2 s .c o m*/
        log.info("drawing: Saving annotation for obs " + obs.getObsId());

        File metadataFile = getComplexMetadataFile(obs);
        log.info("drawing: Using file " + metadataFile.getCanonicalPath());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document xmldoc;
        Element annotationsParent;
        int newId = 0;

        if (metadataFile.exists()) {
            xmldoc = builder.parse(metadataFile);
            annotationsParent = (Element) xmldoc.getElementsByTagName("Annotations").item(0);
            NodeList annotationNodeList = xmldoc.getElementsByTagName("Annotation");

            for (int i = 0; i < annotationNodeList.getLength(); i++) {
                NamedNodeMap attributes = annotationNodeList.item(i).getAttributes();
                String idString = attributes.getNamedItem("id").getNodeValue();
                int existingId = Integer.parseInt(idString);
                if (existingId == annotation.getId() && !(annotation.getStatus() == Status.UNCHANGED)) {
                    annotationsParent.removeChild(annotationNodeList.item(i));
                    break;
                }
                if (existingId >= newId)
                    newId = existingId + 1;
            }
        } else {
            metadataFile.createNewFile();
            DOMImplementation domImpl = builder.getDOMImplementation();
            xmldoc = domImpl.createDocument(null, "ImageMetadata", null);
            Element root = xmldoc.getDocumentElement();
            annotationsParent = xmldoc.createElementNS(null, "Annotations");
            root.appendChild(annotationsParent);
        }

        if (!delete && annotation.getStatus() != Status.UNCHANGED) {
            if (annotation.getId() >= 0)
                newId = annotation.getId();

            Element e = xmldoc.createElementNS(null, "Annotation");
            Node n = xmldoc.createTextNode(annotation.getText());
            e.setAttributeNS(null, "id", newId + "");
            e.setAttributeNS(null, "xcoordinate", annotation.getLocation().getX() + "");
            e.setAttributeNS(null, "ycoordinate", annotation.getLocation().getY() + "");
            e.setAttributeNS(null, "userid", annotation.getUser().getUserId() + "");
            e.setAttributeNS(null, "date", annotation.getDate().getTime() + "");
            e.appendChild(n);
            annotationsParent.appendChild(e);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(xmldoc), new StreamResult(metadataFile));

        log.info("drawing: Saving annotation complete");

    } catch (Exception e) {
        log.error("drawing: Error saving image metadata: " + e.getClass() + " " + e.getMessage());
    }
}

From source file:org.opennms.reporting.availability.render.HTMLReportRenderer.java

/**
 * <p>render</p>/*from w  w w  .j a va2s  .com*/
 *
 * @param in a {@link java.io.Reader} object.
 * @param out a {@link java.io.OutputStream} object.
 * @param xslt a {@link java.io.Reader} object.
 * @throws org.opennms.reporting.availability.render.ReportRenderException if any.
 */
public void render(final Reader in, final OutputStream out, final Reader xslt) throws ReportRenderException {
    try {
        TransformerFactory tfact = TransformerFactory.newInstance();
        Transformer transformer = tfact.newTransformer(new StreamSource(xslt));
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new StreamSource(in), new StreamResult(out));
    } catch (final Exception e) {
        if (e instanceof ReportRenderException)
            throw (ReportRenderException) e;
        throw new ReportRenderException(e);
    }
}

From source file:org.opennms.reporting.availability.render.PDFReportRenderer.java

/**
 * <p>render</p>//from   w ww. ja  va  2s .co m
 *
 * @param in a {@link java.io.Reader} object.
 * @param out a {@link java.io.OutputStream} object.
 * @param xslt a {@link java.io.Reader} object.
 * @throws org.opennms.reporting.availability.render.ReportRenderException if any.
 */
public void render(final Reader in, final OutputStream out, final Reader xslt) throws ReportRenderException {
    try {
        final FopFactory fopFactory = FopFactory.newInstance();
        fopFactory.setStrictValidation(false);
        final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

        final TransformerFactory tfact = TransformerFactory.newInstance();
        final Transformer transformer = tfact.newTransformer(new StreamSource(xslt));
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        final StreamSource streamSource = new StreamSource(in);
        transformer.transform(streamSource, new SAXResult(fop.getDefaultHandler()));
    } catch (final Exception e) {
        throw new ReportRenderException(e);
    }
}

From source file:org.ow2.proactive.scheduler.common.job.factories.Job2XMLTransformer.java

/**
 * Creates the xml representation of the job in argument
 *
 * @throws TransformerException/*from   w  ww  . ja  v a 2  s  .  com*/
 * @throws ParserConfigurationException
 */
public InputStream jobToxml(TaskFlowJob job) throws TransformerException, ParserConfigurationException {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    doc.setXmlStandalone(true);

    // create the xml tree corresponding to this job
    Element rootJob = createRootJobElement(doc, job);
    doc.appendChild(rootJob);

    // set up a transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    // If the encoding property is set on the client JVM, use it (it has to match the server-side encoding),
    // otherwise use UTF-8
    if (PASchedulerProperties.FILE_ENCODING.isSet()) {
        trans.setOutputProperty(OutputKeys.ENCODING, PASchedulerProperties.FILE_ENCODING.getValueAsString());
    } else {
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    }
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    // write the xml
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(baos);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, result);
    byte[] array = baos.toByteArray();
    return new ByteArrayInputStream(array);
}

From source file:org.pentaho.reporting.platform.plugin.ParameterXmlContentHandlerTest.java

private String toString(final Document doc) {
    try {//from   w  w  w .j  a  va2s  . c  om
        final StringWriter stringWriter = new StringWriter();
        final TransformerFactory factory = TransformerFactory.newInstance();
        final Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (final Exception ex) {
        // no op
        return "fail";
    }
}

From source file:org.programmatori.domotica.own.plugin.map.Map.java

private void createStatusFile(String fileName) {
    StreamResult streamResult = new StreamResult(new File(fileName));

    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler hd = null;
    try {//  w w  w.  j a  v  a2s.  com
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
    Transformer serializer = hd.getTransformer();

    serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    //serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "users.dtd");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    //serializer.setOutputProperty( XalanOutputKeys.OUTPUT_PROP_INDENT_AMOUNT, "2" );

    hd.setResult(streamResult);
    try {
        hd.startDocument();

        AttributesImpl attrs = new AttributesImpl();
        hd.startElement("", "", "home", attrs);

        hd.startElement("", "", "version", attrs);
        hd.characters("2.0".toCharArray(), 0, 3);
        hd.endElement("", "", "version");

        attrs.clear();
        attrs.addAttribute("", "", "unit", "CDATA", "min");
        hd.startElement("", "", "statusSave", attrs);
        hd.characters("10".toCharArray(), 0, 2);
        hd.endElement("", "", "statusSave");

        // ----------------------------------------- Area
        for (Iterator<Integer> iterAree = localBus.keySet().iterator(); iterAree.hasNext();) {
            Integer area = (Integer) iterAree.next();

            attrs.clear();
            attrs.addAttribute("", "", "id", "CDATA", area.toString());
            attrs.addAttribute("", "", "name", "CDATA", Config.getInstance().getRoomName(area));
            hd.startElement("", "", "area", attrs);

            // ----------------------------------------- Component
            Set<SCSComponent> rooms = localBus.get(area);
            for (Iterator<SCSComponent> iterRoom = rooms.iterator(); iterRoom.hasNext();) {
                SCSComponent c = (SCSComponent) iterRoom.next();
                log.info("PL: " + c.getStatus().getWhere().getPL() + "("
                        + Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()) + ")");

                attrs.clear();
                attrs.addAttribute("", "", "type", "CDATA",
                        Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()));
                attrs.addAttribute("", "", "pl", "CDATA", "" + c.getStatus().getWhere().getPL());
                hd.startElement("", "", "component", attrs);
                hd.characters("0".toCharArray(), 0, 1);
                hd.endElement("", "", "component");
            }
            // ----------------------------------------- Component

            hd.endElement("", "", "area");
        }
        // ----------------------------------------- End Area

        // ----------------------------------------- Scheduler
        attrs.clear();
        hd.startElement("", "", "scheduler", attrs);

        attrs.clear();
        attrs.addAttribute("", "", "time", "CDATA", "-1");
        hd.startElement("", "", "command2", attrs);
        hd.characters("*1*1*11##".toCharArray(), 0, 9);
        hd.endElement("", "", "command2");

        hd.endElement("", "", "scheduler");
        // ----------------------------------------- End Scheduler

        hd.endElement("", "", "home");
        hd.endDocument();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    //      for (Iterator<Integer> iterAree = localBus.keySet().iterator(); iterAree.hasNext();) {
    //         Integer area = (Integer) iterAree.next();
    //
    //         log.info("Room: " + area + " - " + Config.getInstance().getRoomName(area));
    //         Set<SCSComponent> rooms = localBus.get(area);
    //         for (Iterator<SCSComponent> iterRoom = rooms.iterator(); iterRoom.hasNext();) {
    //            SCSComponent c = (SCSComponent) iterRoom.next();
    //            log.info("PL: " + c.getStatus().getWhere().getPL() + "(" + Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()) + ")");
    //         }
    //      }
}