Accessing properties file in a war - java

I'm trying to access my properties file in a war. The code is working, but when i'm exporting the code into a war and use a POST (with an accepted input) using Fiddler, it cannot find the config.properties. (NullPointerException)
The input and webservice are running correctly. Just trying to figure out a way to edit my properties while using a war.
Some facts:
I've made a RetreivePropertiesClass. This uses:
properties.load(this.getClass()
.getResourceAsStream("/WEB-INF/config.properties"));
My properties file path:
/com.webapp/WebContent/WEB-INF/config.properties
I'm trying to use the properties data in:
String url = RetreiveProperties.getUrl();
String driver = RetreiveProperties.getDriver();
String username = RetreiveProperties.getUsername();
String password = RetreiveProperties.getPassword();
// line below causes the NullPointerException
Class.forName(driver);
Getter used:
public static String getDriver() {
return driver = properties.getProperty("jdbc.driver");
}
When the war is deployed, the properties file is in:
webapps\com.webapp1\WEB-INF\config.properties
Config.properties:
jdbc.url = jdbc:postgresql://127.0.0.1:2222/gisdb
jdbc.driver = org.postgresql.Driver
jdbc.username = postgres
jdbc.password = admin
I already tried to work out the examples given here and here. Keeps giving the NullPointerException because the properties file isn't loaded.
Can anyone push me in the right direction?
Cheers!

If you are going to load the properties file from the classpath, it must be in the WEB-INF/classes directory inside of your war. (Or inside a jar inside of WEB-INF/lib ). The WEB-INF directory itself is not on the classpath.
If you make sure the file ends up as WEB-INF/classes/config.properties your above code should work if you change the getResourceAsStream call to getResourceAsStream("/config.properties")

If the method is a static method, the getClass() method will be failed, and prompts “Cannot make a static reference to the non-static method getClass() from the type Object“.
Instead, you should use CurrentClass.class.getClassLoader().getResourceAsStream.
Source: here

Related

relative path doesn't work when executing jar

i am developping an application where i have to specify the path of a file called dao.properties it works just fine but when i execute the jar using the cmd : java -jar StockManagement.jar i get the error that the file is not found (it works fine in netbeans)
the class and the file are in the same folder.
i've tried a lot of relative paths and nothing works so this is my last hope
here is the code and the hierarchy:
thank y in advance
If your file is in your code base you should use the classLoader to load it.
If I'm not mistaken, the way you're using ClassLoader is it looking for a file path relative to where it is being called.
From the picture, it seems that you're using ClassLoader from the DAOFactory class, is that right? You're declaring the path to your file to be
stock/DAO/dao.properties
If you're calling it from DAOFactory, Java looks for the file in
<where DAOFactory is>/stock/DAO/dao.properties
If DAOFactory and dao.properties reside in the same file I think your file path should just be
dao.properties
So it looks in the same folder that DAOFactory is in.
EDIT: Use DAOFactory class to read in properties file.
Using something like the following code snippet, call this function from the DAOFactory class using just the main method to try to see if you can read the properties file without anything else. Change any classes or names you need to to work on your local machine.
public static String getProperty(String property) {
String value = "";
try (InputStream is = DAOFactory.class.getResourceAsStream("dao.properties")) {
Properties prop = new Properties();
prop.load(is);
value = prop.getProperty(property);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}

Understanding MultipartFile transferTo() method in Spring MVC

I am using Spring Framework's MultipartFile to allow a user to upload a picture to a profile. I've configured DispatcherServlet in a servlet initializer class that extends AbstractAnnotationConfigDispatcherServletInitializer. In that class, I've overridden the customizeRegistration() method as follows:
#Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement("/tmp/practicewellness/uploads", 2097152, 4194304, 0));
}
The MultipartFile's transferTo() method calls for a file location in the filesystem where the uploaded file will be written temporarily. Can this location be anywhere? When I used the following location in the method:
profilePicture.transferTo(new File("tmp/practicewellness/" + employee.getUsername() + ".jpg"));
... I get the following error:
Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [C:\Users\kyle\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\work\Catalina\localhost\practicewellness\tmp\practicewellness\uploads] is not valid
So I can see that it's looking for this file location deep inside one of my Eclipse plugins. I don't understand why it looks there. When I look there, the "tmp" directory is not there. But regardless, is it okay for me to go into that plugin and create the directory there? Or is there a better way to smooth this out?
I've uploaded files using Spring mvc, but never used transferTo(), I just assume that your problem is due to "No existence of specified path" because there wont be a path ending with .jpg. Try it like this.
String path = "/tmp/practicewellness/";
File dirPath = new File(path);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
And then execute the transferTo() code.
Also do not set the path directly like you've done. Since you're doing it in spring, so I assume you want the folder to be in your Project path not the eclipse's metadata path. So change your path to this.
String path = request.getSession().getServletContext().getRealPath("/tmp/practicewellness/");
It will create a folder inside your Project's Webapp folder using mkdir. If you want to save differentiate the files for each user, you can create a folder for each user by using this below path.
String path = request.getSession().getServletContext().getRealPath("/tmp/practicewellness")+"/"+employee.getUsername()+"/";

properties file not found within web application

I am trying to invoke a Method present within a JAR file from my Web Application (A simple Servlet Application). Below is the code that method is using for accessing the properties file:
InputStream inputStream =
ClassLoader.getSystemClassLoader()
.getResourceAsStream("demo.properties");
properties.load(inputStream);
When this method is invoked using my Web Application, I am getting this NullPointerException:
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
Possible reason for this exception is: My Web Application is not able to find the demo.properties file, hence the inputStream is NULL and this exception is thrown.
Please let me know:
How to resolve this exception.
Do I need to place the properties file manually within my Web Based Application? If yes then where exactly where to place this demo.properties file in my Web Application for resolving this exception.
The system class loader only knows about the core Java libraries, for example, those in java.lang., java.util., etc.
You want to load the properties file using the same class loader which looks at that JAR file, which is probably the same class loader that loaded your class.
Try something like this:
public class PropertyFileTest {
public void loadProperties() {
InputStream inputStream = PropertyFileTest.class.getResourceAsStream("/demo.properties");
properties.load(inputStream);
// do something with properties to see if it worked or not.
}
}
Note that I used Class.getResourceAsStream, which will use that class's class loader for you, per:
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
The class loaders interprete the passed string as absolute path, hence as if it were /demo.properties (but never use the heading slash for ClassLoader.getResource). So open the war and look for /WEB-INF/classes/demo.properties. This must be case sensitive.
You might (in general) be interested in alternatives:
MyServletClass.class.getResourceAsStream("/demo.properties") -- better;
ResourceBundle bundle = ResourceBundle.get("demo");
Using Servlet's init parameters in /WEB-INF/web.xml.
ClassLoader does not identified which properties file location.
Use this code:
String path = AbcServiceImpl.class.getClassLoader().getResource("abc.properties").getFile().toString();
path = path.replace("%20", " ");
File f = new File(path);

Get resource(jar) path in java

I have a class XYZ in application that is executed as jar in any directory. I want to find the current directory path in which jar is executing for this I have used following code.
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
I write this code in public constructor of XYZ class but it is not working though I am using it since long time it works fine, but now it is not returning the current directory path.
please mark and suggest what is going wrong in this.
When you execute your statement within "this" - it means that you are trying to locate current instance of the class but you need to find the class itself.
In your case you can use this:
String path = XYZ.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
It will give you the path you are looking for and will solve issues with whitespaces and special characters inside this path.
In case you are doing this for Linux it might be useful to use:
URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(‌​), "UTF-8");
...but now it is not returning the current directory path.
It shouldn't return the current directory path. It should return the path of the jar file the class is coming from, or the root folder where the class files are loaded from (if not packed in a jar). It might and it might not be the current folder.
Calling
this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
will try to locate the path the class of the current instance (this) is coming from.
Make sure that the Class you start from is part of the jar file. E.g. do not use this but use an explicit class which you're sure is from the jar file, e.g.
SomeClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()
Also note that this won't work if you start the application from your IDE in which case the result would be the bin folder (the root folder of compiled class files).
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
OR
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath().toURI());

Reading from src/main/resources gives NullPointerException

In my Maven project, I have a xls file in src/main/resources.
When I read it like this:
InputStream in = new
FileInputStream("src/main/resources/WBU_template.xls");
everything is ok.
However I want to read it as InputStream with getResourceAsStream. When I do this, with or without the slash I always get a NPE.
private static final String TEMPLATEFILE = "/WBU_template.xls";
InputStream in = this.getClass.getResourceAsStream(TEMPLATEFILE);
No matter if the slash is there or not, or if I make use of the getClassLoader() method, I still get a NullPointer.
I also have tried this :
URL u = this.getClass().getResource(TEMPLATEFILE);
System.out.println(u.getPath());
the console says.../target/classes/WBU_template.xls
and then get my NullPointer.
What am I doing wrong ?
FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process.
getResourceAsStream() will load a file path relative from your application's classpath.
When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.
When you use .getClass().getClassLoader().getResource(fileName)
it considers the location of the fileName is the root - in other words bin folder.
The file should be located in src/main/resources when loading using Class loader
In short, you have to use .getClass().getClassLoader().getResource(fileName) to load the file in your case.
I usually load files from WEB-INF like this
session.getServletContext().getResourceAsStream("/WEB-INF/WBU_template.xls")

Categories