Example usage for org.w3c.dom Document getDocumentElement

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

Introduction

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

Prototype

public Element getDocumentElement();

Source Link

Document

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

Usage

From source file:com.vmware.identity.samlservice.Shared.java

/**
 * Method to convert Document to String/*from w w  w. j  av  a2 s.c  o m*/
 *
 * @param doc
 * @return
 */
public static String getStringFromDocument(Document doc) {
    try {
        return getStringFromElement(doc.getDocumentElement());
    } catch (Exception ex) {
        return null;
    }
}

From source file:Main.java

public static org.w3c.dom.Document read(java.io.InputStream is) {
    try {//from  w w w  . j a v a  2 s.  c  o m
        //todo?
        javax.xml.parsers.DocumentBuilder documentBuilder = getDocumentBuilder();
        synchronized (documentBuilder) {
            org.w3c.dom.Document rv = documentBuilder.parse(is);
            // TODO: we should validate this document with a schema and call DocumentBuilderFactory.setIgnoringElementContentWhitespace() instead.
            // but this work-around will at least allow us to load files that have empty white space.
            removeWhitespaceNodes(rv.getDocumentElement());
            return rv;
        }
    } catch (java.io.IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (org.xml.sax.SAXException saxe) {
        throw new RuntimeException(saxe);
    }
}

From source file:com.aurel.track.admin.customize.category.report.ReportBL.java

public static Map<String, Object> getTemplateDescription(InputStream is) {
    Map<String, Object> description = new HashMap<String, Object>();
    try {//from  w w  w  .j  a  v  a  2s  . c o m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(is);
        doc.getDocumentElement().normalize();
        try {
            NodeList nl = doc.getElementsByTagName("locale");
            for (int s = 0; s < nl.getLength(); s++) {
                Node localeNode = nl.item(s);
                if (localeNode.getNodeType() == Node.ELEMENT_NODE) {
                    Map<String, String> localizedStuff = new HashMap<String, String>();
                    String value = "";
                    String descript = "";
                    String listing = "";
                    String toolTip = "";
                    Element element = (Element) localeNode;
                    descript = getTagValue("description", element).trim();
                    listing = getTagValue("listing", element).trim();
                    toolTip = getTagValue("tool-tip", element).trim();
                    value = element.getAttribute("value");
                    if (value == null) {
                        value = "";
                    }
                    localizedStuff.put("listing", listing);
                    localizedStuff.put("description", descript);
                    localizedStuff.put("tool-tip", toolTip);

                    description.put("locale_" + value, localizedStuff);
                }
            }
        } catch (Exception e) {
            LOGGER.error("Getting the locale elements failed with " + e.getMessage());
        }
        NodeList nl = doc.getDocumentElement().getChildNodes();
        for (int s = 0; s < nl.getLength(); s++) {
            if (nl.item(s).getNodeType() == Node.ELEMENT_NODE) {
                description.put(nl.item(s).getNodeName(), nl.item(s).getChildNodes().item(0).getNodeValue());
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    return description;
}

From source file:eidassaml.starterkit.EidasMetadataNode.java

/**
 * Parse an metadata.xml/* w  w w.  ja v a 2s  .  c o m*/
 * 
 * @param is
 * @return
 * @throws XMLParserException
 * @throws UnmarshallingException
 * @throws CertificateException
 * @throws IOException
 * @throws ErrorCodeException 
 * @throws DOMException 
 */
public static EidasMetadataNode Parse(InputStream is) throws XMLParserException, UnmarshallingException,
        CertificateException, IOException, DOMException, ErrorCodeException {
    EidasMetadataNode eidasMetadataService = new EidasMetadataNode();
    BasicParserPool ppMgr = new BasicParserPool();
    Document inCommonMDDoc = ppMgr.parse(is);
    Element metadataRoot = inCommonMDDoc.getDocumentElement();
    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);
    EntityDescriptor metaData = (EntityDescriptor) unmarshaller.unmarshall(metadataRoot);

    eidasMetadataService.setId(metaData.getID());
    eidasMetadataService.setEntityId(metaData.getEntityID());
    eidasMetadataService.setValidUntil(metaData.getValidUntil().toDate());
    if (metaData.getExtensions() != null) {
        Element extension = metaData.getExtensions().getDOM();
        for (int i = 0; i < extension.getChildNodes().getLength(); i++) {
            Node n = extension.getChildNodes().item(i);
            if ("SPType".equals(n.getLocalName())) {
                eidasMetadataService.spType = EidasRequestSectorType.GetValueOf(n.getTextContent());
                break;
            }
        }
    }

    SPSSODescriptor ssoDescriptor = metaData.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");

    ssoDescriptor.getAssertionConsumerServices().forEach(s -> {
        String bindString = s.getBinding();
        if ("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST".equals(bindString)) {
            eidasMetadataService.setPostEndpoint(s.getLocation());
        }
    });

    for (KeyDescriptor k : ssoDescriptor.getKeyDescriptors()) {
        if (k.getUse() == UsageType.ENCRYPTION) {
            eidasMetadataService.encCert = GetFirstCertFromKeyDescriptor(k);
        } else if (k.getUse() == UsageType.SIGNING) {
            eidasMetadataService.sigCert = GetFirstCertFromKeyDescriptor(k);
        }
    }

    return eidasMetadataService;
}

From source file:fll.xml.XMLUtils.java

public static List<String> getSubjectiveCategoryNames(final Document challengeDocument) {
    final List<String> subjectiveCategories = new LinkedList<String>();
    for (final Element categoryElement : new NodelistElementCollectionAdapter(
            challengeDocument.getDocumentElement().getElementsByTagName("subjectiveCategory"))) {
        final String categoryName = categoryElement.getAttribute("name");
        subjectiveCategories.add(categoryName);
    }//from   w  w  w .  java 2s .  c om
    return subjectiveCategories;
}

From source file:fr.aliasource.webmail.server.proxy.client.http.DOMUtils.java

public static void serialise(Document doc, OutputStream out) throws TransformerException {
    TransformerFactory fac = TransformerFactory.newInstance();
    Transformer tf = fac.newTransformer();
    tf.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
    Source input = new DOMSource(doc.getDocumentElement());
    Result output = new StreamResult(out);
    tf.transform(input, output);//from  www  . j av  a  2s .c  o  m
}

From source file:eidassaml.starterkit.EidasMetadataService.java

public static EidasMetadataService Parse(InputStream is)
        throws XMLParserException, UnmarshallingException, CertificateException, IOException {
    EidasMetadataService eidasMetadataService = new EidasMetadataService();
    BasicParserPool ppMgr = new BasicParserPool();
    Document inCommonMDDoc = ppMgr.parse(is);
    Element metadataRoot = inCommonMDDoc.getDocumentElement();
    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);
    EntityDescriptor metaData = (EntityDescriptor) unmarshaller.unmarshall(metadataRoot);
    eidasMetadataService.setSupportcontact(unmarshalContactPerson(metaData.getContactPersons(), "support"));
    eidasMetadataService.setTechnicalContact(unmarshalContactPerson(metaData.getContactPersons(), "technical"));
    eidasMetadataService.setOrganisation(unmarshalOrganisation(metaData.getOrganization()));
    eidasMetadataService.setId(metaData.getID());
    eidasMetadataService.setEntityId(metaData.getEntityID());
    eidasMetadataService.setValidUntil(metaData.getValidUntil().toDate());
    IDPSSODescriptor idpssoDescriptor = metaData.getIDPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
    idpssoDescriptor.getSingleSignOnServices().forEach(s -> {
        String bindString = s.getBinding();
        if ("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST".equals(bindString)) {
            eidasMetadataService.setPostEndpoint(s.getLocation());
        } else if ("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect".equals(bindString)) {
            eidasMetadataService.setRedirectEndpoint(s.getLocation());
        }/*from  w w w .  j  av a2s .  c om*/
    });
    List<EidasPersonAttributes> attributes = new ArrayList<>();
    idpssoDescriptor.getAttributes().forEach(a -> {
        EidasPersonAttributes eidasPersonAttributes = null;
        try {
            eidasPersonAttributes = EidasNaturalPersonAttributes.GetValueOf(a.getName());
        } catch (Exception e1) { //legal person?
            try {
                eidasPersonAttributes = EidasLegalPersonAttributes.GetValueOf(a.getName());
            } catch (Exception e) { //no natural and no legal
                //ignore error, perhaps log?
            }
        }

        attributes.add(eidasPersonAttributes);
    });
    eidasMetadataService.setAttributes(attributes);
    for (KeyDescriptor k : idpssoDescriptor.getKeyDescriptors()) {
        if (k.getUse() == UsageType.ENCRYPTION) {
            eidasMetadataService.encCert = GetFirstCertFromKeyDescriptor(eidasMetadataService, k);
        } else if (k.getUse() == UsageType.SIGNING) {
            eidasMetadataService.sigCert = GetFirstCertFromKeyDescriptor(eidasMetadataService, k);
        }
    }

    return eidasMetadataService;
}

From source file:it.osm.gtfs.input.OSMParser.java

public static List<Stop> readOSMStops(String fileName)
        throws ParserConfigurationException, SAXException, IOException {
    List<Stop> result = new ArrayList<Stop>();
    Multimap<String, Stop> refBuses = HashMultimap.create();
    Multimap<String, Stop> refRails = HashMultimap.create();

    File file = new File(fileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();

    NodeList nodeLst = doc.getElementsByTagName("node");

    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        Stop st = new Stop(null, null,
                Double.valueOf(fstNode.getAttributes().getNamedItem("lat").getNodeValue()),
                Double.valueOf(fstNode.getAttributes().getNamedItem("lon").getNodeValue()), null);
        st.originalXMLNode = fstNode;//from   w ww . j av a  2s. c o m
        NodeList att = fstNode.getChildNodes();
        for (int t = 0; t < att.getLength(); t++) {
            Node attNode = att.item(t);
            if (attNode.getAttributes() != null) {
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("ref"))
                    st.setCode(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("name"))
                    st.setName(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("gtfs_id"))
                    st.setGtfsId(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("highway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("bus_stop"))
                    st.setIsRailway(false);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("railway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("tram_stop"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("railway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("station"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("public_transport")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("stop_position")
                        && st.isRailway() == null)
                    st.setIsStopPosition(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("train")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("tram")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("bus")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(false);
            }
        }

        if (st.isRailway() == null)
            if (st.isStopPosition())
                continue; //ignore unsupported stop positions (like ferries)
            else
                throw new IllegalArgumentException("Unknow node type for node: " + st.getOSMId()
                        + ". We support only highway=bus_stop, public_transport=stop_position, railway=tram_stop and railway=station");

        //Check duplicate ref in osm
        if (st.getCode() != null) {
            if (st.isStopPosition() == null || st.isStopPosition() == false) {
                if (st.isRailway()) {
                    if (refRails.containsKey(st.getCode())) {
                        for (Stop existingStop : refRails.get(st.getCode())) {
                            if (OSMDistanceUtils.distVincenty(st.getLat(), st.getLon(), existingStop.getLat(),
                                    existingStop.getLon()) < 500)
                                System.err.println("Warning: The ref " + st.getCode()
                                        + " is used in more than one node within 500m this may lead to bad import."
                                        + " (nodes ids:" + st.getOSMId() + "," + existingStop.getOSMId() + ")");
                        }
                    }

                    refRails.put(st.getCode(), st);
                } else {
                    if (refBuses.containsKey(st.getCode())) {
                        for (Stop existingStop : refBuses.get(st.getCode())) {
                            if (OSMDistanceUtils.distVincenty(st.getLat(), st.getLon(), existingStop.getLat(),
                                    existingStop.getLon()) < 500)
                                System.err.println("Warning: The ref " + st.getCode()
                                        + " is used in more than one node within 500m this may lead to bad import."
                                        + " (nodes ids:" + st.getOSMId() + "," + existingStop.getOSMId() + ")");
                        }
                    }
                    refBuses.put(st.getCode(), st);
                }
            }
        }
        result.add(st);
    }

    return result;
}

From source file:edu.harvard.i2b2.eclipse.plugins.query.utils.XmlUtil.java

public static XmlValueType stringToXml(String c_xml) {
    if (c_xml == null)
        return null;
    else {/*from w  w w .j  a v a  2  s.c  o  m*/
        // convert 
        SAXBuilder parser = new SAXBuilder();
        java.io.StringReader xmlStringReader = new java.io.StringReader(c_xml);
        Element rootElement = null;
        try {
            org.jdom.Document metadataDoc = parser.build(xmlStringReader);
            org.jdom.output.DOMOutputter out = new DOMOutputter();
            Document doc = out.output(metadataDoc);
            rootElement = doc.getDocumentElement();
        } catch (JDOMException e) {
            log.error(e.getMessage());
            return null;
        } catch (IOException e1) {
            log.error(e1.getMessage());
            return null;
        }
        if (rootElement != null) {
            XmlValueType xml = new XmlValueType();
            xml.getAny().add(rootElement);
            return xml;
        }
    }
    return null;
}

From source file:apps.ParsedPost.java

public static ParsedPost parsePost(String postText, boolean excludeCode) throws Exception {
    Document post = XmlHelper.parseDocWithoutXMLDecl(postText);

    NamedNodeMap attr = post.getDocumentElement().getAttributes();

    if (null == attr) {
        throw new Exception("Invalid entry, no attributes!");
    }/*from  w  w  w .  j  a  v a 2s  .  c  o  m*/

    Node itemId = attr.getNamedItem("Id");
    Node itemAcceptedAnswerId = attr.getNamedItem("AcceptedAnswerId");
    Node itemParentId = attr.getNamedItem("ParentId");
    Node itemPostTypeId = attr.getNamedItem("PostTypeId");
    Node itemTitle = attr.getNamedItem("Title");
    Node itemBody = attr.getNamedItem("Body");

    if (null == itemId)
        throw new Exception("Missing Id");
    if (null == itemPostTypeId)
        throw new Exception("Missing PostTypeId");
    if (null == itemBody)
        throw new Exception("Missing Body");

    String id = XmlHelper.getNodeValue(itemId);
    String acceptedAnswerId = itemAcceptedAnswerId != null ? XmlHelper.getNodeValue(itemAcceptedAnswerId) : "";
    String postIdType = XmlHelper.getNodeValue(itemPostTypeId);
    String parentId = itemParentId != null ? XmlHelper.getNodeValue(itemParentId) : "";
    String title = itemTitle != null ? XmlHelper.getNodeValue(itemTitle) : "";
    String body = XmlHelper.getNodeValue(itemBody);

    return new ParsedPost(id, acceptedAnswerId, parentId, postIdType,
            (new PostCleaner(title, MIN_CODE_CHARS, true)).getText(),
            (new PostCleaner(body, MIN_CODE_CHARS, excludeCode)).getText());
}