Print system property name if property not found in property file - java

I have 2 property files:
application.properties
config.properties
Both of these fiels contains properties in it.
I am loading properties of these fiels by setting system properties in IBM websphere server.
During application startup all properties in both of these files are loaded through ApplicationProperty.java class.
private static Properties applicationProperties = new Properties();
readPropertyFileOne(...){
properties.load(new FileInputStream(propertiesLocationOne));
}
readPropertyFileTwo(...){
properties.load(new FileInputStream(propertiesLocationTwo));
}
Now after application starts and read all properties in both files. If I tried to access any property in file through this code
findNonNullableProperty(String aPropertyName){
String value = properties.getProperty(aPropertyName);
if(value == null){
//print system property name here. Name can be propertiesLocationOne or propertiesLocationTwo. But what is that? I want to know file location.
}
}
and it return null.

UPDATE: after evaluating your question again I understand this: You want to get a property value form your own property class. If the property value returns null you want to know which property file holds the key and print out the name of the property file.
The answer to this is that you can't do this. If you read the javadoc for the properties class, you fine that the get("KEY_NAME") method return null only if put an unknown key in. For a empty value you get "", an empty string. As the key is not known it can't be in either of your files. You can't decide which file name to print (or you have to print both).
If you want to do this for the empty strings ("") you have to add more information in your own property class. The java.util.Properties class uses a hash map to store the key value pairs. After loading the pairs from the file the name of the file isn't available any longer. So you needs to store the file name somewhere.
Next problem is that you load keys from two files into one hash map. Once inside the table you can't decide from which file they where read. Two possible solutions:
you add the file name to the key: if you do this in the property file itself it's easy, but you then have to know the file name to get the value.
you hold one property for each file: then you have to look into both properties when someone ask fro a value. However this can be wrapped in your Property class, so the user don't know this.

Just get property from System class:
public class PrintPropery {
public static void main(String[] args) {
System.out.println(System.getProperty("app.property"));
}
}

Related

How to write a data into the application.properties file in java

I am working on some automation stuff, in which I just want to write the values into the application.properties file as shown below:
project.ids = 01234, 56789, 14587,...
So here, my key(project.ids) will be the same, I just want to append the ids to the previously stored values (shown above). Whenever my service will be called a new project id will be generated so I just want to append or store the value in the property file to the same key(project.ids).
Could anyone help or suggest here how can I achieve this?
Any suggestions around how to write the value to the application.properties file in Java?
I would suggest to use the Environment class of Spring. But it is only used to read properties and not write them.
what you could do is follow this way:
Load the .properties file:
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("application.properties");
prop.load(in);
Get the value as it is of the property
String ids = prop.getProperty("project.ids");
Set the new value
String ids = prop.setProperty("project.ids", ids + ", 12324...");
PS: I wouldn't play around with the .properties file much, it is mostly used for configurations. Try saving your ids in a DB, Spring can be very helpful for that.

Unable to resolve ${file.separator} programmatically to read property path

I am trying to read a property which contains a file path including logged in user name in path as below.
test.file = ${file.separator}test${file.separator}${user.name}${file.separator}file.txt
I am able to read file with OS specific path (/ - unix or -windows) when I read the property using #Value annotation in a class and when used it in pom.xml as an argument..
When i read this as regular property from property file, spring is reading it as another string value which is expected.
But if i pass this value to File constructor, ${file.separator} doesn't get resolved..
what is the best way to represent file separator in a property file? I want to avoid .replace technique to replace a variable with File.separator in code.
If you are just looking for a file separator which is platform neutral then, we have been using / separator without any problem.
path=C:/Users/<user_name>/myconfig.properties
path=/Users/<user_name>/myconfig.properties
The following code always returns true on both systems.
finput = new File(prop.getProperty("path"));
System.out.println(finput.exists());

How to "unload" a .properties file

in my game i'm loading properties files from a specific level folder with this code:
Properties prop = new Properties
public void LoadLevel(int levelID) {
try {
prop.load(new FileInputStream("/resources/levels" + levelID + "lev.properties"));
....snip....
if I want to load another level, how do I unload the last level's properties file?
I found a solution, but it was blurred as the site was pay only, so I came crawling back here :D
Properties is a Hashtable. You can clear it.
Another alternative is to just create a new Properties object, load it, and assign it to prop. This should work just fine, unless your code has saved the reference to the original object in other places.

How to reference a system property within a user-defined .properties file?

I want to define a property for a working directory(say work.dir=/home/username/working-directory), for my production .properties file, without hard-coding the /home/username.
I want to reference the system property user.home in place on the hard-coded /home/username, to make work.dir more generic.
How do I reference the system property and concatenate it will other user-defined strings in a user-defined .properties?
Note: I don't want to access the user.home property in my java code, but from the .properties that I have defined. I want to be able to replace the value of the work.dir with different value for both my production and development(JUnit tests for example).
Get the property from the file, then replace supported macros.
String propertyValue = System.getProperty("work.dir");
String userHome = System.getProperty("user.home" );
String evaluatedPropertyValue = propertyValue.replace("$user.home", userHome );
You can manage your properties with Commons Configuration and use Variable Interpolation
If you are familiar with Ant or Maven, you have most certainly already encountered the variables (like ${token}) that are automatically expanded when the configuration file is loaded. Commons Configuration supports this feature as well[...]
That would allow a .properties file with
work.dir=${user.home}/working-directory
This feature is not available in java.util.Properties. But many libraries add variable substitution to properties.
Here an example of what you are trying to do using OWNER API library (see paragraph "importing properties"):
public interface SystemPropertiesExample extends Config {
#DefaultValue("Welcome: ${user.name}")
String welcomeString();
#DefaultValue("${TMPDIR}/tempFile.tmp")
File tempFile();
}
SystemPropertiesExample conf =
ConfigFactory.create(SystemPropertiesExample.class, System.getProperties(), System.getenv());
String welcome = conf.welcomeString();
File temp = conf.tempFile();

Need help with making a settings file

I am trying to make an application launcher that has a settings file that will save 'names' for programs and the path to that program, and when you type the name in an input box it will run the program that name is assigned to.
Also if it the name entered is not known by the application (in the settings file) it will ask the user to add the path and will save that name with the user set path in the settings file.
What I need to know is the best way for me to do this and read/write the file, and the easiest way to organize the settings file to be interpreted.
Any suggestions?
You could use java.util.Properties - it stores key/value pairs in a textfile, and is fairly easy to instantiate. e.g:
Properties mySettings = new Properties();
mySettings.load(new FileInputStream("myapp.cfg"));
// getProperty() returns a String
filepath1 = mySettings.getProperty("filePath1");
Then you simply save your settings in myapp.cfg, either directly (it's a simple textfile with key=value pairs), or via mySettings.store(...). The contents of myapp.cfg will look something like this:
# comment and date added by the Properties object
filePath1=/usr/bin/share/filename
otherVar=52

Categories

Resources