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:com.cloud.hypervisor.xenserver.resource.CitrixResourceBase.java

protected Object[] getRRDData(final Connection conn, final int flag) {

    /*//from ww w  . j  av  a 2  s.  c  om
     * Note: 1 => called from host, hence host stats 2 => called from vm,
     * hence vm stats
     */
    Document doc = null;

    try {
        doc = getStatsRawXML(conn, flag == 1 ? true : false);
    } catch (final Exception e1) {
        s_logger.warn("Error whilst collecting raw stats from plugin: ", e1);
        return null;
    }

    if (doc == null) { // stats are null when the host plugin call fails
        // (host down state)
        return null;
    }

    final NodeList firstLevelChildren = doc.getChildNodes();
    final NodeList secondLevelChildren = firstLevelChildren.item(0).getChildNodes();
    final Node metaNode = secondLevelChildren.item(0);
    final Node dataNode = secondLevelChildren.item(1);

    Integer numRows = 0;
    Integer numColumns = 0;
    Node legend = null;
    final NodeList metaNodeChildren = metaNode.getChildNodes();
    for (int i = 0; i < metaNodeChildren.getLength(); i++) {
        final Node n = metaNodeChildren.item(i);
        if (n.getNodeName().equals("rows")) {
            numRows = Integer.valueOf(getXMLNodeValue(n));
        } else if (n.getNodeName().equals("columns")) {
            numColumns = Integer.valueOf(getXMLNodeValue(n));
        } else if (n.getNodeName().equals("legend")) {
            legend = n;
        }
    }

    return new Object[] { numRows, numColumns, legend, dataNode };
}

From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java

protected Object[] getRRDData(Connection conn, int flag) {

    /*//  w  ww . j  a  va  2  s  .c om
     * Note: 1 => called from host, hence host stats 2 => called from vm, hence vm stats
     */
    String stats = "";

    try {
        if (flag == 1) {
            stats = getHostStatsRawXML(conn);
        }
        if (flag == 2) {
            stats = getVmStatsRawXML(conn);
        }
    } catch (Exception e1) {
        s_logger.warn("Error whilst collecting raw stats from plugin: ", e1);
        return null;
    }

    // s_logger.debug("The raw xml stream is:"+stats);
    // s_logger.debug("Length of raw xml is:"+stats.length());

    //stats are null when the host plugin call fails (host down state)
    if (stats == null) {
        return null;
    }

    StringReader statsReader = new StringReader(stats);
    InputSource statsSource = new InputSource(statsReader);

    Document doc = null;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(statsSource);
    } catch (Exception e) {
        s_logger.warn("Exception caught whilst processing the document via document factory:", e);
        return null;
    }

    if (doc == null) {
        s_logger.warn("Null document found after tryinh to parse the stats source");
        return null;
    }

    NodeList firstLevelChildren = doc.getChildNodes();
    NodeList secondLevelChildren = (firstLevelChildren.item(0)).getChildNodes();
    Node metaNode = secondLevelChildren.item(0);
    Node dataNode = secondLevelChildren.item(1);

    Integer numRows = 0;
    Integer numColumns = 0;
    Node legend = null;
    NodeList metaNodeChildren = metaNode.getChildNodes();
    for (int i = 0; i < metaNodeChildren.getLength(); i++) {
        Node n = metaNodeChildren.item(i);
        if (n.getNodeName().equals("rows")) {
            numRows = Integer.valueOf(getXMLNodeValue(n));
        } else if (n.getNodeName().equals("columns")) {
            numColumns = Integer.valueOf(getXMLNodeValue(n));
        } else if (n.getNodeName().equals("legend")) {
            legend = n;
        }
    }

    return new Object[] { numRows, numColumns, legend, dataNode };
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageManagerResource.java

/**
 * Boolean to determine whether the user contained in the AuthToken is
 * authorized to execute the specified service method.
 * /*  w  w w. ja  v a2 s . c o m*/
 * @param serviceMethodName
 *            the name of the service method
 * @param authToken
 *            the AuthToken containing the user name
 * @return true if authorized to run the service method, else false
 */
