Example usage for org.w3c.dom Document getXmlEncoding

List of usage examples for org.w3c.dom Document getXmlEncoding

Introduction

In this page you can find the example usage for org.w3c.dom Document getXmlEncoding.

Prototype

public String getXmlEncoding();

Source Link

Document

An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, the encoding of this document.

Usage

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Convert a DOM node to a stringified XML representation.
 *//* www . j av  a  2  s. c  o  m*/
static public String domToString(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value = null;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE
            || nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE);
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // create a proper XML encoding header based on the input document;
        // default to UTF-8 if the parent document's encoding is not accessible
        String usedEncoding = "UTF-8";
        Document parent = node.getOwnerDocument();
        if (parent != null) {
            String parentEncoding = parent.getXmlEncoding();
            if (parentEncoding != null) {
                usedEncoding = parentEncoding;
            }
        }

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding(usedEncoding);

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}

From source file:org.apache.ode.utils.DOMUtils.java

public static void serialize(Element elmt, OutputStream ostr) {
    String usedEncoding = "UTF-8";
    Document parent = elmt.getOwnerDocument();
    if (parent != null) {
        String parentEncoding = parent.getXmlEncoding();
        if (parentEncoding != null) {
            usedEncoding = parentEncoding;
        }//w w  w.  j  a  va2s  . c o  m
    }

    DOMOutputImpl out = new DOMOutputImpl();
    out.setEncoding(usedEncoding);

    DOMSerializerImpl ser = new DOMSerializerImpl();
    out.setByteStream(ostr);
    ser.write(elmt, out);
}

From source file:org.artificer.integration.artifactbuilder.XmlArtifactBuilder.java

