0

I am using struts2 and have a DAO class in that ,ve one authenticate method where i am getting a query from db.properties file. But my question is how to get query data from xml file in to this method instead of db.properties. Thanks in advance.

AuthenticateUser method

     'Properties properties = new Properties();
                   InputStream inputStream = DBConnection.class.getClassLoader()
                    .getResourceAsStream("db.properties");
           @Override
           /** function authenticateUser 
            *  @return UserBean
            */
           public UserBean authenticateUser(UserBean userBean) throws SQLException,
                NullPointerException {
            // logger.info("connection establishing ");
            // establishing connection
            con = conn.createConnection();
            userBean.setPassword(PasswordUtil.encryptPassword(userBean
                    .getPassword().toString()));
            try {
                properties.load(inputStream);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
            String sql = properties.getProperty("users_signin_query");
            // PreparedStatement is used to execute queries.
            preparedstatement = con.prepareStatement(sql);
            preparedstatement.setString(1, userBean.getUserName());
            preparedstatement.setString(2, userBean.getPassword());
            resultSet = preparedstatement.executeQuery();

            UserBean bean = new UserBean();
            if (resultSet.next()) {
                bean.setIs_admin(resultSet.getString("is_admin"));
                bean.setEmail(resultSet.getString("email"));
                bean.setFirstname(resultSet.getString("first_name"));
                bean.setUserid(resultSet.getString("id"));
                bean.setMobile(resultSet.getString("mobile"));
                bean.setUserName(resultSet.getString("username"));
                bean.setLastname(resultSet.getString("last_name"));
                bean.setPassword(resultSet.getString("password"));
                return bean;
            } else {
                conn.close(con);
                return bean;
            }
           }'

db.properties

jdbc details driver=com.mysql.jdbc.Driver db_url=jdbc:mysql://localhost:3306/app

Database Credentials

db_user_name=root db_password=root users_query=
   insert into users(username,password,email,first_name,last_name,mobile,id)
   values(?,?,?,?,?,?,?)*
Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
user3620383
  • 11
  • 1
  • 4
  • @SunJCarkeY Why do you think OP is using it or is able to use it? And it's very vague, spring DI? – Roman C Jun 19 '14 at 11:06
  • @user3620383 Are you asking to get query from `struts.xml` file or **any** xml file?? I think I misunderstood the question... – prem30488 Jun 20 '14 at 17:45

1 Answers1

0

Alternative 1: Use DOM Parser (Not Recmmanded as it is slow) Copy paste jaxp-api-x.x.x.jar and dom jars in your project.

Use following function in your code

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public String ReadAttributefromXML(String xmlFilepath,String AttributeName) {

try {

File fXmlFile = new File("xmlFilepath");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("jdBCProperties");

for (int temp = 0; temp < nList.getLength(); temp++) {

    Node nNode = nList.item(temp);

    System.out.println("\nCurrent Element :" + nNode.getNodeName());

    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

        Element eElement = (Element) nNode;
                  return(eElement.getElementsByTagName(AttributeName).item(0).getTextContent());
            //or return(eElement.getAttribute(AttributeName)); if your structure is simpler than I mensioned like <jdBCProperties query="....">
    }
}
} catch (Exception e) {
e.printStackTrace();
}

   }

In yourxmlfile.xml

<? xml version="1.0"?>
<Properties>
<Properties>
<jdBCProperties>
        <jdbc_details_driver>com.mysql.jdbc.Driver</jdbc_details_driver>
        <db_url>jdbc:mysql://localhost:3306/app</db_url>
        <db_user_name>root</db_user_name>
     <db_password>root</db_password>
        <users_query>insert into users(username,password,email,first_name,last_name,mobile,id) values(?,?,?,?,?,?,?)*</users_query>
</jdBCProperties>

</Properties>

Use in your code :

 String sql =  ReadAttributefromXML("/yourxmlFileName.xml","users_query");

If I did not understand your question please tell me...

Reference Read this article

Alternative 2: Use SAX Parser (Re-commanded as it is faster than DOM Parser)

Make a package xml.util and Create a calss ReadXML.java in it

Copy and paste below code in class

package xml.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXML {
public String value="";
public String ReadXmlAttribute(String path,final String AtttributeName)
{
    value="";
    SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser saxParser;
    try {
        saxParser = factory.newSAXParser();


      DefaultHandler handler = new DefaultHandler() {

        boolean flag = false;


        public void startElement(String uri, String localName,
            String qName, Attributes attributes)
            throws SAXException {

         // System.out.println("Start Element :" + qName);

          if (qName.equalsIgnoreCase(AtttributeName)) {
              flag = true;
          }

        }

        public void endElement(String uri, String localName,
                String qName)
                throws SAXException {

              //System.out.println("End Element :" + qName);

        }

        public void characters(char ch[], int start, int length)
            throws SAXException {

          //System.out.println(new String(ch, start, length));


          if (flag) {
              value =  new String(ch, start, length);
              System.out.println("Attribute Found : "
                +value);


            flag = false;
          }
        }
      };

    File file = new File(path);
    InputStream inputStream = new FileInputStream(file);

    Reader reader = new InputStreamReader(inputStream,"UTF-8");


    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");

    saxParser.parse(is, handler);

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return value;
}
}    

Use in your code

import xml.util.ReadXML;

 // in your action method
 ReadXML myxml = new ReadXML();
 String sql = myxml.ReadXmlAttribute("c:\\yourxmlfile.xml", "users_query");

Reference SAX Parser Example

prem30488
  • 2,828
  • 2
  • 25
  • 57