Load a File in a JSF application - java

My logic need to load a File that is embedded in the applications .war.
The file is located at the root of the application. It works fine on my machine
because the path is hard coded: File hmmFile = new File("/home/kirill/projetos/biosearchrefinement/pos-en-bio-medpost.HiddenMarkovModel");
but when I deploy it to a server it won`t work because the absolute path is different.
I tried to use ClassLoader but got a null reference and tried to use FacesContext but no success either. I am using glassfish 3 and Mojarra 2.1.6
My project tree looks like this:
In my code I am referencing the file like this:
File hmmFile = new File("/home/kirill/projetos/biosearchrefinement/pos-en-bio-medpost.HiddenMarkovModel");
But this only works when I run the application locally, if I deploy it to a remote server obviously it will stop loading that File. I would like to load this file Relatively to the project`s root folder.
Thanks!

From your vague description, what you need is to use the Class.getResourceAsStream() method.

Solved the problem using getRealPath() from ExternalContext.
ExternalContext ext = FacesContext.getCurrentInstance().getExternalContext();
String resourcesPath = ext.getRealPath("/WEB-INF/resources");
File hmmFile = new File(resourcesPath + "/pos-en-bio-medpost.HiddenMarkovModel");
Worked fine!

Related

How to refer to a file present within src/main/resources folder deployed in a jboss env?

I need to look up for an image present in src/main/resources folder in a web application. Its an Apache CXF SAOP based web application.
We are running it in a jboss env(jboss-eap-6.4)
After building the war, the same is deployed.
However, I am unable to get the correct path to the above file.
Please suggest.
I have tried multiple options.
File logo= new File("src/main/resources/image.jpg");
logo.getAbsolutePath(); // This works great when Junit tested, however breaks with the server.
Neither does this works-
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
contextClassLoader.getResource("image.jpg").getPath();
Since you're using Maven, files from src/main/resources will end up on the classpath automatically.
To load a resource from the classpath, use something like this:
InputStream in = getClass().getResourceAsStream("/image.jpg");
Getting the path to the resource or opening it as a File may not always work though since the file is probably still stored inside a .war file. class.getResource() will therefore return a URL that is recognizable only by the app server's classloader.
This is my file structure within the Maven project:
src/main/resources/
src/main/resources/META-INF
src/main/resources/adir
src/main/resources/adir/afile.json
Finally,this worked for me:
String resourceName = "adir/afile.json";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource(resourceName);
InputStream iStream = resource.openStream();
byte[] contents = iStream.readAllBytes();
System.out.println(new String(contents));
HTH,
Thomas

Netbeans - GlassFish - Java EE Configuration File

Since it was really difficult for me to find an answer to this question I'm gonna post both the question and the answer I found to this problem.
Problem: How to use a configuration file in java while working with Netbeans and deploying into a GlassFish Server?
Main problem is to actually access the file (a lot of trouble with the path in which things as getResource, creating a new File and getting it's absolute path, and many other tricks didn't work).
In this particular case I wanted the file to be in my ejb Project.
Create a configuration File (e.g. "config.properties") in
ProjectName-ejb\src\conf
You will be able to see the file from Netbeans in your project configuration Files:
Insert all the properties you want:
Create an attribute in the class from which you will access the file like this: private final String BAD_WORDS_FILE_NAME = "\META-INF\config.properties";
Once your code is deployed to GlassFIsh, all conf files seem to be deployed to this META-INF folder:
Access Properties using sth like:
private String[] getBadWordsFromFile() throws IOException {
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(BAD_WORDS_FILE_NAME);
Properties properties = new Properties();
properties.load(resourceAsStream);
String badWordsAsString = properties.getProperty(BAD_WORDS_PROPERTY_NAME);
return badWordsAsString.split(BAD_WORDS_SEPARATOR);
}
This was the Solution I found, which worked but was only tested on a local machine... this might get some trouble on Release.

Not able to get files under directory in web application(java)