private boolean isServiceMethodAuthorized(String serviceMethodName, Rule.Permission permission,
        AuthToken authToken) {
    boolean isAuthorized = false;
    NodeList nodeList = null;
    String serviceDocumentStr = ConfigurationListener.getServiceDocument();
    Document document = XmlUtility.xmlStringToDoc(serviceDocumentStr);

    try {
        if (document != null) {
            NodeList documentNodeList = document.getChildNodes();
            Node rootNode = documentNodeList.item(0);
            nodeList = rootNode.getChildNodes();

            if (nodeList != null) {
                int nodeListLength = nodeList.getLength();
                for (int i = 0; i < nodeListLength; i++) {
                    Node childNode = nodeList.item(i);
                    String nodeName = childNode.getNodeName();
                    String nodeValue = childNode.getNodeValue();
                    if (nodeName.contains("service-method")) {
                        Element serviceElement = (Element) nodeList.item(i);
                        NamedNodeMap serviceAttributesList = serviceElement.getAttributes();

                        for (int j = 0; j < serviceAttributesList.getLength(); j++) {
                            Node attributeNode = serviceAttributesList.item(j);
                            nodeName = attributeNode.getNodeName();
                            nodeValue = attributeNode.getNodeValue();
                            if (nodeName.equals("name")) {
                                String name = nodeValue;
                                if (name.equals(serviceMethodName)) {
                                    NodeList accessNodeList = serviceElement.getElementsByTagName("access");
                                    Node accessNode = accessNodeList.item(0);
                                    String accessXML = XmlUtility.nodeToXmlString(accessNode);
                                    AccessMatrix accessMatrix = new AccessMatrix(accessXML);
                                    String principalOwner = "pasta";
                                    isAuthorized = accessMatrix.isAuthorized(authToken, principalOwner,
                                            permission);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            String message = "No service methods were found in the service.xml file";
            throw new IllegalStateException(message);
        }
    } catch (InvalidPermissionException e) {
        throw new IllegalStateException(e);
    }

    return isAuthorized;
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageManagerResource.java

/**
 * <strong>List Service Methods</strong> operation, returning a simple list
 * of web service methods supported by the Data Package Manager web service.
 * //w w w.j av a 2  s  .  c  o m
 * <h4>Requests:</h4>
 * <table border="1" cellspacing="0" cellpadding="3">
 * <tr>
 * <th><b>Message Body</b></th>
 * <th><b>MIME type</b></th>
 * <th><b>Sample Request</b></th>
 * </tr>
 * <tr>
 * <td align=center>none</td>
 * <td align=center>none</td>
 * <td>
 * <code>curl -i -X GET https://pasta.lternet.edu/package/service-methods</code>
 * </td>
 * </tr>
 * <tr>
 * <td align=center>none</td>
 * <td align=center>none</td>
 * <td>
 * <code>curl -i -X GET https://pasta.lternet.edu/package/eml/knb-lter-lno/1?filter=newest</code>
 * </td>
 * </tr>
 * </table>
 *
 * <h4>Responses:</h4>
 * <table border="1" cellspacing="0" cellpadding="3">
 * <tr>
 * <th><b>Status</b></th>
 * <th><b>Reason</b></th>
 * <th><b>Message Body</b></th>
 * <th><b>MIME type</b></th>
 * <th><b>Sample Message Body</b></th>
 * </tr>
 * <tr>
 * <td align=center>200 OK</td>
 * <td align=center>The list request was successful</td>
 * <td align=center>A newline-separated list of revision values matching the
 * specified scope and identifier values</td>
 * <td align=center><code>text/plain</code></td>
 * <td>
 * 
 * <pre>
 * appendProvenance
 * createDataPackage
 * createDataPackageArchive
 * .
 * .
 * . (truncated for brevity)
  * </pre>
 * 
 * </td>
 * </tr>
 * <tr>
 * <td align=center>400 Bad Request</td>
 * <td align=center>The request contains an error, such as an illegal scope
 * or identifier value</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>401 Unauthorized</td>
 * <td align=center>The requesting user is not authorized to access a list
 * of the data package revisions</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>404 Not Found</td>
 * <td align=center>No data package revisions associated with the specified
 * scope and identifier are found</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>405 Method Not Allowed</td>
 * <td align=center>The specified HTTP method is not allowed for the
 * requested resource</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>500 Internal Server Error</td>
 * <td align=center>The server encountered an unexpected condition which
 * prevented it from fulfilling the request</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * </table>
 * 
 * @return a Response, containing a newline-separated list of service
 *         method names supported by the Data Package Manager
 */
@GET
@Path("/service-methods")
@Produces("text/plain")
public Response listServiceMethods(@Context HttpHeaders headers) {
    ResponseBuilder responseBuilder = null;
    Response response = null;
    final String serviceMethodName = "listServiceMethods";
    Rule.Permission permission = Rule.Permission.read;
    AuthToken authToken = null;

    try {
        authToken = getAuthToken(headers);
        String userId = authToken.getUserId();

        // Is user authorized to run the service method?
        boolean serviceMethodAuthorized = isServiceMethodAuthorized(serviceMethodName, permission, authToken);
        if (!serviceMethodAuthorized) {
            throw new UnauthorizedException(
                    "User " + userId + " is not authorized to execute service method " + serviceMethodName);
        }

        String serviceMethods = "";
        StringBuffer stringBuffer = new StringBuffer();
        NodeList nodeList = null;
        String serviceDocumentStr = ConfigurationListener.getServiceDocument();
        Document document = XmlUtility.xmlStringToDoc(serviceDocumentStr);

        if (document != null) {
            NodeList documentNodeList = document.getChildNodes();
            Node rootNode = documentNodeList.item(0);
            nodeList = rootNode.getChildNodes();

            if (nodeList != null) {
                int nodeListLength = nodeList.getLength();
                for (int i = 0; i < nodeListLength; i++) {
                    Node childNode = nodeList.item(i);
                    String nodeName = childNode.getNodeName();
                    String nodeValue = childNode.getNodeValue();
                    if (nodeName.contains("service-method")) {
                        Element serviceElement = (Element) nodeList.item(i);
                        NamedNodeMap serviceAttributesList = serviceElement.getAttributes();

                        for (int j = 0; j < serviceAttributesList.getLength(); j++) {
                            Node attributeNode = serviceAttributesList.item(j);
                            nodeName = attributeNode.getNodeName();
                            nodeValue = attributeNode.getNodeValue();
                            if (nodeName.equals("name")) {
                                String name = nodeValue;
                                stringBuffer.append(String.format("%s\n", name));
                            }
                        }
                    }
                }
            }
        } else {
            String message = "No service methods were found in the service.xml file";
            throw new IllegalStateException(message);
        }

        serviceMethods = stringBuffer.toString();
        responseBuilder = Response.ok(serviceMethods.trim());
        response = responseBuilder.build();
    } catch (IllegalArgumentException e) {
        response = WebExceptionFactory.makeBadRequest(e).getResponse();
    } catch (ResourceNotFoundException e) {
        response = WebExceptionFactory.makeNotFound(e).getResponse();
    } catch (UnauthorizedException e) {
        response = WebExceptionFactory.makeUnauthorized(e).getResponse();
    } catch (UserErrorException e) {
        response = WebResponseFactory.makeBadRequest(e);
    } catch (Exception e) {
        WebApplicationException webApplicationException = WebExceptionFactory
                .make(Response.Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
        response = webApplicationException.getResponse();
    }

    response = stampHeader(response);
    return response;
}

From source file:nl.imvertor.common.file.ZipFile.java

/**
 * Take a serialized folder and deserialize it; pack to the result file path specified.
 * //from   w ww .  j av  a 2  s . c  o m
 * @param serializeFolder
 * @param replace
 * @throws Exception 
 */
public void deserializeFromXml(AnyFolder serializeFolder, boolean replace) throws Exception {
    XmlFile contentFile = new XmlFile(serializeFolder, "__content.xml");
    // test if this is a non-exitsing zip file
    if (exists() && !replace)
        throw new Exception("ZIP file exists: " + getCanonicalPath());
    //get the content file.
    if (!serializeFolder.exists())
        throw new Exception("Serialized folder doesn't exist: " + serializeFolder.getCanonicalPath());
    if (!contentFile.exists())
        throw new Exception("Serialized folder has invalid format");
    // process the XML and recreate the ZIP structure.
    Document dom = contentFile.toDocument();

    List<Node> nodes = getElements(
            getElements(getNodes(dom.getChildNodes()), "zip-content-wrapper:files").get(0).getChildNodes(),
            "zip-content-wrapper:file"); // get all <file> nodes. 
    for (int i = 0; i < nodes.size(); i++) {
        Node filenode = nodes.get(i);
        if (filenode.getNodeType() == Node.ELEMENT_NODE
                && filenode.getNodeName().equals("zip-content-wrapper:file")) {
            String fileType = getAttribute(filenode, "type");
            String filePath = getAttribute(filenode, "path");

            File resultFile = new File(serializeFolder, filePath);

            if (fileType.equals("xml")) {
                // pass the contents of the XML file to the XML file
                List<Node> elms = getElements(filenode.getChildNodes());
                if (elms.size() > 1)
                    throw new Exception("More than one root element found for file: \"" + filePath + "\"");
                Node contentNode = elms.get(0);
                resultFile.getParentFile().mkdirs();
                FileWriter writer = new FileWriter(resultFile);
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.transform(new DOMSource((Node) contentNode), new StreamResult(writer));
                writer.close();

            } else if (fileType.equals("bin")) {
                // already there 
            } else
                throw new Exception("Unknown result file type: \"" + fileType + "\"");
        }
    }
    // done; remove the __content.xml file, pack to result
    contentFile.delete();
    compress(serializeFolder);

    // and remove the work folder.
    //serializeFolder.deleteDirectory();
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Load the types from the input wsdl file.
 *
 * @param inputWSDL file or URL//  ww  w  . j  av a2 s  .co  m
 * @throws IOException
 * @throws WSDLException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public void loadInputTypes(String inputWSDL)
        throws IOException, WSDLException, SAXException, ParserConfigurationException {

    // Read the input wsdl file into a Document
    Document doc = XMLUtils.newDocument(inputWSDL);

    // Search for the 'types' element
    NodeList elements = doc.getChildNodes();

    if ((elements.getLength() > 0) && elements.item(0).getLocalName().equals("definitions")) {
        elements = elements.item(0).getChildNodes();

        for (int i = 0; (i < elements.getLength()) && (wsdlTypesElem == null); i++) {
            Node node = elements.item(i);

            if ((node.getLocalName() != null) && node.getLocalName().equals("types")) {
                wsdlTypesElem = (Element) node;
            }
        }
    }

    // If types element not found, there is no need to continue.
    if (wsdlTypesElem == null) {
        return;
    }

    // Import the types element into the Types docHolder document
    wsdlTypesElem = (Element) docHolder.importNode(wsdlTypesElem, true);

    docHolder.appendChild(wsdlTypesElem);

    // Create a symbol table and populate it with the input wsdl document
    BaseTypeMapping btm = new BaseTypeMapping() {

        public String getBaseName(QName qNameIn) {

            QName qName = new QName(qNameIn.getNamespaceURI(), qNameIn.getLocalPart());
            Class cls = tm.getClassForQName(qName);

            if (cls == null) {
                return null;
            } else {
                return JavaUtils.getTextClassName(cls.getName());
            }
        }
    };
    SymbolTable symbolTable = new SymbolTable(btm, true, false, false);

    symbolTable.populate(null, doc);
    processSymTabEntries(symbolTable);
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerSpringBookTest.java

@Test
public void testGetWadlFromWadlLocation() throws Exception {
    String address = "http://localhost:" + PORT + "/the/generated";
    WebClient client = WebClient.create(address + "/bookstore" + "?_wadl&_type=xml");
    Document doc = StaxUtils.read(new InputStreamReader(client.get(InputStream.class), StandardCharsets.UTF_8));
    List<Element> resources = checkWadlResourcesInfo(doc, address, "/schemas/book.xsd", 2);
    assertEquals("", resources.get(0).getAttribute("type"));
    String type = resources.get(1).getAttribute("type");
    String resourceTypeAddress = address + "/bookstoreImportResourceType.wadl#bookstoreType";
    assertEquals(resourceTypeAddress, type);

    checkSchemas(address, "/schemas/book.xsd", "/schemas/chapter.xsd", "include");
    checkSchemas(address, "/schemas/chapter.xsd", null, null);

    // check resource type resource
    checkWadlResourcesType(address, resourceTypeAddress, "/schemas/book.xsd");

    String templateRef = null;//from   w  ww. ja v  a 2  s.com
    NodeList nd = doc.getChildNodes();
    for (int i = 0; i < nd.getLength(); i++) {
        Node n = nd.item(i);
        if (n.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE) {
            String piData = ((ProcessingInstruction) n).getData();
            int hRefStart = piData.indexOf("href=\"");
            if (hRefStart > 0) {
                int hRefEnd = piData.indexOf("\"", hRefStart + 6);
                templateRef = piData.substring(hRefStart + 6, hRefEnd);
            }
        }
    }
    assertNotNull(templateRef);
    WebClient client2 = WebClient.create(templateRef);
    WebClient.getConfig(client2).getHttpConduit().getClient().setReceiveTimeout(1000000L);
    String template = client2.get(String.class);
    assertNotNull(template);
    assertTrue(template.indexOf("<xsl:stylesheet") != -1);
}

From source file:org.apache.fop.tools.TestConverter.java

/**
 * Run the Tests./* w ww  . j  av  a 2  s  . c o  m*/
 * This runs the tests specified in the xml file fname.
 * The document is read as a dom and each testcase is covered.
 * @param fname filename of the input file
 * @param dest destination directory
 * @param compDir comparison directory
 * @return Map a Map containing differences
 */
public Map runTests(String fname, String dest, String compDir) {
    logger.debug("running tests in file:" + fname);
    try {
        if (compDir != null) {
            compare = new File(baseDir + "/" + compDir);
        }
        destdir = new File(baseDir + "/" + dest);
        destdir.mkdirs();
        File f = new File(baseDir + "/" + fname);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(f);

        NodeList suitelist = doc.getChildNodes();
        if (suitelist.getLength() == 0) {
            return differ;
        }

        Node testsuite = null;
        testsuite = doc.getDocumentElement();

        if (testsuite.hasAttributes()) {
            String profile = testsuite.getAttributes().getNamedItem("profile").getNodeValue();
            logger.debug("testing test suite:" + profile);
        }

        NodeList testcases = testsuite.getChildNodes();
        for (int count = 0; count < testcases.getLength(); count++) {
            Node testcase = testcases.item(count);
            if (testcase.getNodeName().equals("testcases")) {
                runTestCase(testcase);
            }
        }
    } catch (Exception e) {
        logger.error("Error while running tests", e);
    }
    return differ;
}

From source file:org.apache.openaz.xacml.std.dom.DOMRequest.java

/**
 * Unit test program to load an XML file containing a XACML Request document.
 *
 * @param args the list of Request files to load and parse
 *//* w  w  w . j a v a 2  s .  c o  m*/
public static void main(String[] args) {
    if (args.length > 0) {
        for (String xmlFileName : args) {
            File fileXml = new File(xmlFileName);
            if (!fileXml.exists()) {
                System.err.println("Input file \"" + fileXml.getAbsolutePath() + "\" does not exist.");
                continue;
            } else if (!fileXml.canRead()) {
                System.err
                        .println("Permission denied reading input file \"" + fileXml.getAbsolutePath() + "\"");
                continue;
            }
            System.out.println(fileXml.getAbsolutePath() + ":");
            try {
                Document documentRequest = DOMUtil.loadDocument(fileXml);
                assert documentRequest != null;

                NodeList children = documentRequest.getChildNodes();
                if (children == null || children.getLength() == 0) {
                    System.err.println("No Requests found in \"" + fileXml.getAbsolutePath() + "\"");
                    continue;
                } else if (children.getLength() > 1) {
                    System.err.println("Multiple Requests found in \"" + fileXml.getAbsolutePath() + "\"");
                }
                Node nodeRequest = children.item(0);
                if (!nodeRequest.getLocalName().equals(XACML3.ELEMENT_REQUEST)) {
                    System.err.println("\"" + fileXml.getAbsolutePath() + "\" is not a Request");
                    continue;
                }

                Request domRequest = DOMRequest.newInstance(nodeRequest);
                System.out.println(domRequest.toString());
                System.out.println();
            } catch (Exception ex) {
                ex.printStackTrace(System.err);
            }
        }
    }
}

From source file:org.apache.openaz.xacml.std.dom.DOMResponse.java

/**
 * Unit test program to load an XML file containing a XACML Response document.
 *
 * @param args the list of Response files to load and parse
 *//*from   ww w  .  j  a v a2s .co m*/
public static void main(String[] args) {
    if (args.length > 0) {
        for (String xmlFileName : args) {
            File fileXml = new File(xmlFileName);
            if (!fileXml.exists()) {
                System.err.println("Input file \"" + fileXml.getAbsolutePath() + "\" does not exist.");
                continue;
            } else if (!fileXml.canRead()) {
                System.err
                        .println("Permission denied reading input file \"" + fileXml.getAbsolutePath() + "\"");
                continue;
            }
            System.out.println(fileXml.getAbsolutePath() + ":");
            try {
                Document documentResponse = DOMUtil.loadDocument(fileXml);
                assert documentResponse != null;

                NodeList children = documentResponse.getChildNodes();
                if (children == null || children.getLength() == 0) {
                    System.err.println("No Responses found in \"" + fileXml.getAbsolutePath() + "\"");
                    continue;
                } else if (children.getLength() > 1) {
                    System.err.println("Multiple Responses found in \"" + fileXml.getAbsolutePath() + "\"");
                }
                Node nodeResponse = children.item(0);
                if (!nodeResponse.getLocalName().equals(XACML3.ELEMENT_RESPONSE)) {
                    System.err.println("\"" + fileXml.getAbsolutePath() + "\" is not a Response");
                    continue;
                }

                Response domResponse = DOMResponse.newInstance(nodeResponse);
                System.out.println(domResponse.toString());
                System.out.println();
            } catch (Exception ex) {
                ex.printStackTrace(System.err);
            }
        }
    }
}