Friday, 25 September 2015

Java Config Cacheing



Tags: Java, Config-Cacheing


This Post talks about Reading All Properties Files in a folder/sub-folders into one object then use that object as a glue throughout the project.

Lets say for example the config properties of a project have the following folder Structure.














File Contents
POC/errorMessages.properties
message1=Hey POC, its working
message2=Hey POC, its worked again

POC/screenMessage.properties
message1=Hey POC, its working on the screen
message2=Hey POC, its worked again on the screen

Test/errorMessages.properties
message1=Hey test, its working
message2=Hey test, its worked again


Test/screenMessage.properties
message1=Hey its working on the screen
message2=Hey its worked again on the screen




Output of the sysouts
System.out.println(gcv("POC.errorMessage", "message1"));
-->Hey POC, its working
System.out.println(gcv("POC.screenMessage", "message1"));
-->Hey POC, its working on the screen

System.out.println(gcv("TEST.errorMessage", "message1"));
-->Hey test, its working
System.out.println(gcv("TEST.screenMessage", "message1"));
-->Hey its working on the screen



CODE



ConfigTester.java


import com.company_name.common.configuration.ConfigurationHelper;
public class ConfigTester {
      public static void main(String[] args) {
            try {
                  ConfigurationHelper.init("c:/config");
                  System.out.println(gcv("POC.errorMessage", "message1"));
                  System.out.println(gcv("POC.screenMessage", "message1"));
                  System.out.println(gcv("TEST.errorMessage", "message1"));
                  System.out.println(gcv("TEST.screenMessage", "message1"));
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }
    private static String gvc(String string, String string2) {      
        return ConfigurationHelper.getConfigValue(string, string2);
    }
}


ConfigurationHelper.java


package com.company_name.common.configuration;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public final class ConfigurationHelper {
      private static final String PACKAGE = "package";
      private static final String KEY = "key";
      private static final String VALUE = "value";
      private static HashMap configHashMap = null;
      private static String configRootFolder = null;
      public synchronized static void init(String configFolderPath) throws Exception {
            configRootFolder = (new File(configFolderPath).getCanonicalPath()).toString();
            configHashMap = new HashMap();
            initConfigHashMap(configFolderPath);
      }

      private static void initConfigHashMap(String configFolderPath) throws Exception {
            File rootDirectory = new File(configFolderPath);
            File[] files = rootDirectory.listFiles();
            if (files != null) {
                  for (int k = 0; k < files.length; ++k) {
                        String filePath = files[k].getAbsolutePath();
                        String fileName = files[k].getName();
                        if (files[k].isFile()) {
                              if (fileName.endsWith(".xml")) {
                                    populateConfigHashTable(configHashMap, filePath);
                              } else if (fileName.endsWith(".properties")) {
                                    String packageName = fetchPackageName(filePath);
                                    populateConfigHashTableWithProperties(configHashMap, filePath, packageName);
                              }
                        } else if (files[k].isDirectory()) {
                              initConfigHashMap(filePath);
                        }
                  }
            }
      }

      private static void populateConfigHashTableWithProperties(HashMap configHashMap, String filePath, String packageName) throws Exception {
            ArrayList configItems = new ArrayList();
            Properties properties = new Properties();
            properties.load(new FileInputStream(filePath));
            Enumeration enumeration = properties.keys();
            while (enumeration.hasMoreElements()) {
                  String keyName = (String) enumeration.nextElement();
                  String value = properties.getProperty(keyName);
                  ConfigurationItem theConfigItem = new ConfigurationItem();
                  theConfigItem.setKey(keyName.trim());
                  theConfigItem.setValue(value.trim());
                  configItems.add(theConfigItem);
            }
            ArrayList arrayList = (ArrayList) configHashMap.get(packageName.toLowerCase());
            if (arrayList == null) {
                  configHashMap.put(packageName.toLowerCase(), configItems);
            } else {
                  arrayList.addAll(configItems);
            }
      }

      private static String fetchPackageName(String filePath) {
            String packageName = filePath.replaceFirst("\\.properties", "");
            packageName = packageName.replace(configRootFolder, "");
            packageName = packageName.replace("\\", ".");
            packageName = packageName.substring(1);
            return packageName;
      }

      public static String getConfigValue(String packageName, String key) {
            String configItemValue = null;
            ConfigurationItem[] configItemsArray = getConfigItems(packageName.toLowerCase());
            if (configItemsArray != null) {
                  for (int i = 0; i < configItemsArray.length; ++i) {
                        ConfigurationItem configItem = configItemsArray[i];
                        if (configItem.getKey().compareTo(key) == 0) {
                              configItemValue = configItem.getValue();
                              break;
                        }
                  }
            }
            return configItemValue;
      }

      public static String getConfigValue(String packageName, String key, String locale) {
            String packageNameINT = packageName + "_" + locale;
            String configItemValue = getConfigValue(packageNameINT, key);
            if (configItemValue == null) {
                  configItemValue = getConfigValue(packageName, key);
            }
            return configItemValue;
      }

      private static void populateConfigHashTable(HashMap configHashtable, String fileName) throws Exception {
            Document dom = createDocumentFromFile(fileName);
            NodeList nl = dom.getElementsByTagName(PACKAGE);
            String packageName = null;
            for (int i = 0; i < nl.getLength(); ++i) {
                  Node node = nl.item(i);
                  Node child = node.getFirstChild();

                  if (child != null) {
                        packageName = child.getNodeValue().trim();
                        if (packageName == null)
                              continue;

                  }
                  ArrayList configItems = new ArrayList();
                  getAllValues(configItems, node);
                  ArrayList arrayList = (ArrayList) configHashtable.get(packageName.toLowerCase());
                  if (arrayList == null) {
                        configHashtable.put(packageName.toLowerCase(), configItems);
                  } else {
                        arrayList.addAll(configItems);
                  }
            }
      }

      private static void getAllValues(ArrayList configItems, Node node) {
            NodeList allNodesInThisPackage = node.getChildNodes();
            int j = 0;
            while ((allNodesInThisPackage != null) && (j < allNodesInThisPackage.getLength())) {
                  Node keyValueNode = allNodesInThisPackage.item(j);
                  if (keyValueNode != null) {
                        String nodeName = keyValueNode.getNodeName();
                        if ((nodeName != null) && (nodeName.equals(KEY))) {
                              String keyName = keyValueNode.getFirstChild().getNodeValue();
                              Node ValueNode = findNode(VALUE, keyValueNode.getChildNodes());
                              String tagValue = "";
                              if ((ValueNode != null) && (ValueNode.getFirstChild() != null)) {
                                    tagValue = ValueNode.getFirstChild().getNodeValue();
                              }
                              ConfigurationItem theConfigItem = new ConfigurationItem();
                              if (keyName != null) {
                                    theConfigItem.setKey(keyName.trim());
                              }
                              if (tagValue != null) {
                                    theConfigItem.setValue(tagValue.trim());
                              }
                              configItems.add(theConfigItem);
                        }
                  }
                  ++j;
            }
      }

      private static Node findNode(String tagName, NodeList nodeList) {
            Node foundNode = null;
            if (nodeList != null) {
                  for (int i = 0; i < nodeList.getLength(); i++) {
                        Node node = nodeList.item(i);
                        String nodeName = node.getNodeName();
                        if (nodeName.equals(tagName)) {
                              foundNode = node;
                              break;
                        }
                  }
            }
            return foundNode;
      }

      private static Document createDocumentFromFile(String URL) throws Exception {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document dom = documentBuilder.parse(new File(URL));
            return dom;
      }

      public static ConfigurationItem[] getConfigItems(String packageName) {
            ArrayList arrayList = (ArrayList) configHashMap.get(packageName.toLowerCase());
            if (arrayList == null)
                  return null;
            ConfigurationItem[] configurationItemArray = new ConfigurationItem[arrayList.size()];
            for (int i = arrayList.size() - 1; i >= 0; i--) {
                  configurationItemArray[i] = (ConfigurationItem) arrayList.get(i);
            }
            return configurationItemArray;
      }

      public static void printHashMap() {
            Set setOfKeys = configHashMap.keySet();
            Iterator iterator = setOfKeys.iterator();
            while (iterator.hasNext()) {
                  String packageName = (String) iterator.next();
                  ConfigurationItem[] configurationItems = getConfigItems(packageName);
                  System.out.println("Package:" + packageName);
                  System.out.println("\tKey\tValue");
                  for (ConfigurationItem configurationItem : configurationItems) {
                        System.out.println("\t" + configurationItem.getKey() + "\t" + configurationItem.getValue());
                  }
            }
      }
}
ConfigurationItem.java
package com.company_name.common.configuration;
public class ConfigurationItem {
      private String key;
      private String value;

      public String getKey() {
            return key;
      }
      public void setKey(String key) {
            this.key = key;
      }
      public String getValue() {
            return value;
      }
      public void setValue(String value) {
            this.value = value;
      }
}

No comments:

Post a Comment