Search in sources :

Example 46 with DOMImplementationLS

use of org.w3c.dom.ls.DOMImplementationLS in project coprhd-controller by CoprHD.

the class CinderApiUtils method convertMapToXML.

/**
 * This function converts Map to xml format
 *
 * @param map Hash Map
 * @param root root Element Name
 * @return XML object in String form
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws DOMException
 */
public static Object convertMapToXML(Map<String, ? extends Object> map, String root, Class<?> clazz) throws DOMException, IllegalArgumentException, IllegalAccessException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    Document document = null;
    LSSerializer lsSerializer = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
        Element rootElement = document.createElement(root);
        if (null != rootElement) {
            document.appendChild(rootElement);
            for (Entry<String, ? extends Object> entry : map.entrySet()) {
                Element mapElement = document.createElement(entry.getKey());
                if (entry.getValue() instanceof String) {
                    mapElement.setTextContent(entry.getValue().toString());
                } else {
                    Method[] methods = clazz.getDeclaredMethods();
                    String getterPrefix = "get";
                    for (Method method : methods) {
                        String methodName = method.getName();
                        if (methodName.startsWith("get")) {
                            String fieldName = methodName.substring(getterPrefix.length(), getterPrefix.length() + 1).toLowerCase();
                            fieldName = fieldName + methodName.substring(getterPrefix.length() + 1);
                            Element subElement = document.createElement(fieldName);
                            try {
                                subElement.setTextContent(String.valueOf(method.invoke(clazz.cast(entry.getValue()))));
                            } catch (SecurityException e) {
                                _log.info("The getter method {} for the field led to security exception {}", methodName);
                            } catch (Exception e) {
                                _log.info("The getter method {} for the field failed with exception {}", methodName, e.toString());
                            }
                            mapElement.appendChild(subElement);
                        }
                    }
                }
                rootElement.appendChild(mapElement);
            }
        }
        DOMImplementationLS domImplementation = (DOMImplementationLS) document.getImplementation();
        lsSerializer = domImplementation.createLSSerializer();
    } catch (ParserConfigurationException e) {
        throw APIException.internalServerErrors.ioWriteError(root);
    }
    return lsSerializer.writeToString(document);
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSSerializer(org.w3c.dom.ls.LSSerializer) Method(java.lang.reflect.Method) Document(org.w3c.dom.Document) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) DOMException(org.w3c.dom.DOMException) IOException(java.io.IOException) JsonGenerationException(org.codehaus.jackson.JsonGenerationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) JSONException(org.codehaus.jettison.json.JSONException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 47 with DOMImplementationLS

use of org.w3c.dom.ls.DOMImplementationLS in project cloudstack by apache.

the class VsmCommand method serialize.

private static String serialize(DOMImplementation domImpl, Document document) {
    DOMImplementationLS ls = (DOMImplementationLS) domImpl;
    LSSerializer lss = ls.createLSSerializer();
    return lss.writeToString(document);
}
Also used : DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSSerializer(org.w3c.dom.ls.LSSerializer)

Example 48 with DOMImplementationLS

use of org.w3c.dom.ls.DOMImplementationLS in project survey by markoniemi.

the class XPathTest method xmlDocumentAsString.

private String xmlDocumentAsString(Document document) {
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) document.getImplementation();
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
    return lsSerializer.writeToString(document);
}
Also used : DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSSerializer(org.w3c.dom.ls.LSSerializer)

Example 49 with DOMImplementationLS

use of org.w3c.dom.ls.DOMImplementationLS in project flexmark-java by vsch.

the class XmlDocxSorter method sortDocumentParts.

