How do I utilize a config file with my Java program? - java

I'm trying to use a config file that holds a list of hosts/websites and a time frequency for each one.
ex.
google.com 15s
yahoo.com 10s
My objective is to ping each website from the config file at every time period (15 secs).
Should I just read the config file and input the hosts/time into separate arrays?
Seems like there is a more efficient method...

Why use two arrays when the two items are so intimately related?
I'd put them into a Map:
Map<String, Integer> pingUrlTimes = new HashMap<String, Integer>();
pingUrlTimes.put("google.com", 15);
pingUrlTimes.put("yahoo.com", 10);
int pingTime = pingUrlTimes.get("google.com");

Here is a quick rundown of how to use a properties file.
You can create a file with the extension .properties (if under Windows make sure you have file extensions displayed) in the root of your project. The properties can be defined as pairs:
google.com=15
yahoo.com=10
In Java,
To get the ping time of a particular URL:
final String path = "config.properties";
Properties prop = new Properties();
int pingTimeGoogle = prop.load(new FileInputStream(path)).getProperty("google.com");
To cycle through the properties and get the whole list:
final String path = "config.properties";
Properties props = new Properties().load(new FileInputStream(path));
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + "=" + props.getProperty(key));
}
Edit: And here's a handy way to transform properties into a Map (Properties implements the Map interface):
final String path = "config.properties";
Properties props = new Properties().load(new FileInputStream(path));
Map<String, Integer> pingUrlTimes = new HashMap<String, Integer>((Map) props);
Cycling through the HashMap can be done like this:
Iterator iterator = pingUrlTimes.keySet().iterator(); // Get Iterator
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key + "=" + pingUrlTimes.get(key) );
}

Related

Problem in writing special characters to a properties file in Java

I need to add key value pairs to a properties file.
All are working fine except # and = everytine a \ is appended before the characters.
Please share me any suggestion.
current properties file data
paper = Normalised
I want to comment this key
#paper = Normalised
but what is happening is \ is getting added
\#paper = Normalised
'''
String valueOfKey = updatedMap.get(key);
updatedMap.remove(key);
updatedMap.put("#" + key, valueOfKey);
String totalPath = propertiesService.getFilePath(request) + "\\" + propertiesModel.getSelectedFile();
propertiesService.updatePropertyfile(updatedMap, request, totalPath);
'''
'''
public boolean updatePropertyfile(Map<String, String> map, HttpServletRequest request, String fileName) {
Properties props = new Properties();
Writer Out = null;
File file = new File(fileName);
try {
FileOutputStream out = new FileOutputStream(file);
Out = new BufferedWriter(new OutputStreamWriter(out));
Set<String> keyset = map.keySet();
Iterator iter = keyset.iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
props.setProperty(key, (String) map.get(key));
}
props.store(Out, "update");
Out.flush();
Out.close();
} catch (IOException e) {
return false;
}
return true;
}
'''
Value in property file getting written
\#paper = Normalised
The hash tag is the lead-in for a comment in Java Properties files:
# Created by generator on 2020-05-01
#current properties file data
paper = Normalised
#want to update like
#paper = Normalised – but this is a comment …
#but what is happening is \# is getting added
\#paper = Normalised # Backslash required …
So the escape with the backslash is the only way to get it working.
Unfortunately, when you need to read the Properties file with another API than java.util.Properties, you have to add this capability to your parser.

How to store specific Key-Value Pairs from properties file

I want to store the key values pair in java from the config.properties file. Problem is it has some other which in dont want to store in array or hashmap.Below is my config.properties file. One thing the line must start with #usergroup and end of line should be End_TT_Executive as described in the file
#Usergroup
TT_Executive
#Tilename
KPI
#No of Submenu=3
#Submenu_1
OPs_KPI=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Submenu_2
Ontime_OnBudget=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_3
Ops_KPI_Cloud=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
Alerting Dashboard
#No of submenu=0
Alerting_Dashboard=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
FTE_Dashboard
#No of submenu=3
#Submenu_1
FTE_Market_Sector_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_2
FTE_Account_TT_Executive= http://tntanalytics1.sl1430087.sl.dst.ibm.com/ibmcognos/bi/?pathRef=.public_folders%2FP=false
#Submenu_3
FTE_Laborpool_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
PCR
#No of Submenu=0
PCR=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
End_TT_Executive
How can I do this? The key value pair are with URL only rest is some title for understanding.
Suppose your config.properties is like:
p1=abc
p2=def
p3=zxc
p4=eva
and you want to load p1 and p2 to map.
You can load all properties into Properties instance with:
InputStream inputStream = null;
try
{
inputStream = new BufferedInputStream(new FileInputStream("config.properties"));
Properties properties = new Properties();
properties.load(new InputStreamReader(inputStream, "UTF-8")); // load all properties in config.properties file
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
inputStream.close();
}
Then you create a map:
Map<String, String> propertyMap = new HashMap<>();
You also need a String[] to store all properties which you want to load to propertyMap.
String[] wantedProperties = new String[]{"p1", "p2"};
Then you write a for loop to load the properties you wanted:
for (String property : wantedProperties) {
propertyMap.put(property, properties.getProperty(property));
}
Now propertyMap is what you want.
If you want to store to List:
List<String> propertyList = new ArrayList<>();
for (String property : wantedProperties) {
propertyList.add(properties.getProperty(property));
}
This is the way to save to list. It'll help you more if you find the solution yourself.

