Example usage for org.w3c.dom.ls LSSerializer writeToString

List of usage examples for org.w3c.dom.ls LSSerializer writeToString

Introduction

In this page you can find the example usage for org.w3c.dom.ls LSSerializer writeToString.

Prototype

public String writeToString(Node nodeArg) throws DOMException, LSException;

Source Link

Document

Serialize the specified node as described above in the general description of the LSSerializer interface.

Usage

From source file:com.limegroup.gnutella.archive.ArchiveContribution.java

/**
 * @throws   IllegalStateException/*  w w  w . j  a va 2  s .co m*/
 *          If java's DOMImplementationLS class is screwed up or
 *          this code is buggy
 * @param document
 * @return
 */
private String serializeDocument(Document document) {

    try {
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMImplementationSourceImpl");
        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

        final LSSerializer writer = impl.createLSSerializer();
        final String str = writer.writeToString(document);

        return str;

    } catch (final ClassNotFoundException e) {
        final IllegalStateException ise = new IllegalStateException();
        ise.initCause(e);
        throw ise;
    } catch (final InstantiationException e) {
        final IllegalStateException ise = new IllegalStateException();
        ise.initCause(e);
        throw ise;
    } catch (final IllegalAccessException e) {
        final IllegalStateException ise = new IllegalStateException();
        ise.initCause(e);
        throw ise;
    }

}

From source file:org.dasein.cloud.cloudstack.CSMethod.java

