0

I have a DAO which makes use of an xml file as a pseudo-database. This is my DAO Class:

package com.bootcamp.webapps.DAOs;

import java.io.File;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

import com.bootcamp.webapps.beans.DragonBean;
import com.bootcamp.webapps.beans.DragonDatabaseBean;

public class DragonDAO {
    private Logger logger = Logger.getLogger(DragonDAO.class);
    private List<DragonBean> dragonsList;
    private DragonDatabaseBean dragonDatabase;


    public DragonDAO() {
    }


    private void getDragonsFromDatabase()  {
        try {
            File file = new File("dragonDatabase.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(DragonDatabaseBean.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            dragonDatabase = (DragonDatabaseBean) jaxbUnmarshaller.unmarshal(file);
            dragonsList = dragonDatabase.getDragonsList();
            System.out.println("dragonListSize: " + dragonsList.size());
        } catch (JAXBException e) {
            logger.debug("ERROR: " + e.getMessage());
        } catch (Exception e) {
            logger.debug("ERROR: " + e.getMessage());
        } 
    }


    public Logger getLogger() {
        return logger;
    }


    public List<DragonBean> getDragonsList() {
        getDragonsFromDatabase();
        return dragonsList;
    }


}

What's weird is that when I use a main method and make use of getDragonsFromDatabase() method (after adding the static keyword to the necessary places in my code), it seems to work. My log4j just shows this message though:

2016-01-04 11:05:27 DEBUG DragonDAO:34 - ERROR: null
  • 1
    Don't use a `File`. Search for how to read "resources" or "classpath resources". Something should pop up. – Paul Samsotha Jan 04 '16 at 03:13
  • So the File object is the problem then? Does that mean that in web apps I should avoid using that object? –  Jan 04 '16 at 03:17
  • 1
    Pretty much. Put the file at the root of the classpath, and use `DragonDAO.class.getResourceAsStream("/dragonDatabase.xml")`. This will return an `InputStream`. This should work for both the standalone and webapp. You can pass the InputStream to the unmarshall method – Paul Samsotha Jan 04 '16 at 03:19
  • Does this mean I'll be unmarshalling the InputStream object? –  Jan 04 '16 at 03:55
  • 1
    Yup!... _"You can pass the InputStream to the unmarshall method "_ – Paul Samsotha Jan 04 '16 at 03:58

0 Answers0