Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Main {
    private static boolean validateMessageXML(Document doc, String xml) {
        NodeList nodeList = null;

        // Check the elements and values exist
        nodeList = doc.getElementsByTagName("message");
        if (nodeList.getLength() != 1) {
            return false;
        }

        // Check that email element exists
        nodeList = doc.getElementsByTagName("content");
        if (nodeList.getLength() != 1) {
            return false;
        }

        // Check that value is not null or empty
        String content = getValue((Element) doc.getElementsByTagName("message").item(0), "content");
        if (content == null || content.isEmpty()) {
            return false;
        }

        // Validate that user is part of the message XML
        return validateUserXML(doc);
    }

    private static String getValue(Element ele, String tagName) {
        String value = null;
        NodeList nl = ele.getElementsByTagName(tagName);
        if (nl != null && nl.getLength() > 0) {
            Element el = (Element) nl.item(0);
            value = el.getFirstChild().getNodeValue();
        }

        return value;
    }

    private static boolean validateUserXML(Document doc) {
        NodeList nodeList = null;

        // Check the elements and values exist
        nodeList = doc.getElementsByTagName("user");
        if (nodeList.getLength() != 1) {
            return false;
        }

        // Check that email element exists
        nodeList = doc.getElementsByTagName("username");
        if (nodeList.getLength() != 1) {
            return false;
        }

        // Check that value is not null or empty
        String username = getValue((Element) doc.getElementsByTagName("user").item(0), "username");
        if (username == null || username.isEmpty()) {
            return false;
        }

        // Check that email element exists
        nodeList = doc.getElementsByTagName("password");
        if (nodeList.getLength() != 1) {
            return false;
        }

        // Check that value is not null or empty
        String password = getValue((Element) doc.getElementsByTagName("user").item(0), "password");
        if (password == null || password.isEmpty()) {
            return false;
        }

        return true;
    }
}