Example usage for org.w3c.dom Document getChildNodes

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

Introduction

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

Prototype

public NodeList getChildNodes();

Source Link

Document

A NodeList that contains all children of this node.

Usage

From source file:org.sakaiproject.content.chh.dspace.ContentHostingHandlerImplDSpace.java

protected List listDSpaceItemsIn(String endpoint, String base) {
    List<String> resultList = new ArrayList<String>();
    try {/*w  ww  .j av a  2  s  . c om*/
        Document d = getDSpaceProps(endpoint, base, 1);
        if (d == null)
            return null;

        // find multistatus node
        Node node_multistatus = null;
        NodeList nl = d.getChildNodes();
        for (int j = 0; j < nl.getLength(); ++j)
            if (nl.item(j).getNodeName() != null && nl.item(j).getNodeName().equals(LAYER1)) {
                node_multistatus = nl.item(j);
                break;
            }
        if (node_multistatus == null)
            return null;

        // examine each response node, looking for ones which match the
        // string sought
        nl = node_multistatus.getChildNodes();
        for (int j = 0; j < nl.getLength(); ++j) {
            // only interested in nodes with name="response"
            if (nl.item(j).getNodeName() == null || !nl.item(j).getNodeName().equals(LAYER2))
                continue;
            Node node_response = nl.item(j);
            NodeList resources = node_response.getChildNodes();

            // grab the resource handle
            String handle = null;
            for (int k = 0; k < resources.getLength(); ++k)
                if (resources.item(k).getNodeName() != null && resources.item(k).getNodeName().equals(HREF)) {
                    handle = resources.item(k).getFirstChild().getNodeValue().trim();
                    break;
                }
            if (handle == null)
                continue; // skip this resource if it
            // doesn't have an 'href' node.
            String[] handles = handle.split("/");
            handle = handles[handles.length - 1]; // only interested in
            // the last one
            handle = handle.replace("%24", "/").substring(4);
            if (isWithdrawn(resources))
                return new ArrayList(); // if
            // the
            // base
            // is
            // withdrawn,
            // ignore
            // all
            // children
            if (handle.equals(base))
                continue; // response includes the
            // object queried itself --
            // omit this from the output
            // list

            // loop over the child nodes looking at propstat blocks...
            for (int k = 0; k < resources.getLength(); ++k) {
                if (resources.item(k).getNodeName() == null || !resources.item(k).getNodeName().equals(LAYER3))
                    continue; // only
                // want
                // 'propstat'
                // nodes

                NodeList propstats = resources.item(k).getChildNodes();

                // first check whether status is OK (ignore all HTTP status
                // codes except 200)
                // no status node is assumed to mean OK. abort this propstat
                // if status is not OK.
                boolean status_ok = true;
                for (int l = 0; l < propstats.getLength(); ++l)
                    if (propstats.item(l).getNodeName() != null
                            && propstats.item(l).getNodeName().equals(STATUS)
                            && !propstats.item(l).getFirstChild().getNodeValue().trim().equals(ST_OK)) {
                        status_ok = false;
                        break;
                    }
                if (!status_ok)
                    continue; // skip this propstat node

                // look for child nodes with name 'prop', having nested
                // child called 'displayname'
                // if the displayname is the 'needle' being sought, return
                // handle.
                for (int l = 0; l < propstats.getLength(); ++l) {
                    if (propstats.item(l).getNodeName() != null
                            && propstats.item(l).getNodeName().equals(LAYER4)) {
                        NodeList properties = propstats.item(l).getChildNodes();
                        for (int m = 0; m < properties.getLength(); ++m)
                            if (properties.item(m).getNodeName() != null
                                    && properties.item(m).getNodeName().equals(DISPNM))
                                resultList.add(properties.item(m).getFirstChild().getNodeValue().trim());
                    }
                }
            }
        }
    } catch (Exception e) {
        log.warn("Error in CHH DSpace mechanism: parse error: [" + e.toString() + "]");
        return new ArrayList();
    }
    return resultList; // problem talking to DSpace or named resource has
    // gone
}

