How to provide property file name dynamically in java - java

Hi I am using two property files. one is for application configuration and another one is for object repository. I am going to use these two properties through out my application. for each and every testcase I am initialising property and access the files using property object. But I want to initialise property in a separate method in separate class.Also I want to call the method in another class and access the property files using that initialised property object. I don't know how to do this. Please give me a hand for this task to be done.Thanks in advance
Below is my code
public class PropertiesExample {
public static void main(String[] args) {
WebDriver driver = null;
String baseUrl;
File file = new File("/home/vaav/workspace/PropertiesExample/config.properties");
Properties prop = new Properties();
FileInputStream fileIO = null;
try{
fileIO = new FileInputStream(file);
prop.load(fileIO);
fileIO.close();
}catch(FileNotFoundException ex){
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.setProperty("webdriver.chrome.driver", "/home/vaav/workspace/PropertiesExample/lib/chromedriver");
driver = new ChromeDriver();
baseUrl = prop.getProperty("URL");
driver.get(baseUrl+"/");
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath(prop.getProperty("Login.btnAdmin"))).click();
driver.findElement(By.id(prop.getProperty("Login.txtUsername"))).sendKeys(prop.getProperty("userName"));
driver.findElement(By.id(prop.getProperty("Login.txtPassword"))).sendKeys(prop.getProperty("password"));
driver.findElement(By.id(prop.getProperty("Login.btnSignIn"))).click();
}
}
I want to do the property related stuff in another file and make reusability of that code

Pick a default filename and location for your property file. E.g. "./config.properties" which would assume the properties file is in the user.dir on startup. Or load the same file from the classpath via the Resource Loader e.g.
final InputStream stream =
this.getClass().getResourceAsStream("config.properties");
properties.load(stream);
But also give the option to override the default location via a System Property. System.
String configLocation = System.getProperties().getProperty("properties.location");
If configLocation is not null, use the user specified location. Otherwise use the default.

You could allow the user to specify it by a command line argument:
String configLocation == "default/location/config.properties"
if(args.length >= 1){
configLocation = args[0];
//You could also test here that the file exists
}

Related

Getting NullPointerException when getting the values from Properties file in Selenium

