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:it.imtech.metadata.MetaUtility.java

/**
 * Metodo adibito all'esportazione dei metadati su oggetto Document a
 * partire dai valori dell'interfaccia/* w  ww  . j  a  v  a  2  s.c o m*/
 *
 * @param pid PID del libro durante upload
 * @param pagenum Numero pagina corrente di esportazione
 * @param objectDefaultValues Valori di default durante upload
 * @return Oggetto xml contenente i metadati inseriti nei campi
 * dell'interfaccia
 * @throws Exception
 */
public Document create_uwmetadata(String pid, int pagenum, HashMap<String, String> objectDefaultValues,
        String collTitle, String panelname) throws Exception {
    String xmlFile = "";

    if (objectDefaultValues != null) {
        this.objectDefaultValues = objectDefaultValues;
    }

    StreamResult result = new StreamResult(new StringWriter());

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // set the factory to be namespace aware
    factory.setNamespaceAware(true);

    // create the xml document builder object and get the DOMImplementation object
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation domImpl = builder.getDOMImplementation();
    Document xmlDoc = domImpl.createDocument("http://phaidra.univie.ac.at/XML/metadata/V1.0", "ns0:uwmetadata",
            null);

    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.STANDALONE, "");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        // get the root element
        Element rootElement = xmlDoc.getDocumentElement();

        //Add namespaces in XML Root
        for (Map.Entry<String, String> field : metadata_namespaces.entrySet()) {
            rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + field.getKey().toString(),
                    field.getValue().toString());
        }
        create_uwmetadata_recursive(xmlDoc, rootElement, BookImporter.getInstance().getMetadata(),
                this.objectDefaultValues, pagenum, collTitle, panelname);
    } catch (TransformerConfigurationException e) {
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }

    return xmlDoc;
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