private String prettifyXml(Document doc) {
    try {//from ww w.  j  a  v a2 s . com
        DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance()
                .getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        return writer.writeToString(doc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Creates a DOM element node from JAXB element.
 * @param element/*www .j  a  v  a2s .  c  om*/
 * @return
 */
private <T> T createJaxbObjectFromElement(Element element) {
    LSSerializer serializer = XMLUtils.createLSSerializer();
    return (T) springBeanMarshaller
            .unmarshal(new StreamSource(new StringReader(serializer.writeToString(element))));
}

From source file:eumetsat.pn.common.ISO2JSON.java

private JSONObject convert(Document xmlDocument) throws XPathExpressionException, IOException {
    String expression = null;//w  w  w .ja  v  a  2  s  .  com
    String result = null;
    XPath xPath = XPathFactory.newInstance().newXPath();
    JSONObject jsonObject = new JSONObject();

    String xpathFileID = "//*[local-name()='fileIdentifier']/*[local-name()='CharacterString']";
    String fileID = xPath.compile(xpathFileID).evaluate(xmlDocument);
    log.trace("{} >>> {}", xpathFileID, fileID);
    if (fileID != null) {
        jsonObject.put(FILE_IDENTIFIER_PROPERTY, fileID);
    }

    expression = "//*[local-name()='hierarchyLevelName']/*[local-name()='CharacterString']";
    JSONArray list = new JSONArray();
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        list.add(nodeList.item(i).getFirstChild().getNodeValue());
    }
    if (list.size() > 0) {
        JSONObject hierarchies = parseThemeHierarchy((String) jsonObject.get(FILE_IDENTIFIER_PROPERTY), list);
        hierarchies.writeJSONString(writer);
        jsonObject.put("hierarchyNames", hierarchies);
        log.trace("{} >>> {}", expression, jsonObject.get("hierarchyNames"));
    }

    // Get Contact info
    String deliveryPoint = "//*[local-name()='address']//*[local-name()='deliveryPoint']/*[local-name()='CharacterString']";
    String city = "//*[local-name()='address']//*[local-name()='city']/*[local-name()='CharacterString']";
    String administrativeArea = "//*[local-name()='address']//*[local-name()='administrativeArea']/*[local-name()='CharacterString']";
    String postalCode = "//*[local-name()='address']//*[local-name()='postalCode']/*[local-name()='CharacterString']";
    String country = "//*[local-name()='address']//*[local-name()='country']/*[local-name()='CharacterString']";
    String email = "//*[local-name()='address']//*[local-name()='electronicMailAddress']/*[local-name()='CharacterString']";

    StringBuilder addressString = new StringBuilder();
    StringBuilder emailString = new StringBuilder();

    appendIfResultNotNull(xPath, xmlDocument, addressString, deliveryPoint);

    result = xPath.compile(postalCode).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(city).evaluate(xmlDocument);
    if (result != null) {
        addressString.append(" ").append(result.trim());
    }

    result = xPath.compile(administrativeArea).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(country).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(email).evaluate(xmlDocument);
    if (result != null) {
        emailString.append(result.trim());
    }

    HashMap<String, String> map = new HashMap<>();
    map.put("address", addressString.toString());
    map.put("email", emailString.toString());
    jsonObject.put("contact", map);
    log.trace("contact: {}", Arrays.toString(map.entrySet().toArray()));

    // add identification info
    String abstractStr = "//*[local-name()='identificationInfo']//*[local-name()='abstract']/*[local-name()='CharacterString']";
    String titleStr = "//*[local-name()='identificationInfo']//*[local-name()='title']/*[local-name()='CharacterString']";
    String statusStr = "//*[local-name()='identificationInfo']//*[local-name()='status']/*[local-name()='MD_ProgressCode']/@codeListValue";
    String keywords = "//*[local-name()='keyword']/*[local-name()='CharacterString']";

    HashMap<String, Object> idMap = new HashMap<>();

    result = xPath.compile(titleStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("title", result.trim());
    }

    result = xPath.compile(abstractStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("abstract", result.trim());
    }

    result = xPath.compile(statusStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("status", result.trim());
    }

    list = new JSONArray();
    nodeList = (NodeList) xPath.compile(keywords).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        list.add(nodeList.item(i).getFirstChild().getNodeValue());
    }

    if (list.size() > 0) {
        idMap.put("keywords", list);
    }

    jsonObject.put("identificationInfo", idMap);
    log.trace("idMap: {}", idMap);

    // get thumbnail product
    String browseThumbnailStr = "//*[local-name()='graphicOverview']//*[local-name()='MD_BrowseGraphic']//*[local-name()='fileName']//*[local-name()='CharacterString']";
    result = xPath.compile(browseThumbnailStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("thumbnail", result.trim());
        log.trace("thumbnail: {}", result);
    }

    // add Geo spatial information
    String westBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='westBoundLongitude']/*[local-name()='Decimal']";
    String eastBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='eastBoundLongitude']/*[local-name()='Decimal']";
    String northBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='northBoundLatitude']/*[local-name()='Decimal']";
    String southBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='southBoundLatitude']/*[local-name()='Decimal']";

    // create a GeoJSON envelope object
    HashMap<String, Object> latlonMap = new HashMap<>();
    latlonMap.put("type", "envelope");

    JSONArray envelope = new JSONArray();
    JSONArray leftTopPt = new JSONArray();
    JSONArray rightDownPt = new JSONArray();

    result = xPath.compile(westBLonStr).evaluate(xmlDocument);
    if (result != null) {
        leftTopPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(northBLatStr).evaluate(xmlDocument);
    if (result != null) {
        leftTopPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(eastBLonStr).evaluate(xmlDocument);
    if (result != null) {
        rightDownPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(southBLatStr).evaluate(xmlDocument);
    if (result != null) {
        rightDownPt.add(Double.parseDouble(result.trim()));
    }

    envelope.add(leftTopPt);
    envelope.add(rightDownPt);

    latlonMap.put("coordinates", envelope);
    jsonObject.put("location", latlonMap);

    DOMImplementationLS domImplementation = (DOMImplementationLS) xmlDocument.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    String xmlString = lsSerializer.writeToString(xmlDocument);

    jsonObject.put("xmldoc", xmlString);

    return jsonObject;
}

From source file:com.marklogic.client.impl.CombinedQueryBuilderImpl.java

private CombinedQueryDefinitionImpl parseCombinedQuery(RawCombinedQueryDefinition qdef) {
    DOMHandle handle = new DOMHandle();
    HandleAccessor.receiveContent(handle, HandleAccessor.contentAsString(qdef.getHandle()));
    Document combinedQueryXml = handle.get();
    DOMImplementationLS domImplementation = (DOMImplementationLS) combinedQueryXml.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("xml-declaration", false);

    NodeList nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "options");
    Node n = nl.item(0);/*from ww  w.j  a v  a  2 s. c  o m*/
    String options = null;
    StringHandle optionsHandle = null;
    if (n != null) {
        options = lsSerializer.writeToString(n);
        optionsHandle = new StringHandle(options).withFormat(Format.XML);
    }

    //TODO this could be more than one string...
    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "qtext");
    n = nl.item(0);
    String qtext = null;
    if (n != null) {
        qtext = lsSerializer.writeToString(n);
    }

    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "sparql");
    n = nl.item(0);
    String sparql = null;
    if (n != null) {
        sparql = lsSerializer.writeToString(n);
    }

    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "query");
    n = nl.item(0);
    String query = null;
    if (n != null) {
        query = lsSerializer.writeToString(nl.item(0));
    }
    StringHandle structuredQueryHandle = new StringHandle().with(query).withFormat(Format.XML);
    RawStructuredQueryDefinition structuredQueryDefinition = new RawQueryDefinitionImpl.Structured(
            structuredQueryHandle);
    return new CombinedQueryDefinitionImpl(structuredQueryDefinition, optionsHandle, qtext, sparql);
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Transform into formatted XML.//from   ww w . j a  va 2 s.co  m
 */
private String getFormattedXml(Node node) {
    Document document = node.getOwnerDocument().getImplementation().createDocument("", "fake", null);
    Element copy = (Element) document.importNode(node, true);
    document.importNode(node, false);
    document.removeChild(document.getDocumentElement());
    document.appendChild(copy);
    DOMImplementation domImpl = document.getImplementation();
    DOMImplementationLS domImplLs = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
    LSSerializer serializer = domImplLs.createLSSerializer();
    serializer.getDomConfig().setParameter("format-pretty-print", true);
    return serializer.writeToString(document);
}