I am trying to get the properties(key:value pairs) from the properties file but I am getting Null Pointer Exception.
Properties prop;
#BeforeTest
public void beforeTest() throws IOException {
prop=new Properties();
FileInputStream objfile = new FileInputStream(
"\\resources\\config.properties");
prop.load(objfile);
objfile.close();
}
The folder structure is
You should load the properties as a resource, since they are part of your project. No need to use full file system path.
Properties prop = new Properties();
#BeforeTest
public void beforeTest() throws Exception {
try (InputStream in = getClass().getResourceAsStream("/Config.properties") {
prop.load(in);
}
}
Please note that it's not recommended to use the default Java package to avoid classpath clashes. Moving Config.properties to a named package would solve it.
Have you tried to run in debug mode? Seems like your prop object is null. So there is nothing to load to. You need to create your Properties object inside your method. Move the constructor inside the method and then check.
#BeforeTest
public void beforeTest() throws IOException {
Properties prop=new Properties();
FileInputStream objfile = new FileInputStream(
"C:\\Users\\psailaja\\workspace\\TestPropertiesAndKeyword\\Config.properties");
prop.load(objfile);
objfile.close();
}
While trying to get the properties(key:value pairs) from the properties file you are getting Null Pointer Exception. You have to take care of a couple of facts here as follows:
Change the name of the property file from config.properties to config.property
While you take help of project location, use the reference through .
You need to initialize the Properties type of object prop.
Here would be your working code:
Properties prop;
#BeforeTest
public void beforeTest() throws IOException {
File src = new File("./resources/config.property");
FileInputStream fis = new FileInputStream(src);
prop = new Properties();
prop.load(fis);
String propValue = prop.getProperty("propKey");
}
Thanks for the response
The issue is due to not declaring the valid Access Modifier(public static) to the variables that are extracted from the Properties file.
There is no problem in below points
We can declare the properties file without using the resources folder
we can declare the properties file as config.properties or config.property there is no need of any proper name
We can get the file without using the format getClass().getResourceAsStream("/Config.properties") by using FIS

Java Properties Class

using java 8, tomcat 8
Hi, i am loading a file using properties, but i have a check before loading which returns the same properties object if its already been loaded (not null). which is a normal case scenario but i want to know if there is any way that if any change occur in target file, and some trigger should be called and refreshes all the properties objects. here is my code.
public static String loadConnectionFile(String keyname) {
String message = "";
getMessageFromConnectionFile();
if (propertiesForConnection.containsKey(keyname))
message = propertiesForConnection.getProperty(keyname);
return message;
}
public static synchronized void getMessageFromConnectionFile() {
if (propertiesForConnection == null) {
FileInputStream fileInput = null;
try {
File file = new File(Constants.GET_CONNECTION_FILE_PATH);
fileInput = new FileInputStream(file);
Reader reader = new InputStreamReader(fileInput, "UTF-8");
propertiesForConnection = new Properties();
propertiesForConnection.load(reader);
} catch (Exception e) {
Utilities.printErrorLog(Utilities.convertStackTraceToString(e), logger);
} finally {
try {
fileInput.close();
} catch (Exception e) {
Utilities.printErrorLog(Utilities.convertStackTraceToString(e), logger);
}
}
}
}
the loadConnectionFile method executes first and calls getMessageFromConnectionFile which has check implemented for "null", now if we remove that check it will definitely load updated file every time but it will slower the performance. i want an alternate way.
hope i explained my question.
thanks in advance.
Java has a file watcher service. It is an API. You can "listen" for changes in files and directories. So you can listen for changes to your properties file, or the directory in which your properties file is located. The Java Tutorials on Oracle's OTN Web site has a section on the watcher service.
Good Luck,
Avi.

How to load external properties file with Java without rebuilding the Jar?

I use gradle which structures projects in maven style so I have the following
src/main/java/Hello.java and src/main/resources/test.properties
My Hello.java look like this
public class Hello {
public static void main(String[] args) {
Properties configProperties = new Properties();
ClassLoader classLoader = Hello.class.getClassLoader();
try {
configProperties.load(classLoader.getResourceAsStream("test.properties"));
System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?
You can try this one, which will first try to load properties file from project home directory so that you don't have to rebuild jar, if not found then will load from classpath
public class Hello {
public static void main(String[] args) {
String configPath = "test.properties";
if (args.length > 0) {
configPath = args[0];
} else if (System.getenv("CONFIG_TEST") != null) {
configPath = System.getenv("CONFIG_TEST");
}
File file = new File(configPath);
try (InputStream input = file.exists() ? new FileInputStream(file) : Hello.class.getClassLoader().getResourceAsStream(configPath)) {
Properties configProperties = new Properties();
configProperties.load(input);
System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can send the properties file path as argument or set the path to an environment variable name CONFIG_TEST
Archaius may be complete overkill for such a simple problem, but it is a great way to manage external properties. It is a library for handling configuration: hierarchies of configuration, configuration from property files, configuration from databases, configuration from user defined sources. It may seem complicated, but you will never have to worry about hand-rolling a half-broken solution to configuration again. The Getting Started page has a section on using a local file as the configuration source.

Where to keep `java.util.Properties` file and how to access it?

I am adding email sending capability to my web app. SMTP server settings will be read from a java.util.Properties file. I wouldn't like to hardcode path to this file.
Where should I keep this file?
How should I access this file?
A good pattern to follow is to keep your static resources (like property files) under your WEB-INF/classes/ directory.
That way they can be read from the classpath and not accessed by the browser:
for example, put your settings file under WEB-INF/classes/mail-settings.properties, and use the following to read it:
InputStream is = MyClass.class.getResourceAsStream("mail-settings.properties");
Properties p = new Properties();
p.load(is);
is.close();
Keep property file in classpath location like in folder : WEB-INF/classes/mail.properties
Here property file is - mail.properties. To read this file you can use below code
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class EmailPropertyReader {
private static ResourceBundle myResources;
public static String FILENAME = "mail";
static{
initialize(FILENAME);
}
public static void initialize(String propertyFile) throws MissingResourceException
{
try{
myResources = ResourceBundle.getBundle(FILENAME, Locale.getDefault());
}catch(Exception ex){
//Logger
}
}
private static String getParameter(String parmName)
{
String param = null;
try
{
param = myResources.getString(parmName) ;
}catch(Exception e){
param = null;
//Logger
}
if (param != null)
return param.trim();
else
return param;
}
}
You just create object and enter code here use method getParameter() ->
For example:
mail.properties :
EMAILID=a#a.com
then
String strEmailid=EmailPropertyReader.getParameter("EMAILID");
if you want to keep it with your code you may just as well create the Properties instance programmatically.
Properties mailProperties = new Properties();
mailProperties.setProperty("mail.transport.protocol", "smtp");
mailProperties.setProperty("mail.smtp.host", "localhost");
mailProperties.setProperty("mail.smtp.port", "587");
mailProperties.setProperty("mail.smtp.auth", "false");
javax.mail.Session.getInstance(mailProperties);
If you want to have it in a properties file anyway you can load it as a classpath resource. Have a look at getResourceAsStream in java.lang.Class. Update: see epochs answer for how to do this!
Here is a solution:
I have placed EmailSettings.properties file into WebContent\WEB-INF\classes. This code now works:
InputStream inputFile = this.getClass().getClassLoader().getResourceAsStream("EmailSettings.properties");
Properties emailConfig = new Properties();
emailConfig.load( inputFile );
.
.
.
If the settings are stage dependent ,you could set the path to the File via a vm Enviorment varibable.
-DmyPropertyFilePath=....
Also there is a good artikel about loading property files (even so it is a bit Dated) on Java World

How to read a properties file in Java? [duplicate]

This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 7 years ago.
I am using servlets where I hard-code the database connection details, so if make any change I have to recompile the code. So instead I'd like to use a .properties file (which I can modify later) and use that as the source for my database connection.
The problem is I don't know how to read the property file. Could someone please help me to read the file?
. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();
// create application properties with default
Properties applicationProps = new Properties(defaultProps);
// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .
Example is coming from here Properties (Java)
The methods of Properties can throw exceptions.
- When the file path is not valid (FileNotFoundException). Please try to create a File object and check, whether the File is existing.
- ...
You may take a look at Apache Commons Configuration. Using it you can read properties file like that:
Configuration config = new PropertiesConfiguration("user.properties");
String connectionUrl = config.getString("connection.url");
This information regarding file location may be also important:
If you do not specify an absolute
path, the file will be searched
automatically in the following
locations:
in the current directory
in the user home directory
in the classpath
So in case of reading properties file in a servlet you should put properties file in a classpath (e.g. in WEB-INF/classes).
You can find more examples at their website.
You can use java.util.Properties
The biggest problem in reading a property file in web application is that you actually don't know about the actaul path of the file. So we have to use the relative path and for that we have to use various functions and classes like getresourceAsStream(), InputStream, FileinputStream etc.
And the method getReourceAsStream behaves differently in static and non static methogs..
you can do this in below way
Non Static
InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties");
Static
InputStream input = ReadPropertyFile.class.getClassLoader().getResourceAsStream("config.properties");
For complete reference you can follow these links..
http://www.codingeek.com/java/using-getresourceasstream-in-static-method-reading-property-files
http://www.codingeek.com/java/read-and-write-properties-file-in-java-examples/
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
Properties p = new Properties();
p.load(in);
in.close();
The below code, will add a Listener which checks for file configured with dbprops system property. For every given interval it will look if the file is modified, if it is modified it will load the Properties from the file.
package com.servlets;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class DBPropsWatcherListener
implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext();
Timer timer = new Timer("ResourceListener");
timer.schedule(new MyWatcherTask(servletContext), 15);
}
public void contextDestroyed(ServletContextEvent event)
{
}
private class MyWatcherTask extends TimerTask
{
private final ServletContext servletContext;
private long lastModifiedTime = -1;
public MyWatcherTask(ServletContext servletContext)
{
this.servletContext = servletContext;
}
public void run()
{
try {
File resourceFile = new File(System.getProperty("dbProps"));
long current = resourceFile.lastModified();
if (current > lastModifiedTime) {
java.io.InputStream dbPropsStream = new FileInputStream(resourceFile );
java.util.Properties dbProps = new java.util.Properites();
dbProps.load(dbPropsStream);
realoadDBProps();
}
lastModifiedTime = current;
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
Below program read the properties file a display using key value pair
File f1 = new File("abcd.properties");
FileReader fin = new FileReader(f1);
Properties pr = new Properties();
pr.load(fin);
Set<String> keys = pr.stringPropertyNames();
Iterator<String> it = keys.iterator();
String key, value;
while (it.hasNext())
{
key = it.next();
value = pr.getProperty(key);
System.out.println(key+":"+value);
}
}
If your application is small enough with only a handful of properties coming from just one or two property files, then I would suggest to use the JDK's own Properties class which load the properties from a file and use it just like the way you use a hashtable. Properties class itself inherits from Hashtable. But, your application is significantly large with sizable number of properties coming from different sources like property files, xml files, system properties then I would suggest to use Apache commons configuration. It presents a unified view of properties from across different configuration sources and allows you to define an override and preference mechanism for common properties appearing in different sources. Refer this article http://wilddiary.com/reading-property-file-java-using-apache-commons-configuration/ for a quick tutorial on using the commons configuration.
This may work::
Properties prop = new Properties();
FileReader fr = new FileReader(filename);
prop.load(fr);
Set<String> keys = pr.stringPropertyNames();
//now u can get the values from keys.
The Properties class has a convenient load method. That's the easiest way to read a java properties file.
That is a good idea to read the database values from properties file
You can use a properties class from Util package. The important thing to keep in mind is closing the stream after reading the file or writing the file to disk. Otherwise it causes problems. Here is an example for your reference:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class App
{
public static void main( String[] args )
{
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output
localhost
mkyong
password
ResourceBundle rb = ResourceBundle.getBundle("mybundle");
String propertyValue = rb.getString("key");
assuming mybundle.properties file is in classpath
Read this.Usually the properties file is kept in the classpath so that this method can read it.

Categories