sâmbătă, 18 aprilie 2015

[OmniFaces utilities (2.0)] Get the absolute disk file system path representation of the given web content path


[OmniFaces utilities] The getRealPath() method returns the absolute disk file system path representation of the given web content path. This thus converts the given path of a web content resource (e.g. /index.xhtml) to an absolute disk file system path (e.g. /path/to/server/work/folder/some.war/index.xhtml) which can then be used in File, FileInputStream, etc.
Note that this will return null when the WAR is not expanded into the disk file system, but instead into memory. If all you want is just an InputStream of the web content resource, then better use #getResourceAsStream(String) instead.
Also note that it wouldn't make sense to modify or create files in this location, as those changes would get lost anyway when the WAR is redeployed or even when the server is restarted. This is thus absolutely not a good location to store for example uploaded files.

Method:
See also: Faces#getContext()
Usage:

For example, let's suppose that we have the following folder structure of an web application:
Now, the demo.xhtml page URL may be something like:

http://localhost:8080/MyApp/faces/user/demo/demo.xhtml

But, for obtaining the absolute disk file system path representation for our demo.xhtml page, we can use the OmniFaces utility method, Faces#getRealPath(), as below:

String onDisk = Faces.getRealPath("/user/pages/demo.xhtml");

A possible output will be:

A:\Applications\UseCase\build\web\user\pages\demo.xhtml

If you simply want to obtain the absolute disk file system path representation of the current view, then use this approach (suppose that index.xhtml is the current view):

String onDisk = Faces.getRealPath(FacesContext.getCurrentInstance().getViewRoot().getViewId());

Or, using one more OmniFaces utilities, we can write this:

String onDisk = Faces.getRealPath(Faces.getViewId());

The result of the above two examples can be:

A:\Applications\UseCase\build\web\index.xhtml


Niciun comentariu:

Trimiteți un comentariu