From source file:org.sakaiproject.content.chh.file.ContentHostingHandlerImplFileSystem.java

public ContentEntity getVirtualContentEntity(ContentEntity edit, String finalId) {
    // Algorithm: get the mount point from the XML file represented by 'edit'
    // construct a new ContentEntityFileSystem and return it
    try {/* w  w  w.  j a v a 2 s  . c o  m*/
        boolean showHiddenFiles = false;
        boolean searchable = false; // allow the sakai-search tool to index the virtual hierarchy?
        byte[] xml = ((ContentResource) edit).getContent();
        if (xml == null)
            return null;
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        if (db == null)
            return null;
        Document d = db.parse(new ByteArrayInputStream(xml));
        if (d == null)
            return null;
        Node node_mountpoint = null;
        NodeList nl = d.getChildNodes();
        for (int j = 0; j < nl.getLength(); ++j)
            if (nl.item(j).getNodeName() != null && nl.item(j).getNodeName().equals(XML_NODE_NAME)) {
                node_mountpoint = nl.item(j);
                break;
            }
        if (node_mountpoint == null)
            return null;

        Node node_basepath = node_mountpoint.getAttributes().getNamedItem(XML_ATTRIBUTE_NAME);
        if (node_basepath == null)
            return null;
        final String basepath = node_basepath.getNodeValue();

        Node node_hiddenFiles = node_mountpoint.getAttributes().getNamedItem(XML_ATTRIBUTE_HIDDEN);
        if (node_hiddenFiles != null)
            showHiddenFiles = Boolean.parseBoolean(node_hiddenFiles.getNodeValue());

        Node node_searchable = node_mountpoint.getAttributes().getNamedItem(XML_ATTRIBUTE_SEARCHABLE);
        if (node_searchable != null)
            searchable = Boolean.parseBoolean(node_searchable.getNodeValue());

        if (basepath == null || basepath.equals(""))
            return null; // invalid mountpoint specification

        String relativePath = finalId.substring(edit.getId().length());
        ContentEntityFileSystem cefs = resolveToFileOrDirectory(edit, basepath, relativePath, this,
                showHiddenFiles, searchable);
        if ("/".equals(finalId.substring(finalId.length() - 1)) && (cefs instanceof ContentResourceFileSystem))
            cefs = ((ContentResourceFileSystem) cefs).convertToCollection();
        Edit ce = cefs.wrap();
        if (ce == null)
            return null; // happens when the requested URL requires a log on but the user is not logged on
        return (ContentEntity) ce;
    } catch (Exception e) {
        log.warn("Invalid XML for the mountpoint [" + edit.getId() + "], error is [" + e + "]");
        return (ContentEntity) (new ContentResourceFileSystem(edit, "/ERROR:invalid_sakai_mount_point", "/",
                this, contentHostingHandlerResolver, false, false).wrap());
    }
}

From source file:org.sakaiproject.content.chh.jcr.ContentHostingHandlerImplJCR.java

