Search code examples
jsfnetbeansprimefacesweblogic

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


Solution

  • 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: