Java , XML User Verification Failure - java

I've been trying to make this work for longer than I'd like to say now and just can't figure out why it won't recognize the password,I get a null pointer exception on this line if (userPassword.getTextContent().equals(password)
Here is the method
public class XML {
public static boolean login(String email, String password) {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("data.xml");
Element root = document.getDocumentElement();
NodeList nList = root.getChildNodes();
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element users = (Element) nNode;
if (users.getNodeName().compareTo("users") == 0) {
NodeList userList = users.getChildNodes();
for (int j = 0; j < userList.getLength(); j++) {
Node userNode = userList.item(j);
NodeList AttributeList = userNode.getChildNodes();
Node userPassword = AttributeList.item(1);
Node userEmail = AttributeList.item(0);
if (userPassword.getTextContent().equals(password)
&& userEmail.getTextContent().equals(email)) {
return true;
}
}
}
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
}
return false;
}

Attribute nodes don't have text content but a value. You should use the following construct to retrieve it :
Node userNode = userList.item(j);
String attributeValue = userNode.getAttribute("attributeName")
Alternatively since you already have the attributes Nodes, you could cast them to org.w3c.dom.Attr and use their .getValue() method.

Related

Java XML removeChild not working?

Hello so i've looked this question up alot but I couldn't find a solution that worked. I'm basically trying to remove the "job" node as seen declared in line 7 and removed in line 13. There's 0 runtime errors but the node doesn't get removed.
NodeList rootNodes = xml.getElementsByTagName("jobs");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
NodeList jobsList = rootElement.getElementsByTagName("job");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
if(jobElement.getAttribute("id").equals(
msgEvent.getMessage().getContentRaw().split(" ")[2]))
{
rootNode.removeChild(job);
msgEvent.getChannel().sendMessage("Removed Job " + jobElement.getAttribute("id") + " (Summary: '" + jobElement.getAttribute("summary") + "')").complete();
}
}
Here's the XML
<?xml version = "1.0"?>
<jobs>
<job payment = "50000" poster="171048434529337344" collect = "asdf" id = "1" summary="asdfd" expires="5/10/18"> </job>
<job payment = "10000" poster="171048434529337344" collect = "asdf" id = "2" summary="asdf" expires="5/10/18"> </job>
</jobs>
since this is too large for comment, Here is my test code and results:
public static void main(String[] args) {
try (InputStream is = Files.newInputStream(Paths.get("C://Temp/xx.xml"))) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document xml = builder.parse(new InputSource(is));
NodeList rootNodes = xml.getElementsByTagName("jobs");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
NodeList jobsList = rootElement.getElementsByTagName("job");
System.out.println("list before removal");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
System.out.println(jobElement.getAttribute("id"));
}
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
if (jobElement.getAttribute("id").equals("1")) {
rootNode.removeChild(job);
}
}
System.out.println("list after removal");
jobsList = rootElement.getElementsByTagName("job");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
System.out.println(jobElement.getAttribute("id"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
output:
list before removal
1
2
list after removal
2

How can get node child tag from xml with dom (Java)

Took a long time searching and watching videos.
I'm trying to access the course subjects ID
This is my xml code
<list>
<Asignatura>
<id>1</id>
<nombre>Programación</nombre>
<curso>
<id>1</id>
<nombre>1º DAM</nombre>
<listaAsignaturas>
<Asignatura reference="../../.."/>
<Asignatura>
<id>2</id>
<nombre>Bases de datos</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
<Asignatura>
<id>3</id>
<nombre>Formación y orientación laboral</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
<Asignatura>
<id>4</id>
<nombre>Entornos de desarrollo</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
</listaAsignaturas>
</curso>
<listaAlumnos/>
</Asignatura>
</list>
And here my code in java
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("./datos/Asignaturas.xml");
document.getDocumentElement().normalize();
NodeList Asignatura = document.getElementsByTagName("Asignatura");
for (int i = 0; i < Asignatura.getLength(); i++) {
Node c = Asignatura.item(i);
if (c.getNodeType() == Node.ELEMENT_NODE) {
Element elemento = (Element) c;
int id = Integer.parseInt(getValorHijo("id", elemento));
String nombre = getValorHijo("nombre", elemento);
//int idCurso = Integer.parseInt(getValorHijo("curso", elemento));
curso = new Curso();
curso.setId(idCurso);
curso = (Curso) FileXMLDAOFactory.getInstance().getCursoDAO().buscar(curso);
}
}
} catch (Exception e) {
e.printStackTrace();
}
I have to say it works, pick up the ID and name of the subject.
But I can not pick up the ID or name of the course subject that is within.
Im not have idea how can get it :(
I tried a slighty different approach with the same xml input file with the following code.
public static void main(String[] args) {
List<Assignatura> assignaturas = new ArrayList<Assignatura>();
List<Curso> cursos = new ArrayList<Curso>();
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse("datos.xml");
DocumentTraversal traversal = (DocumentTraversal) document;
NodeIterator iterator = traversal.createNodeIterator(
document.getDocumentElement(), NodeFilter.SHOW_ALL, new ListAsignaturasFilter(), true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
Element el = (Element) n;
NodeList assignments = el.getElementsByTagName("Asignatura");
for(int i=0; i<assignments.getLength(); i++){
Node currentNode = assignments.item(i);
NodeList childs = currentNode.getChildNodes();
String id = getValorHijo(childs, "id");
String nombre = getValorHijo(childs, "nombre");
if(!id.isEmpty() || !nombre.isEmpty())
assignaturas.add(new Assignatura(id, nombre));
}
}
NodeIterator itCurso = traversal.createNodeIterator(
document.getDocumentElement(), NodeFilter.SHOW_ALL, new CursoFilter(), true);
for (Node n = itCurso.nextNode(); n != null; n = itCurso.nextNode()) {
Element el = (Element) n;
NodeList cursos = el.getChildNodes();
String id = getValorHijo(cursos, "id");
String nombre = getValorHijo(cursos, "nombre");
if(!id.isEmpty() || !nombre.isEmpty())
cursos.add(new Curso(id, nombre));
}
for(Assignatura assignatura : assignaturas){
System.out.println(assignatura);
}
for(Curso curso : cursos){
System.out.println(curso);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private static String getValorHijo(NodeList childs, String data){
String search="";
if(childs.getLength()>0)
for(int j=0; j<childs.getLength(); j++){
if(childs.item(j).getNodeName().equals(data)){
return childs.item(j).getTextContent();
}
}
return search;
}
private static final class ListAsignaturasFilter implements NodeFilter {
public short acceptNode(Node n) {
if (n instanceof Element) {
if (((Element) n).getTagName().equals("listaAsignaturas")) {
return NodeFilter.FILTER_ACCEPT;
}
}
return NodeFilter.FILTER_REJECT;
}
}
private static final class CursoFilter implements NodeFilter {
public short acceptNode(Node n) {
if (n instanceof Element) {
if (((Element) n).getTagName().equals("curso")) {
return NodeFilter.FILTER_ACCEPT;
}
}
return NodeFilter.FILTER_REJECT;
}
}
As you can see I created two lists to memorize "Assignatura" an "Curso" object which are simple POJO with two attributes id and nombre. At the end of the main method I display the content of these lists and I've got the id and nombre information of element "Curso" besides all "Asignatura" elements. Hope this code help you !
Just for the record. The use of DOM was compulsory ? Because, it would have been easier to use JAXB.

DOM - Missing Element in XML Document

The XML file contains Employee (with empID, empName, empCode). In some situation empCode is missing.
<Employee><Detail><empID>1</empID><empName>Abhi</empName><empCode>One</empCode>
</Detail>
<Detail><empID>2</empID><empName>Amit</empName>
</Detail>
</Employee>
I am getting the Null pointer Exception while calling the getTagValue() method for "empCode" as there is no tag available with the name in XML.
Java Code :
try
{
File xmlFile = new File("New.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Detail");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
EmpDetail empInfo = new EmpDetail();
empInfo.SetEmpID(getTagValue("empID", eElement));
empInfo.SetEmpName(getTagValue("empName",eElement));
empInfo.SetEmpCode(getTagValue("empCode",eElement));
DBConnector.SaveinDB(empInfo);
}
}
}
catch (Exception e)
{
System.out.println("Error: ");
e.printStackTrace();
}
}
private static String getTagValue(String sTag, Element eElement)
{
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
if(nValue == null)
return null;
return insertEscapeSequance(nValue.getNodeValue());
}
private static String insertEscapeSequance(String str)
{
String returnstr = "";
String[] strarr = str.split("'");
returnstr = strarr[0];
for(int i=1;i<strarr.length;i++)
{
returnstr = returnstr + "\\'" + strarr[i];
}
return returnstr;
}
Now I want to save the XML data into sql like this :
1 Abhi One
2 Amit null
I tried so many links but not success. Can someone please help me
If this is possible that there is no such value, then simply handle it like that:
if(getTagValue("empCode",eElement) != null){
empInfo.SetEmpCode(getTagValue("empCode",eElement));
}
Regarding to adding them into SQL, do the same check while creating your statement. As SQL NULL type exists
The problem is caused by eElement.getElementsByTagName(sTag).item(0). The statement returns the first node specified by sTag. In the case of empCode, null is returned, and calling getChildNodes() will raise a null pointer exception.
Try:
Node node = eElement.getElementsByTagName(sTag).item(0);
if (node != null) {
Node nValue = node.getChildNodes().item(0);
if (nValue != null) {
return insertEscapeSequance(nValue.getNodeValue());
}
}
return null;

Getting attribute from XML document

I've looked on here for solutions, but I am still having problems getting this attribute from my xml document. I am trying to fetch the "1" from this: <update-comments total="1">
Here the code that I am using to fetch the other values without attributes:
DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
doc = dbBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("update");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String update_type = getValue("update-type", element);
String numLikes = null;
String submittedUrl = null;
String comments = null;
if (update_type.equals("SHAR")) {
String shar_user = null;
String timestamp = null;
String id = null;
String updateKey = null;
String numComments = null;
try {
shar_user = getValue("first-name", element)
+ " " + getValue("last-name", element);
timestamp = getValue("timestamp", element);
id = getValue("id", element);
updateKey = getValue("update-key", element);
profilePictureUrl = getValue("picture-url", element);
numLikes = getValue("num-likes", element);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
private static String getValue(String tag, Element element)
{
NodeList nodes = element.getElementsByTagName(tag).item(0)
.getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
This function will get an attribute value from an element using the same strategy that you used to find an element. (Note, you solution only works if an element actually exists.)
private static String getAttributeValue(String tag, Element element, String attribute)
{
NodeList nodes = element.getElementsByTagName(tag);
//note: you should actually check the list size before asking for item(0)
//because you asked for ElementsByTagName(), you can assume that the node is an Element
Element elem = (Element) nodes.item(0);
return elem.getAttribute(attribute);
}

Java + reading data from XML file

What's wrong in this code? It gives me null everytime. I have no idea how to repair it, because in ordinary Java Application it works.
#WebMethod(operationName = "getColor")
public String getColor(#WebParam(name = "regNr") String regNr) {
String kolor=null;
try {
File fXmlFile = new File("/base.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("person");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nNode;
String id = ""+ getValue("id",element);
if (regNr.equals(id)) {
color = element.getElementsByTagName("color").item(0).getTextContent();
return color;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return color;
}
I think (not sure because I don't know at which point it gives you null) you have to remove the / form the file name to become only base.xml

Categories