Read and write arrayList of Objects by using HashMap

I want to write and read 'HashMap' to file.
My 'HashMap' is:
Map<String, ArrayList<Descipline>> mapDis = new HashMap<String, ArrayList<Descipline>>();
and I write to file like this:
String root = Environment.getExternalStorageDirectory().toString();
Properties properties = new Properties();
for (Map.Entry<String, ArrayList<Descipline>> entry : mapDis.entrySet()){
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream(root + "/myMap.txt"), null);
But I don't know how to read it.
Map<String, ArrayList<Descipline>> load = new HashMap<String, ArrayList<Descipline>>();
Properties properties1 = new Properties();
properties1.load(new FileInputStream(root + "/myMap.txt"));
for (String key : properties1.stringPropertyNames()){
//something will be here to read file
}
You're already loaded the file. Within the loop you're reading the file (i.e. the map) entries so just use again the put method
It's simple really: java.util.Properties is a subclass of java.util.HashTable, which implements java.util.Map, just like java.util.HashMap does. So you can iterate using entrySet like you do when saving, giving you both the key and value.
Note however that Properties saving and loading expects both the key and value to be String (a .properties file is a simplified 'ini' file), so you might want to look into java.io.Serializable instead.

How to read and write a HashMap to a file?

I have the following HashMap:
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
I write it to a file as follows:
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.
In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).
Thanks,
You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.
public static void main(String... args)
throws IOException, ClassNotFoundException {
HashMap<String, Object> fileObj = new HashMap<String, Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist", cols);
{
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
}
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
s.close();
Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
Assert.assertEquals(fileObj.toString(), fileObj2.toString());
Assert.assertTrue(fileObj.equals(fileObj2));
}
I believe you´re making a common mistake. You forgot to close the stream after using it!
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
you can also use JSON file to read and write MAP object.
To write map object into JSON file
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Suson");
map.put("age", 26);
// write JSON to a file
mapper.writeValue(new File("c:\\myData.json"), map);
To read map object from JSON file
ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map = mapper.readValue(
new File("c:\\myData.json"),
new TypeReference<Map<String, Object>>() {
});
System.out.println(map.get("name"));
System.out.println(map.get("age"));
and import ObjectMapper from com.fasterxml.jackson and put code in try catch block
Your first line:
HashMap<String,Object> fileObj = new HashMap<String,Object>();
gave me pause, as the values are not guaranteed to be Serializable and thus may not be written out correctly. You should really define the object as a HashMap<String, Serializable> (or if you prefer, simpy Map<String, Serializable>).
I would also consider serializing the Map in a simple text format such as JSON since you are doing a simple String -> List<String> mapping.
I believe you're getting what you're saving. Have you inspected the map before you save it? In HashMap:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
e.g. the default HashMap will start off with 16 nulls. You use one of the buckets, so you only have 15 nulls left when you save, which is what you get when you load.
Try inspecting fileObj.keySet(), .entrySet() or .values() to see what you expect.
HashMaps are designed to be fast while trading off memory. See Wikipedia's Hash table entry for more details.
Same data if you want to write to a text file
public void writeToFile(Map<String, List<String>> failureMessage){
if(file!=null){
try{
BufferedWriter writer=new BufferedWriter(new FileWriter(file, true));
for (Map.Entry<String, List<String>> map : failureMessage.entrySet()) {
writer.write(map.getKey()+"\n");
for(String message:map.getValue()){
writer.write(message+"\n");
}
writer.write("\n");
}
writer.close();
}catch (Exception e){
System.out.println("Unable to write to file: "+file.getPath());
e.printStackTrace();
}
}
}

Direct way to convert org.apache.commons.configuration.Configuration to java.util.Properties

I am able to convert org.apache.commons.configuration.Configuration to java.util.Properties using:
Properties props = new Properties();
Configuration config = new PropertiesConfiguration(fileName);
Iterator iter = config.getKeys();
while (iter.hasNext()) {
String key = (String) iter.next();
String value = config.getString(key);
props.put(key, value);
}
Assumption: keys and values are of String type.
Is there any direct way to convert Configuration to Properties?
ConfigurationConverter should do the job .
It has those two methods to convert in both directions :
Configuration getConfiguration(Properties props)
Convert a standard Properties class into a configuration class
and
Properties getProperties(Configuration config)
Convert a Configuration
class into a Properties class.

Categories