public ContentEntity getVirtualContentEntity(ContentEntity edit, String finalId) {
    // Algorithm: get the mount point from the XML file represented by 'edit'
    // construct a new ContentEntityJCR and return it
    try {/*from  ww w.j a va 2s  .c om*/
        boolean searchable = false; // allow the sakai-search tool to index the virtual hierarchy?
        String username = ""; // credentials for JCR repo
        String password = ""; // credentials for JCR repo
        String virtWorldRoot = "/"; // relative path within the JCR repo that you want to expose

        byte[] xml = ((ContentResource) edit).getContent();
        if (xml == null)
            return null;
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        if (db == null)
            return null;
        Document d = db.parse(new ByteArrayInputStream(xml));
        if (d == null)
            return null;
        Node node_mountpoint = null;
        NodeList nl = d.getChildNodes();
        for (int j = 0; j < nl.getLength(); ++j)
            if (nl.item(j).getNodeName() != null && nl.item(j).getNodeName().equals(XML_NODE_NAME)) {
                node_mountpoint = nl.item(j);
                break;
            }
        if (node_mountpoint == null)
            return null;

        Node node_username = node_mountpoint.getAttributes().getNamedItem(XML_ATTRIBUTE_USERNAME);
        if (node_username == null)
            return null;
        username = node_username.getNodeValue();

        Node node_password = node_mountpoint.getAttributes().getNamedItem(XML_ATTRIBUTE_PASSWORD);
        if (node_password == null)
            return null;
        password = node_password.getNodeValue();

        Node node_vwr = node_mountpoint.getAttributes().getNamedItem(XML_ATTRIBUTE_WORLDROOT);
        if (node_vwr == null)
            return null;
        virtWorldRoot = node_vwr.getNodeValue();

        Node node_basepath = node_mountpoint.getAttributes().getNamedItem(XML_ATTRIBUTE_NAME);
        if (node_basepath == null)
            return null;
        final String basepath = node_basepath.getNodeValue();

        Node node_searchable = node_mountpoint.getAttributes().getNamedItem(XML_ATTRIBUTE_SEARCHABLE);
        if (node_searchable != null)
            searchable = Boolean.parseBoolean(node_searchable.getNodeValue());

        if (basepath == null || basepath.equals(""))
            return null; // invalid mountpoint specification
        String relativePath = finalId.substring(edit.getId().length());
        ContentEntityJCR cejcr = resolveToFileOrDirectory(edit, basepath, relativePath, this, searchable,
                username, password, virtWorldRoot);
        Edit ce = cejcr.wrap();
        if (ce == null)
            return null; // happens when the requested URL requires a log on but the user is not logged on
        return (ContentEntity) ce;
    } catch (Exception e) {
        log.warn("Invalid XML for the mountpoint [" + edit.getId() + "], error is [" + e + "]");
        return (ContentEntity) (new ContentResourceJCR(edit, "/ERROR:invalid_sakai_mount_point", "/", this,
                contentHostingHandlerResolver, false, "", "", "/").wrap());
    }
}

From source file:org.seasar.uruma.eclipath.classpath.EclipseProject.java

private Node getProjectDescriptionNode(Document document) {
    NodeList children = document.getChildNodes();
    int len = children.getLength();
    for (int i = 0; i < len; i++) {
        Node node = children.item(i);
        if ("projectDescription".equals(node.getNodeName())) {
            return node;
        }/*from   w w w . j av a2s .  co m*/
    }
    return null;
}

From source file:org.simbasecurity.core.saml.UtilsTest.java

/**
 * Tests the validateSign method of the com.onelogin.saml.Utils
 *//*from www .  j av a 2  s  .co  m*/