@Override
public ArtifactBuilder buildArtifacts(BaseArtifactType primaryArtifact, ArtifactContent artifactContent)
        throws Exception {
    super.buildArtifacts(primaryArtifact, artifactContent);

    try {//w w  w  . j  av  a  2  s. c om
        Document document = DOCUMENT_BUILDER.parse(getContentStream());
        // This *must* be setup prior to calling #configureNamespaceMappings.  Most subclasses will need it.
        rootElement = document.getDocumentElement();

        if (primaryArtifact instanceof XmlDocument) {
            String encoding = document.getXmlEncoding();
            if (StringUtils.isBlank(encoding)) {
                encoding = "UTF-8";
            }
            ((XmlDocument) primaryArtifact).setContentEncoding(encoding);
        }

        xpath = XPATH_FACTORY.newXPath();
        StaticNamespaceContext nsCtx = new StaticNamespaceContext();
        configureNamespaceMappings(nsCtx);
        xpath.setNamespaceContext(nsCtx);

        // Create all derived artifacts
        derive();

        // Set the relatedDocument relationship for all derived artifacts
        for (BaseArtifactType derivedArtifact : getDerivedArtifacts()) {
            if (derivedArtifact instanceof DerivedArtifactType) {
                DerivedArtifactType dat = (DerivedArtifactType) derivedArtifact;
                if (dat.getRelatedDocument() == null) {
                    DocumentArtifactTarget related = new DocumentArtifactTarget();
                    related.setValue(primaryArtifact.getUuid());
                    related.setArtifactType(DocumentArtifactEnum.fromValue(primaryArtifact.getArtifactType()));
                    dat.setRelatedDocument(related);
                }
            } else {
                Relationship genericRelationship = ArtificerModelUtils.getGenericRelationship(derivedArtifact,
                        "relatedDocument");
                if (genericRelationship == null) {
                    ArtificerModelUtils.addGenericRelationship(derivedArtifact, "relatedDocument",
                            primaryArtifact.getUuid());
                }
            }
        }

        return this;
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.exoplatform.content.service.RSSContentPlugin.java

@SuppressWarnings("unchecked")
public PageList loadContentMeta(ContentNode node) throws Exception {
    URL uri = new URL(node.getUrl());
    // TODO: tuan.pham CS-2531 get encode from rss file
    GetMethod get = null;//  w ww. j  a  va  2 s.  co  m
    HttpClientImpl httpClientService = new HttpClientImpl(uri);
    get = httpClientService.getMethod(uri.getFile());
    get.setFollowRedirects(true);
    int statusCode = httpClientService.getHttpClient().executeMethod(get);
    if (statusCode != HttpStatus.SC_OK) {
        throw new Exception("Server response code " + statusCode);
    }
    InputStream input = get.getResponseBodyAsStream();
    DocumentBuilder docbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = docbuilder.parse(input);
    String encode = doc.getXmlEncoding();
    if (encode == null || encode.trim().length() == 0)
        encode = "utf-8";
    RSSDocument<DefaultRSSChannel, RSSItem> document = service_.createDocument(uri, encode,
            DefaultRSSChannel.class, RSSItem.class);
    List<RSSItem> list = document.getItems();
    return new ContentPageList(list);
}

From source file:org.fireflow.pdl.fpdl.io.FPDLDeserializer.java

public WorkflowProcess deserialize(InputStream in)
        throws IOException, DeserializerException, InvalidModelException {
    try {/*  w  w w. j a  v a 2s.c o  m*/
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

        Document document = docBuilder.parse(in);

        String encoding = document.getXmlEncoding();
        log.info("Xml:" + encoding);

        final org.w3c.dom.Node pi = document
                .createProcessingInstruction(StreamResult.PI_DISABLE_OUTPUT_ESCAPING, "");
        document.appendChild(pi);

        WorkflowProcess wp = deserialize(document);// ?
        return wp;
    } catch (ParserConfigurationException e) {
        throw new DeserializerException("Error parsing document.", e);
    } catch (SAXException e) {
        throw new DeserializerException("Error parsing document.", e);
    } finally {
    }
    // return parse(new InputStreamReader(in));
}

From source file:org.openengsb.openengsbplugin.tools.Tools.java

public static String serializeXML(Document doc) throws IOException {
    StringWriter sw = null;/*from w w w  . j ava 2 s. c  o  m*/
    try {
        sw = new StringWriter();
        XMLSerializer xmlSerializer = new XMLSerializer();
        OutputFormat of = new OutputFormat(doc, doc.getXmlEncoding(), false);
        of.setStandalone(doc.getXmlStandalone());
        xmlSerializer.setOutputFormat(of);
        xmlSerializer.setOutputCharStream(sw);
        xmlSerializer.serialize(doc);
        return sw.toString();
    } finally {
        IOUtils.closeQuietly(sw);
    }
}

From source file:org.overlord.sramp.common.artifactbuilder.XmlArtifactBuilder.java

@Override
public ArtifactBuilder buildArtifacts(BaseArtifactType primaryArtifact, ArtifactContent artifactContent)
        throws IOException {
    super.buildArtifacts(primaryArtifact, artifactContent);

    try {/*from  w  ww  .j av a2 s .  c om*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); //$NON-NLS-1$
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); //$NON-NLS-1$

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(getContentStream());
        // This *must* be setup prior to calling #configureNamespaceMappings.  Most subclasses will need it.
        rootElement = document.getDocumentElement();

        if (primaryArtifact instanceof XmlDocument) {
            String encoding = document.getXmlEncoding();
            if (StringUtils.isBlank(encoding)) {
                encoding = "UTF-8";
            }
            ((XmlDocument) primaryArtifact).setContentEncoding(encoding);
        }

        XPathFactory xPathfactory = XPathFactory.newInstance();
        xpath = xPathfactory.newXPath();
        StaticNamespaceContext nsCtx = new StaticNamespaceContext();
        configureNamespaceMappings(nsCtx);
        xpath.setNamespaceContext(nsCtx);

        // Create all derived artifacts
        derive();

        // Set the relatedDocument relationship for all derived artifacts
        for (BaseArtifactType derivedArtifact : getDerivedArtifacts()) {
            if (derivedArtifact instanceof DerivedArtifactType) {
                DerivedArtifactType dat = (DerivedArtifactType) derivedArtifact;
                if (dat.getRelatedDocument() == null) {
                    DocumentArtifactTarget related = new DocumentArtifactTarget();
                    related.setValue(primaryArtifact.getUuid());
                    related.setArtifactType(DocumentArtifactEnum.fromValue(primaryArtifact.getArtifactType()));
                    dat.setRelatedDocument(related);
                }
            } else {
                Relationship genericRelationship = SrampModelUtils.getGenericRelationship(derivedArtifact,
                        "relatedDocument"); //$NON-NLS-1$
                if (genericRelationship == null) {
                    SrampModelUtils.addGenericRelationship(derivedArtifact, "relatedDocument", //$NON-NLS-1$
                            primaryArtifact.getUuid());
                }
            }
        }

        return this;
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.pentaho.di.job.entries.dtdvalidator.DTDValidator.java

public boolean validate() {

    boolean retval = false;

    FileObject xmlfile = null;/*  w w w.j  a v a 2 s . c o  m*/
    FileObject DTDfile = null;

    ByteArrayInputStream ba = null;
    try {
        if (xmlfilename != null && ((getDTDFilename() != null && !isInternDTD()) || (isInternDTD()))) {
            xmlfile = KettleVFS.getFileObject(getXMLFilename());

            if (xmlfile.exists()) {

                URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL();
                StringBuffer xmlStringbuffer = new StringBuffer("");

                BufferedReader xmlBufferedReader = null;
                InputStreamReader is = null;
                try {
                    // open XML File
                    is = new InputStreamReader(xmlFile.openStream());
                    xmlBufferedReader = new BufferedReader(is);

                    char[] buffertXML = new char[1024];
                    int LenXML = -1;
                    while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1) {
                        xmlStringbuffer.append(buffertXML, 0, LenXML);
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (xmlBufferedReader != null) {
                        xmlBufferedReader.close();
                    }
                }

                // Prepare parsing ...
                DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();

                // Let's try to get XML document encoding

                DocBuilderFactory.setValidating(false);
                ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8"));
                Document xmlDocDTD = DocBuilder.parse(ba);
                if (ba != null) {
                    ba.close();
                }

                String encoding = null;
                if (xmlDocDTD.getXmlEncoding() == null) {
                    encoding = "UTF-8";
                } else {
                    encoding = xmlDocDTD.getXmlEncoding();
                }

                int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");

                if (isInternDTD()) {
                    // DTD find in the XML document
                    if (xmlStartDTD != -1) {
                        log.logBasic(BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFound.Label",
                                getXMLFilename()));
                    } else {
                        setErrorMessage(BaseMessages.getString(PKG,
                                "JobEntryDTDValidator.ERRORDTDNotFound.Label", getXMLFilename()));
                    }

                } else {
                    // DTD in external document
                    // If we find an intern declaration, we remove it
                    DTDfile = KettleVFS.getFileObject(getDTDFilename());

                    if (DTDfile.exists()) {
                        if (xmlStartDTD != -1) {
                            int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD);
                            // String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
                            xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, "");
                        }

                        String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();

                        String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='"
                                + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '"
                                + KettleVFS.getFilename(DTDfile) + "'>\n";

                        int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD);
                        xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD);
                    } else {
                        log.logError(
                                BaseMessages.getString(PKG,
                                        "JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"),
                                BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",
                                        getDTDFilename()));
                    }
                }

                if (!(isInternDTD() && xmlStartDTD == -1 || (!isInternDTD() && !DTDfile.exists()))) {

                    // Let's parse now ...
                    MyErrorHandler error = new MyErrorHandler();
                    DocBuilderFactory.setValidating(true);
                    DocBuilder = DocBuilderFactory.newDocumentBuilder();
                    DocBuilder.setErrorHandler(error);

                    ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding));
                    xmlDocDTD = DocBuilder.parse(ba);

                    if (error.errorMessage == null) {
                        log.logBasic(BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Subject"),
                                BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Label",
                                        getXMLFilename()));

                        // Everything is OK
                        retval = true;
                    } else {
                        // Invalid DTD
                        setNrErrors(error.nrErrors);
                        setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorKO",
                                getXMLFilename(), error.nrErrors, error.errorMessage));
                    }
                }

            } else {
                if (!xmlfile.exists()) {
                    setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.FileDoesNotExist.Label",
                            getXMLFilename()));
                }
            }
        } else {
            setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.AllFilesNotNull.Label"));
        }
    } catch (Exception e) {
        setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.ErrorDTDValidator.Label",
                getXMLFilename(), getDTDFilename(), e.getMessage()));
    } finally {
        try {
            if (xmlfile != null) {
                xmlfile.close();
            }
            if (DTDfile != null) {
                DTDfile.close();
            }
            if (ba != null) {
                ba.close();
            }
        } catch (IOException e) {
            // Ignore close errors
        }
    }
    return retval;
}

From source file:org.wso2.carbon.humantask.core.utils.DOMUtils.java

/**
 * Convert a DOM node to a stringified XML representation.
 *
 * @param node DOM Node/*from ww w  .  j  a  va2s  . co m*/
 * @return String
 */
public static String domToString(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE);
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // create a proper XML encoding header based on the input document;
        // default to UTF-8 if the parent document's encoding is not accessible
        String usedEncoding = "UTF-8";
        Document parent = node.getOwnerDocument();
        if (parent != null) {
            String parentEncoding = parent.getXmlEncoding();
            if (parentEncoding != null) {
                usedEncoding = parentEncoding;
            }
        }

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding(usedEncoding);

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}