public static void printDocument(Source doc, OutputStream out) throws IOException, TransformerException {
    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(doc, new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}

From source file:com.maxl.java.aips2sqlite.RealExpertInfo.java

private String prettyFormat(String input) {
    try {/*from ww  w  .  j ava2  s  . c  o m*/
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

void saveDocument(Document document, String path, String name) {
    try {//from  ww w  .j  a v  a2 s  . co m
        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        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:net.sourceforge.pmd.RuleSetWriter.java

public void write(RuleSet ruleSet) {
    try {/*from  w w  w. ja  va  2s.co  m*/
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
        ruleSetFileNames = new HashSet<>();

        Element ruleSetElement = createRuleSetElement(ruleSet);
        document.appendChild(ruleSetElement);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        try {
            transformerFactory.setAttribute("indent-number", 3);
        } catch (IllegalArgumentException iae) {
            // ignore it, specific to one parser
            LOG.log(Level.FINE, "Couldn't set indentation", iae);
        }
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        // This is as close to pretty printing as we'll get using standard
        // Java APIs.
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(document), new StreamResult(outputStream));
    } catch (DOMException e) {
        throw new RuntimeException(e);
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.sourceforge.pmd.util.designer.Designer.java

private void saveSettings() {
    try {/* w  ww  .  ja v a2s  .c  o  m*/
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        Element settingsElement = document.createElement("settings");
        document.appendChild(settingsElement);

        Element codeElement = document.createElement("code");
        settingsElement.appendChild(codeElement);
        codeElement.setAttribute("language-version", getLanguageVersion().getTerseName());
        codeElement.appendChild(document.createCDATASection(codeEditorPane.getText()));

        Element xpathElement = document.createElement("xpath");
        settingsElement.appendChild(xpathElement);
        xpathElement.setAttribute("version", xpathVersionButtonGroup.getSelection().getActionCommand());
        xpathElement.appendChild(document.createCDATASection(xpathQueryArea.getText()));

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        // This is as close to pretty printing as we'll get using standard
        // Java APIs.
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        Source source = new DOMSource(document);
        Result result = new StreamResult(
                Files.newBufferedWriter(new File(SETTINGS_FILE_NAME).toPath(), StandardCharsets.UTF_8));
        transformer.transform(source, result);
    } catch (ParserConfigurationException | IOException | TransformerException e) {
        e.printStackTrace();
    }
}

From source file:net.straylightlabs.tivolibre.DecoderApp.java

private static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
    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(new OutputStreamWriter(out, "UTF-8")));
}

From source file:nl.b3p.viewer.admin.stripes.GeoServiceActionBean.java

public Resolution generateSld() throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from   w  w w.j  a  v  a 2  s .  co  m
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document sldDoc = db.newDocument();

    Element sldEl = sldDoc.createElementNS(NS_SLD, "StyledLayerDescriptor");
    sldDoc.appendChild(sldEl);
    sldEl.setAttributeNS(NS_SLD, "version", "1.0.0");
    sldEl.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation",
            "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd");
    sldEl.setAttribute("xmlns:ogc", NS_OGC);
    sldEl.setAttribute("xmlns:gml", NS_GML);
    service.loadLayerTree();

    Queue<Layer> layerStack = new LinkedList();
    Layer l = service.getTopLayer();
    while (l != null) {
        layerStack.addAll(service.getLayerChildrenCache(l));

        if (l.getName() != null) {
            Element nlEl = sldDoc.createElementNS(NS_SLD, "NamedLayer");
            sldEl.appendChild(nlEl);
            String title = l.getTitleAlias() != null ? l.getTitleAlias() : l.getTitle();
            if (title != null) {
                nlEl.appendChild(sldDoc.createComment(" Layer '" + title + "' "));
            }
            Element nEl = sldDoc.createElementNS(NS_SLD, "Name");
            nEl.setTextContent(l.getName());
            nlEl.appendChild(nEl);

            if (l.getFeatureType() != null) {
                String protocol = "";
                if (l.getFeatureType().getFeatureSource() != null) {
                    protocol = " (protocol " + l.getFeatureType().getFeatureSource().getProtocol() + ")";
                }

                String ftComment = " This layer has a feature type" + protocol
                        + " you can use in a FeatureTypeConstraint element as follows:\n";
                ftComment += "            <LayerFeatureConstraints>\n";
                ftComment += "                <FeatureTypeConstraint>\n";
                ftComment += "                    <FeatureTypeName>" + l.getFeatureType().getTypeName()
                        + "</FeatureTypeName>\n";
                ftComment += "                    Add ogc:Filter or Extent element here. ";
                if (l.getFeatureType().getAttributes().isEmpty()) {
                    ftComment += " No feature type attributes are known.\n";
                } else {
                    ftComment += " You can use the following feature type attributes in ogc:PropertyName elements:\n";
                    for (AttributeDescriptor ad : l.getFeatureType().getAttributes()) {
                        ftComment += "                    <ogc:PropertyName>" + ad.getName()
                                + "</ogc:PropertyName>";
                        if (ad.getAlias() != null) {
                            ftComment += " (" + ad.getAlias() + ")";
                        }
                        if (ad.getType() != null) {
                            ftComment += " (type: " + ad.getType() + ")";
                        }
                        ftComment += "\n";
                    }
                }
                ftComment += "                </FeatureTypeConstraint>\n";
                ftComment += "            </LayerFeatureConstraints>\n";
                ftComment += "        ";
                nlEl.appendChild(sldDoc.createComment(ftComment));
            }

            nlEl.appendChild(sldDoc.createComment(" Add a UserStyle or NamedStyle element here "));
            String styleComment = " (no server-side named styles are known other than 'default') ";
            ClobElement styleDetail = l.getDetails().get(Layer.DETAIL_WMS_STYLES);
            if (styleDetail != null) {
                try {
                    JSONArray styles = new JSONArray(styleDetail.getValue());

                    if (styles.length() > 0) {
                        styleComment = " The following NamedStyles are available according to the capabilities: \n";

                        for (int i = 0; i < styles.length(); i++) {
                            JSONObject jStyle = styles.getJSONObject(i);

                            styleComment += "            <NamedStyle><Name>" + jStyle.getString("name")
                                    + "</Name></NamedStyle>";
                            if (jStyle.has("title")) {
                                styleComment += " (" + jStyle.getString("title") + ")";
                            }
                            styleComment += "\n";
                        }
                    }

                } catch (JSONException e) {
                }
                styleComment += "        ";
            }
            nlEl.appendChild(sldDoc.createComment(styleComment));
        }

        l = layerStack.poll();
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    DOMSource source = new DOMSource(sldDoc);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(bos);
    t.transform(source, result);
    generatedSld = new String(bos.toByteArray(), "UTF-8");

    // indent doesn't add newline after XML declaration
    generatedSld = generatedSld.replaceFirst("\"\\?><StyledLayerDescriptor", "\"?>\n<StyledLayerDescriptor");
    return new ForwardResolution(JSP_EDIT_SLD);
}

From source file:nl.ellipsis.webdav.server.util.XMLHelper.java

public static String format(Document document) {
    String retval = null;//w  ww . ja  v a  2  s.co m
    if (document != null) {
        TransformerFactory transfac = TransformerFactory.newInstance();
        StringWriter sw = null;
        try {
            Transformer transformer = transfac.newTransformer();

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

            //create string from xml tree
            sw = new StringWriter();
            StreamResult result = new StreamResult(sw);

            DOMSource source = new DOMSource(document);

            transformer.transform(source, result);

            retval = sw.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        } finally {
            try {
                sw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return retval;
}

From source file:org.alfresco.util.XMLUtil.java

/** utility function for serializing a node */
public static void print(final Node n, final Writer output, final boolean indent) {
    try {// w ww.  jav  a2  s  .c om
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("writing out a document for "
                    + (n instanceof Document ? ((Document) n).getDocumentElement() : n).getNodeName() + " to "
                    + (output instanceof StringWriter ? "string" : output));
        }
        t.transform(new DOMSource(n), new StreamResult(output));
    } catch (TransformerException te) {
        te.printStackTrace();
        assert false : te.getMessage();
    }
}