@Test
public void testValidateSign() throws Exception {
    String certificate = "MIICgTCCAeoCCQCbOlrWDdX7FTANBgkqhkiG9w0BAQUFADCBhDELMAkGA1UEBhMCTk8xGDAWBgNVBAgTD0FuZHJlYXM"
            + "gU29sYmVyZzEMMAoGA1UEBxMDRm9vMRAwDgYDVQQKEwdVTklORVRUMRgwFgYDVQQDEw9mZWlkZS5lcmxhbmcubm8xITA"
            + "fBgkqhkiG9w0BCQEWEmFuZHJlYXNAdW5pbmV0dC5ubzAeFw0wNzA2MTUxMjAxMzVaFw0wNzA4MTQxMjAxMzVaMIGEMQs"
            + "wCQYDVQQGEwJOTzEYMBYGA1UECBMPQW5kcmVhcyBTb2xiZXJnMQwwCgYDVQQHEwNGb28xEDAOBgNVBAoTB1VOSU5FVFQ"
            + "xGDAWBgNVBAMTD2ZlaWRlLmVybGFuZy5ubzEhMB8GCSqGSIb3DQEJARYSYW5kcmVhc0B1bmluZXR0Lm5vMIGfMA0GCSq"
            + "GSIb3DQEBAQUAA4GNADCBiQKBgQDivbhR7P516x/S3BqKxupQe0LONoliupiBOesCO3SHbDrl3+q9IbfnfmE04rNuMcP"
            + "sIxB161TdDpIesLCn7c8aPHISKOtPlAeTZSnb8QAu7aRjZq3+PbrP5uW3TcfCGPtKTytHOge/OlJbo078dVhXQ14d1ED"
            + "wXJW1rRXuUt4C8QIDAQABMA0GCSqGSIb3DQEBBQUAA4GBACDVfp86HObqY+e8BUoWQ9+VMQx1ASDohBjwOsg2WykUqRX"
            + "F+dLfcUH9dWR63CtZIKFDbStNomPnQz7nbK+onygwBspVEbnHuUihZq3ZUdmumQqCw4Uvs/1Uvq3orOo/WJVhTyvLgFV"
            + "K2QarQ4/67OZfHd7R+POBXhophSMv1ZOo";
    CertificateFactory fty = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(certificate.getBytes()));
    Certificate cert = fty.generateCertificate(bais);

    String responseCoded = getFile("responses/signed_message_response.xml.base64");
    Base64 base64 = new Base64();
    byte[] decodedB = base64.decode(responseCoded);
    String response = new String(decodedB);
    Document dom = Utils.loadXML(response);

    NodeList signatureResNodes = Utils.query(dom, "/samlp:Response/ds:Signature", null);
    assertThat(signatureResNodes.getLength()).isEqualTo(1);
    assertThat(Utils.validateSign(signatureResNodes.item(0), cert)).isTrue();

    assertThatThrownBy(() -> Utils.validateSign(dom.getChildNodes().item(0), cert))
            .isInstanceOf(MarshalException.class).hasMessageContaining("invalid Signature");

    responseCoded = getFile("responses/invalids/no_key.xml.base64");
    base64 = new Base64();
    decodedB = base64.decode(responseCoded);
    response = new String(decodedB);

    NodeList signatureNoKey = Utils.query(Utils.loadXML(response),
            "/samlp:Response/saml:Assertion/ds:Signature", null);
    assertThat(signatureNoKey.getLength()).isEqualTo(1);

    assertThatThrownBy(() -> Utils.validateSign(signatureNoKey.item(0), cert))
            .isInstanceOf(MarshalException.class);
}

From source file:org.squale.squalix.configurationmanager.ConfigUtility.java

/**
 * Retourne l'lment racine du document XML de configuration.
 * // ww  w  .  j a  va 2  s. co  m
 * @param pFile Fichier de configuration
 * @param pName Nom de la racine.
 * @return Le noeud racine.
 * @throws Exception si un problme apparat.
 * @roseuid 42C925800210
 */
public static Node getRootNode(final String pFile, final String pName) throws Exception {
    LOGGER.debug(Messages.getString("log.configuration.getRootNode"));
    DocumentBuilderFactory dbc = DocumentBuilderFactory.newInstance();
    Node root = null;
    DocumentBuilder db = dbc.newDocumentBuilder();
    // On va utiliser de prfrence un InputStream issu du classpath,
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(pFile);
    if (null == is) {
        // mais si celui-ci n'exista pas, alors on le rcupre du fichier pass en paramtre
        is = new FileInputStream(pFile);
    }
    Document doc = db.parse(is);
    NodeList nl = doc.getChildNodes();
    // A partir de la liste des noeuds enfants du document, on va rechercher
    // celui qui possde le nom attendu
    Node node = null;
    for (int i = 0; i < nl.getLength() && null == root; i++) {
        node = nl.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equalsIgnoreCase(pName)) {
            // Le noeud doit tre un lment, et son nom doit correspondre  celui recherch
            root = node;
        }
    }
    return root;
}

From source file:org.squale.squalix.tools.compiling.java.parser.configuration.JParserUtility.java

/**
 * Retourne l'lment racine du document XML de configuration.
 * //from   w w w  .  j av a  2 s .c  om
 * @param pFile Fichier de configuration
 * @param pName Nom de la racine.
 * @return Le noeud racine.
 * @throws Exception si un problme apparat.
 */