public static String sortDocumentParts(String xml) {
    try {
        final InputSource src = new InputSource(new StringReader(xml));
        final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(false);
        final Document document = builderFactory.newDocumentBuilder().parse(src);
        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();
        // Set this to true if the output needs to be beautified.
        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        writer.getDomConfig().setParameter("xml-declaration", false);
        final HashMap<String, HashMap<Pattern, DocxPartEntry>> contentTypeNameEntry = new HashMap<String, HashMap<Pattern, DocxPartEntry>>();
        for (DocxPartEntry entry : entries) {
            HashMap<Pattern, DocxPartEntry> entryHashMap = contentTypeNameEntry.get(entry.contentType);
            if (entryHashMap == null) {
                entryHashMap = new HashMap<>();
                contentTypeNameEntry.put(entry.contentType, entryHashMap);
            }
            entryHashMap.put(entry.regex, entry);
        }
        final DocxPartEntry unknownPartEntry = new DocxPartEntry(99, "", "");
        final ArrayList<DocxPartEntry> partEntries = new ArrayList<>();
        final int[] unknownIndex = new int[] { 0 };
        // final NodeList parts = document.getElementsByTagName("pkg:part");
        final StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        forAllChildren(document, XMLNS_PKG, arrayOf("package"), new Consumer<Node>() {

            @Override
            public void accept(final Node pkg) {
                forAllChildren(pkg, XMLNS_PKG, arrayOf("part"), new Consumer<Node>() {

                    @Override
                    public void accept(final Node part) {
                        sortNodeAttributes(part);
                        sortRelationships(part);
                        sortProperties(part);
                        final NamedNodeMap attributes = part.getAttributes();
                        final Node contentTypeNode = attributes.getNamedItem("pkg:contentType");
                        boolean handled = false;
                        if (contentTypeNode != null) {
                            String contentType = contentTypeNode.getNodeValue();
                            final HashMap<Pattern, DocxPartEntry> entryHashMap = contentTypeNameEntry.get(contentType);
                            if (entryHashMap != null) {
                                final Node nameNode = attributes.getNamedItem("pkg:name");
                                // now we find the entry for these
                                if (nameNode != null) {
                                    String name = nameNode.getNodeValue();
                                    for (Entry<Pattern, DocxPartEntry> entry : entryHashMap.entrySet()) {
                                        Matcher matcher = entry.getKey().matcher(name);
                                        if (matcher.matches()) {
                                            int index = matcher.groupCount() > 0 ? Integer.parseInt(matcher.group(1)) : 0;
                                            partEntries.add(new DocxPartEntry(entry.getValue(), part, index));
                                            handled = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (!handled) {
                            // make it unknown
                            partEntries.add(new DocxPartEntry(unknownPartEntry, part, ++unknownIndex[0]));
                        }
                    }
                });
                for (DocxPartEntry pe : partEntries) {
                    pkg.removeChild(pe.node);
                }
                Collections.sort(partEntries, new Comparator<DocxPartEntry>() {

                    @Override
                    public int compare(final DocxPartEntry o1, final DocxPartEntry o2) {
                        final int ordinals = Integer.compare(o1.ordinal, o2.ordinal);
                        return ordinals != 0 ? ordinals : Integer.compare(o1.index, o2.index);
                    }
                });
                for (DocxPartEntry pe : partEntries) {
                    pkg.appendChild(pe.node);
                }
                sb.append(writer.writeToString(pkg));
            }
        });
        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Matcher(java.util.regex.Matcher) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) Consumer(com.vladsch.flexmark.util.Consumer) StringReader(java.io.StringReader) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) Pattern(java.util.regex.Pattern) NamedNodeMap(org.w3c.dom.NamedNodeMap) LSSerializer(org.w3c.dom.ls.LSSerializer)

Example 50 with DOMImplementationLS

use of org.w3c.dom.ls.DOMImplementationLS in project flexmark-java by vsch.

the class XmlFormatter method format.

public static String format(String xml) {
    try {
        final InputSource src = new InputSource(new StringReader(xml));
        final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
        final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
        // May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();
        // Set this to true if the output needs to be beautified.
        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        // Set this to true if the declaration is needed to be outputted.
        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
        return writer.writeToString(document);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) Node(org.w3c.dom.Node) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) StringReader(java.io.StringReader) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) LSSerializer(org.w3c.dom.ls.LSSerializer)

Aggregations

DOMImplementationLS (org.w3c.dom.ls.DOMImplementationLS)53 LSSerializer (org.w3c.dom.ls.LSSerializer)42 Document (org.w3c.dom.Document)22 DOMImplementationRegistry (org.w3c.dom.bootstrap.DOMImplementationRegistry)21 LSOutput (org.w3c.dom.ls.LSOutput)18 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)15 IOException (java.io.IOException)13 DocumentBuilder (javax.xml.parsers.DocumentBuilder)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)13 Node (org.w3c.dom.Node)12 DOMImplementation (org.w3c.dom.DOMImplementation)10 StringWriter (java.io.StringWriter)9 Element (org.w3c.dom.Element)9 LSParser (org.w3c.dom.ls.LSParser)8 InputSource (org.xml.sax.InputSource)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 StringReader (java.io.StringReader)5 TransformerException (javax.xml.transform.TransformerException)5 NodeList (org.w3c.dom.NodeList)5 LSInput (org.w3c.dom.ls.LSInput)5