20
May

Read property files and set TestContext

Following code snippet performs following actions:

1. Read all property files in given folder and add them as K,V pair in testContext

Step 1: Create a TestContext class which declares a private Map of String and Object with methods to populate, clear and get map
———————————————————————————————————————————

package com.TestContext.map;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class TestContext {

private Map testContext = new HashMap();

public void put(String K, Object V) {
if (StringUtils.isEmpty(K)) {
String err = “Key can’t be null or empty”;
IllegalArgumentException ex = new IllegalArgumentException(err);
System.out.println(“Exception occurred during context insertion” + ex.getMessage());
throw ex;
} else {
this.testContext.put(K, V);
}
}

public void clear() {
this.testContext.clear();
}

@SuppressWarnings(“unchecked”)
public T get(String K) {
Object obj = this.testContext.get(K);
if (obj == null) {
System.out.println(“No match found .. returning null”);
return null;
} else {
return (T) obj;
}
}

public void remove(String key) {
if (StringUtils.isNotEmpty(key)) {
this.testContext.remove(key);
}

}

}

Step 2: Create an Initializer class, which pass “Path” value to “readMap()”. This iterates over all files in this folder and populates testContext:
—————————————————————————————————————————————-

package com.TestContext.map;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import com.globalContext.TestContext;

public class Initializer {

public static String path = “C:\\SRTemp\\files\\”;
public static TestContext mtafTestContext = new TestContext();

public static void main(String[] args) {

try {
readMap();
} catch (Exception e) {
System.out.println(e.getMessage());
}

mtafTestContext.put(“MyKey”, “MyValue”);
System.out.println(mtafTestContext.get(“a”).toString());
System.out.println(mtafTestContext.get(“MyKey”).toString());

}

public static void readMap() throws Exception {
try {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { BufferedReader reader = new BufferedReader(new FileReader(path + "\\" + listOfFiles[i].getName())); String line; while ((line = reader.readLine()) != null) { String[] arr = line.split("="); mtafTestContext.put(arr[0], arr[1]); } } } } catch (IOException e) { e.printStackTrace(); } } } output: ------- A MyValue