step1
I am using the following code to get files under scripts directory
File directory = new File("scripts");
File[] dirlist = directory.listFiles();
It is working fine in stand alone application but when i build this application as jar and place it lib folder of another web application it is giving null pointer exception. It was trying to pickup the folder from eclipse source folder location(C:\softwares\eclipse-jee-luna-R-win32\eclipse\scripts). I am trying to solve this from couple of days but no luck. If any help appriciated.
Thanks
You can try with this code
ServletContext application = getServletContext();
String fullPath = application.getRealPath("");
fullPath = fullPath + "/scripts/";
File directory = new File(fullPath);
Eclipse won't be there when you deploy to the production server. You'll have to move or copy the scripts into the webapp, as resources. Then, use ServletContext.getRealPath() to get the real path to "scripts", convert that to a File, and then proceed as per your second line.

Get resource folder in java war file

I'm creating a REST webservice that uses keyczar for encryption. I've generated both public and private keys and placed them under src/main/resources/RSA.
To instantiate the encrypter I need to pass to it the location of the files like Crypter crypterPrivate = new Crypter(PATH_RSA + "/private"); but I'm having problems with the RSA folder location when I deploy the war file.
I've tried some stuff I've googled like InputStream but it is not this case since I don't want to pass any file but the RSA folder location. Also have tried several different folders like /WEB-INF/classes/RSA (it's where is located in war file).
Any tips? Thank you
If keyczar can take a URL for its key location then this.getClass().getResource("/RSA/private") will give you a suitable URL. If it requires a native file path then you'll have to use
ServletContext ctx = // ...
String pathToKey = ctx.getRealPath("/WEB-INF/classes/RSA/private");
Exactly how you get hold of the ServletContext depends on your toolkit. Note that this will only work if the WAR file is expanded on disk when you deploy it, it won't work if the app is running directly from the compressed WAR file.
You can access this file via the classpath.
URL resourceUrl = URL.class.getResource("/WEB-INF/classes/RSA");
File resourceFile = new File(resourceUrl.toURI());
I'm pretty sure the Java version of Keyczar doesn't support this functionality, but I believe someone submitted a small patch in their issue tracker to add it:
http://code.google.com/p/keyczar/issues/detail?id=55
KeyczarClassLoaderReader reader = new KeyczarClassLoaderReader(PATH_RSA + "/private");
Crypter crypterPrivate = new Crypter(reader);

Classpath Resource in Tomcat6 (Works in Jetty)

I'm having trouble with a legacy Web Application that I'm migrating to Maven3.
I need to obtain a file from the Classpath that in the directory structure is located in:
/src/main/resources/com/thinkglish/geoip/GeoIP.dat
When I create the .war file with the Maven build, I can confirm that this .dat file is located (as it should be) in:
WEB-INF/classes/com/thinkglish/geoip/GeoIP.dat
I'm trying two different approaches to get the resource from one of my classes, which implements javax.servlet.Filter:
ClassPathResource resource = new ClassPathResource("com/thinkglish/geoip/GeoIp.dat");
and
URL resource = getClass().getResource("/com/thinkglish/geoip/GeoIp.dat");
If I start the application using Maven's Jetty plugin, that works fine in both ways. However, when I deploy the application in a Tomcat and start the server, the resource cannot be located.
In the first case I get a java.io.FileNotFoundException: class path resource [com/thinkglish/geoip/GeoIp.dat] cannot be resolved to URL because it does not exist and in the second case the resource is null.
A curious thing about all this is that if I use one method or the other trying to obtain another resource from the Classpath (e.g. com/thinkglish/struts/i18n/MessageResources.properties or com/thinkglish/filter/LanguageFilter.class) it works without any problems.
Do you have any guess about this? Is it possible that the .dat extension has anything to do with this?
Edited - More data!
I added a new .properties mock file to the exact same directory in which the .dat file lives:
/src/main/resources/com/thinkglish/geoip/mock.properties
I tried to obtain it in Tomcat6 and it worked!
ClassPathResource resource = new ClassPathResource("com/thinkglish/geoip/mock.properties");
I'm starting to think that I need to do something else configuration-wise to make Tomcat6 accept the .dat file as a Classpath resource.
Thanks in advance!
I might be barking up completely the wrong tree here... but have you checked the capitalisation of GeoIP.dat / GeoIp.dat? Is Tomcat running on a case-sensitive OS?
Following should work:
String classpathLocation = "com/thinkglish/geoip/GeoIp.dat";
URL classpathResource = Thread.currentThread().getContextClassLoader().getResource(classpathLocation);
// Or:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathLocation);

Categories

Resources