Netbeans - GlassFish - Java EE Configuration File - java

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.

Related

Java find the relative path of the configuration file in the war file

I am trying to access the config.properties file which was previously placed in the config folder. after some research, I moved it to the WEB-INF folder. but even after I moved it, it still return java.lang.NullPointerException whenenver I run my my program. code used to store some password information as below:
ClassLoader resource = ConnectionManager.class.getClass().getClassLoader();
URL path = ConnectionManager.class.getClass().getResource("/WEB-INF/config.properties");
props.load(new FileInputStream(path.getFile()));
String passwordds = props.getProperty("datasource.password");
these are the codes that I found and I try to use it but still I got the null exception.
I cannot use absolute path due to this project will be deploy to production server as in .war file. please advise what is the best way as I am still beginner.
You should check the war your build tool generated, and find where your config file really are.
For maven project, the default resource dir is /src/main/resources/
So /src/main/resources/config.properties will be put at /WEB-INF/classes/config.properties in a war.
You can use getClass().getResourceStream("/config.properties") (getResource sometimes not work will in j2ee environment) to get it.

Add properties file when deploying

I am building a web application using IntelliJ 13 Ultimate and a tomcat8 server.
I have a properties file next to my TextUtil class in order to access it with
TextUtil.class.getResource(TEXT_PROPERTY_PATH).getFile()
But when I am starting my server with IntelliJ, by default the file is not being copied (which is quite logical, because it is not part of the compiler output).
I edited the artifact and added the files manually. But by doing this, the file is not being updated on change without restarting the server.
Is there
A) a better place for the properties-file from where I can access it withou having the context-object or
B) a way to leave the file where it is and get it updated on change?
You can add the file in the classpath and use the below code to have the inputstream
For example in ABC.properties or within a folder like properties/ABC.properties
NOTE:
After proper build it should go to the path /WEB-INF/classes//ABC.properties
public class TextUtil {
....................
//For ABC.properties
InputStream inStream1 = TextUtil.getClass()
.getClassLoader().getResourceAsStream("ABC.properties");
//For properties/ABC.properties
InputStream inStream2 = TextUtil.getClass()
.getClassLoader().getResourceAsStream("properties/ABC.properties");
....................
}

Read a file from Tomcat webapps on different Tomcats

Consider the following:
I got a csv-file. This file is stored in the tomcat wepapps directory. The path to this directory is dependent of the computer used. There are users that use different locations for their Tomcats and use different names. I want to achieve the following.
Via Spring i did the following:
I got an action which imports some data from the csv to the database.
<bean id="setCsvPathAction" class="custom.action.importcsv.SetCsvPathAction">
<property name="csvPath" value="C:/temp/test.csv"/>
</bean>
This works fine for me. To make this path more configurable for others i got a system.properties file. With this file you can easily overrite properties:
setCsvPathAction.csvPath=#{tomcat_home}/webapps/test.csv
That is what i want. I want the path to be on the Tomcat webapps directory. The above doesn't work. Do you have any hint how to achieve this?
Most people who use tomcat would have set CATALINA_HOME environment variable. You can query this environment variable and retrieve value.
String tomcat_home = System.getenv("CATALINA_HOME");
if(tomcat_home){
setCsvPathAction.csvPath=tomcat_home+"/webapps/test.csv"
}
Note: There's no guarantee that this environment variable is set on every system using tomcat
More on getenv() - http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getenv%28%29
If it is going to be in the web apps folder you could also just use the class loader to get the local path so you do not have to configure anything.
someObject.getClass().getClassLoader().getResourceAsStream("path/refferenced/to/app/root/");
The solution for the .properties file was: ${catalina.home}
Next i need a FileInputStream independent of the system environment. I tried the following:
public class environmentTest {
public static void main(final String[] args) {
System.out.println(System.getenv("CATALINA_BASE"));
}
}
null gets printed on the console.
The class Person contains the name of the jpg file. This file is located at the webapps folder. I want the path to be independent of the computer used. I tried the following:
File file = new File(System.getenv("CATALINA_HOME") + "/webapps/" + person.getPhoto());
FileInputStream fileInputStream = new FileInputStream(file);
Sadly this doesn't work because, as unekwu said, this environment variable is not set on all systems. Do you have any idea what i can do in this situation?

Load a File in a JSF application

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!

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