Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get file location from bean using getRealPath()

I have a problem with accessing an external file from my back bean. What I would like to do is to use ttf file in order to use the font through iText library. When I run my application via Netbeans 7.2 the code below works fine:

private static String fontPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("arialuni.ttf");

But as I deploy my ear file manually through Oracle Weblogic 11g console, ttf file is not found and I get NullPointerException.

I have tried several ways to get it work but no chance. If someone could help me, I would be greatly appriciated.

Regards

like image 823
Ali Yucel Akgul Avatar asked Jan 22 '14 12:01

Ali Yucel Akgul


2 Answers

The ServletContext#getRealPath() (and inherently thus also its JSF delegator ExternalContext#getRealPath()) will return null when the servletcontainer is configured to expand the deployed WAR in RAM memory space instead of in local disk file system space. "Heavy" servers are known to do that to improve performance. As there's no means of a physical local disk file system path which you could further utilize in File or FileInputStream, null will be returned.

The getRealPath() is absolutely the wrong tool for the purpose of obtaining the file's content. Never ever use getRealPath(). You should be using ServletContext#getResourceAsStream() (or its JSF delegator ExternalContext#getResourceAsStream()) instead.

InputStream content = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/arialuni.ttf");
// ...

Note that you should absolutely not assign the InputStream as a static variable for obvious reasons. If you really need to, read it into a byte[] first so that you can safely close it.

See also:

  • What does servletcontext.getRealPath("/") mean and when should I use it
  • Where to place and how to read configuration resource files in servlet based application?
  • Recommended way to save uploaded files in a servlet application
  • How to save generated file temporarily in servlet based web application
like image 180
BalusC Avatar answered Sep 28 '22 09:09

BalusC


The relative path you pass to FacesContext.getCurrentInstance().getExternalContext().getRealPath() method, must be relative to context path of your FacesServlet.

lets say you have the "arialuni.ttf" in your resources folder in FacesServlet context path, then you should pass "/resources/arialuni.ttf" to the getRealPath() method like below:

FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/arialuni.ttf");

For details see this:

  • ExternalContext#getRealPath()
  • ServletContext#getRealPath()
like image 29
Sazzadur Rahaman Avatar answered Sep 28 '22 09:09

Sazzadur Rahaman