From source file:edu.harvard.i2b2.query.ui.ConceptTreePanel.java

public static String nodeToString(Node node) {
    DOMImplementation impl = node.getOwnerDocument().getImplementation();
    DOMImplementationLS factory = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = factory.createLSSerializer();
    return serializer.writeToString(node);
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * Utility method for serializing DOM to a String
 * @param doc Document to serialize//  w  w  w.ja va  2  s.c o m
 * @return XML document as a String
 */
private String writeDomToString(Document doc) {
    LSSerializer writer = domLoadSaveImpl.createLSSerializer();
    DOMConfiguration domConfig = writer.getDomConfig();
    domConfig.setParameter("xml-declaration", false);
    String xmlString = writer.writeToString(doc);
    return xmlString;
}

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

private String getStringFromDoc(Document doc) {
    DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    return lsSerializer.writeToString(doc);
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** Given the SOAP response received by AXIS on the successful call to a Meridio
* Web Service, this helper method returns a castor RMDataSet object which represents
* the XML//from  ww  w  . ja  v  a  2 s .  com
*
* This makes it much easier to subsequently manipulate the data that has been
* returned from the web service, and ensures that the Meridio wrapper implementation
* is as close to native .NET code as we can get.
*/
protected RMDataSet getRMDataSet(MessageElement[] messageElement) throws MeridioDataSetException {
    if (oLog != null)
        oLog.debug("Meridio: Entered getRMDataSet method.");

    try {
        if (messageElement.length != 2) {
            if (oLog != null)
                oLog.warn("Meridio: SOAP Message not of expected length");
            if (oLog != null)
                oLog.debug("Meridio: Exiting getRMDataSet method with null.");
            return null;
        }

        /*
        for (int i = 0; i < messageElement.length; i++)
        {
          oLog.debug("Meridio: Message Part: " + i + " " + messageElement[i]);
        }
        */

        Document document = messageElement[1].getAsDocument();
        NodeList nl = document.getElementsByTagName("RMDataSet");

        NodeList errors = document.getElementsByTagName("diffgr:errors");
        if (errors.getLength() != 0) {
            String errorXML = "";

            if (oLog != null)
                oLog.error("Found <" + errors.getLength() + "> errors in returned data set");
            for (int i = 0; i < errors.getLength(); i++) {

                Element e = (Element) errors.item(i);

                Document resultDocument = new DocumentImpl();
                Node node = resultDocument.importNode(e, true);

                resultDocument.appendChild(node);

                DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation();
                DOMImplementationLS implLS = (DOMImplementationLS) domImpl;
                LSSerializer writer = implLS.createLSSerializer();
                errorXML += writer.writeToString(resultDocument) + "\n";

                if (oLog != null)
                    oLog.warn("..." + errorXML);
            }
            throw new MeridioDataSetException(errorXML);
        }

        if (nl.getLength() != 1) {
            if (oLog != null)
                oLog.warn("Meridio: Returning null - could not find RMDataSet in SOAP Message");
            if (oLog != null)
                oLog.debug("Meridio: Exiting getRMDataSet method with null.");
            return null;
        }

        Element e = (Element) nl.item(0);
        Document resultDocument = new DocumentImpl();
        Node node = resultDocument.importNode(e, true);

        resultDocument.appendChild(node);

        DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation();
        DOMImplementationLS implLS = (DOMImplementationLS) domImpl;
        LSSerializer writer = implLS.createLSSerializer();
        String documentXML = writer.writeToString(resultDocument);

        StringReader sr = new StringReader(documentXML);
        RMDataSet dsRM = new RMDataSet();
        dsRM = RMDataSet.unmarshal(sr);
        if (oLog != null)
            oLog.debug("Meridio: Exiting getRMDataSet method.");
        return dsRM;
    } catch (ClassNotFoundException classNotFoundException) {
        throw new MeridioDataSetException(
                "Could not find the DOM Parser class when unmarshalling the Meridio Dataset",
                classNotFoundException);
    } catch (InstantiationException instantiationException) {
        throw new MeridioDataSetException(
                "Error instantiating the DOM Parser when unmarshalling the Meridio Dataset",
                instantiationException);
    } catch (IllegalAccessException illegalAccessException) {
        throw new MeridioDataSetException("DOM Parser illegal access when unmarshalling the Meridio Dataset",
                illegalAccessException);
    } catch (MarshalException marshalException) {
        throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset",
                marshalException);
    } catch (ValidationException validationException) {
        throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset",
                validationException);
    } catch (Exception ex) // from messageElement[1].getAsDocument();
    {
        throw new MeridioDataSetException("Error retrieving the XML Document from the Web Service response",
                ex);
    }
}