public static Node getRootNode(final String pFile, final String pName) throws Exception {
    LOGGER.debug(CompilingMessages.getString("logs.configuration.getRootNode"));
    /* cration du Document */
    DocumentBuilderFactory dbc = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbc.newDocumentBuilder();
    File f = new File(pFile);
    Document doc = db.parse(f);

    /* Rcupration de la liste des noeuds */
    NodeList nl = doc.getChildNodes();

    /* instanciation des noeuds */
    Node node = null;
    Node root = null;

    /*
     * tant qu'il y aura des noeuds ds la liste, et que l'on a pas trouv le noeud racine dsir
     */
    for (int i = 0; i < nl.getLength() && null == root; i++) {
        /* rcupration du i-me noeud */
        node = nl.item(i);
        /* si l'on trouve le noeud recherch */
        if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equalsIgnoreCase(pName)) {
            /* alors on le stocke */
            root = node;
        }
    }
    return root;
}

From source file:org.vulpe.commons.xml.XMLReader.java

public List<XMLAttribute> reader(final String xml) {
    final List<XMLAttribute> attributeList = new ArrayList<XMLAttribute>();
    if (StringUtils.isNotEmpty(xml)) {
        try {// w  w  w  .j a va  2s  .co m
            final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            final ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("utf-8"));
            final Document document = docBuilder.parse(bais);
            final Node entity = document.getChildNodes().item(0);
            final NodeList atributos = entity.getChildNodes();
            for (int i = 0; i < atributos.getLength(); i++) {
                final String attribute = atributos.item(i).getNodeName();
                if (!"#text".equals(attribute)) {
                    final String value = getChildTagValue((Element) entity, attribute);
                    attributeList.add(new XMLAttribute(attribute, value));
                }
            }
        } catch (SAXParseException err) {
            LOG.error("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
            LOG.error(" " + err.getMessage());
        } catch (SAXException e) {
            final Exception exception = e.getException();
            LOG.error(((exception == null) ? e.getMessage() : exception.getMessage()));
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
    }
    return attributeList;
}

From source file:org.wso2.carbon.governance.taxonomy.util.TaxonomyCategoryParser.java

/***
 * This method is use to populate the paths from XML document
 *
 * @return List of Strings//w ww  .j a va 2s .  c  om
 */
public static JSONObject getPathCategories()
        throws RegistryException, JSONException, IOException, SAXException {
    Registry registry = ServiceHolder.getRegistryService().getGovernanceSystemRegistry();
    try {
        DocumentBuilderFactory factory = getSecuredDocumentBuilder();
        Document doc = null;
        if (Utils.getTaxonomyService() == null) {
            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(registry.get(INPUT_XML).getContentStream());

            TaxonomyStorageService ins = new TaxonomyStorageService();
            ins.addParseDocument(doc);
            Utils.setTaxonomyService(ins);
        } else {
            doc = Utils.getTaxonomyService().getParsedDocument();
        }

        NodeList childNodes = doc.getChildNodes();
        loopNodes(childNodes);

    } catch (ParserConfigurationException e) {
        log.error("Error occur while parsing the xml document ", e);
    }

    return jsonPaths;
}

From source file:org.xwiki.xar.XarPackage.java

/**
 * Read a XML descriptor of a XAR package (usually names package.xml).
 * /*from   ww  w. j  a  v a2  s  .c  o m*/
 * @param stream the input stream to the XML file to parse
 * @throws XarException when failing to parse the descriptor
 * @throws IOException when failing to read the file
 */
public void readDescriptor(InputStream stream) throws XarException, IOException {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new XarException("Failed to create a new Document builder", e);
    }

    Document doc;
    try {
        // DocumentBuilder#parse close the passed stream which is not what we want
        doc = dBuilder.parse(new CloseShieldInputStream(stream));
    } catch (SAXException e) {
        throw new XarException("Failed to parse XML document", e);
    }

    // Normalize the document
    doc.getDocumentElement().normalize();

    // Read the document
    NodeList children = doc.getChildNodes();
    for (int i = 0; i < children.getLength(); ++i) {
        Node node = children.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            if (element.getTagName().equals(XarModel.ELEMENT_PACKAGE)) {
                readDescriptorPackage(element);
                break;
            }
        }
    }
}