0

I have a struts2 and hibernate application. What I intend to do is that if database configuration is invalid, I recieve it from user and modify the hibernate.hbm.xml with updated settings. I am able to check and receive settings from user, only problem is that domparser cannot find my hibernate.cfg.xml.

String filepath = "hibernate.cfg.xml";
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(filepath);

When deploy the application as normal user, I get this

/home/uzumaki/hibernate.cfg.xml (No such file or directory)

and when I run as root,

/hibernate.cfg.xml (No such file or directory)

using File("").getAbsolutePath()) and concatinating with hibernate.cfg.xml also gives me same errors. The file is of course not there, it is in same folder as my java code/class, and goes everywhere with it (example war file)

Varun Garg
  • 1,896
  • 18
  • 33
  • Use `this.getResource("hibernate.cfg.xml")`. In my opinion, allowing the hibernate file to be changed at runtime does not look secure. – Priyesh Jun 22 '15 at 12:18
  • @Priyesh, wordpress, phpbb etc irrespective of their platforms write their datatabse configuration on their own. I just want to do the same, remove hardcoding. – Varun Garg Jun 22 '15 at 17:15

1 Answers1

0

After Searching a lot I finally found a way to get application's realpath during runtime. I am posting this in case anybody needs it.

HttpServletRequest servletRequest = ServletActionContext.getRequest();
String app_path;
app_path = servletRequest.getSession().getServletContext().getRealPath("/");

and now (In My Case)

String filepath =  app_path  + "WEB-INF/classes/hibernate.cfg.xml";
Varun Garg
  • 1,896
  • 18
  • 33
  • 1
    There are 2 major conceptual problems with this approach. 1) The `getRealPath()` will return null when server is configured to expand WAR in memory instead of in disk file system. 2) Any changes in there after deployment will get lost when the WAR is redeployed or sometimes even when the server is restarted, for the very simple reason that those changes are not contained in the original WAR. You might want to revise your approach. See also a.o. http://stackoverflow.com/questions/2161054/where-to-place-and-how-to-read-properties-files-in-a-jsp-servlet-web-application – BalusC Jun 22 '15 at 19:38
  • @BalusC 1)When I copy war, or deploy it from manager, the files are extracted on their own -- the chnages will persist even after it it restarted. 2)Yes changes will be lost if war is redeployed, but redeploying is mostly Done for a fresh start.. – Varun Garg Jun 23 '15 at 05:21