廣告

2016年9月22日 星期四

[java] dynamic key-value set from config.properties


config.properties
terminalID =abStoreA1: 11199942, abStoreWeekend: 11199943, abStoreEP: 11199944


LoadPropertyUtil.java
public class LoadPropertyUtil {

    private static Map mapTerminalID = new HashMap();

    public final static String merchantID = PropertyLoader.getInstance().getValue(Constants.MERCHANT_ID_KEY);

    public final static String authMessageType = PropertyLoader.getInstance().getValue(Constants.AUTH_MESSAGE_TYPE_KEY);
    public final static String authProcessingCode = PropertyLoader.getInstance().getValue(Constants.AUTH_PROCESSING_CODE_KEY);
    public final static String authPosEntryMode = PropertyLoader.getInstance().getValue(Constants.AUTH_POSENTRYMODE_KEY);

    public final static String inquireAuthMessageType = PropertyLoader.getInstance().getValue(Constants.INQUIRE_AUTH_MESSAGE_TYPE_KEY);
    public final static String inquireAuthProcessingCode = PropertyLoader.getInstance().getValue(Constants.INQUIRE_AUTH_PROCESSING_CODE_KEY);
    public final static String inquireAuthPosEntryMode = PropertyLoader.getInstance().getValue(Constants.INQUIRE_AUTH_POSENTRYMODE_KEY);

    static {
      /**
        * split the tid property "srcProject1:TID1,srcProject2:TID2,srcProject3:TID3"
        */
      String[] tIDs = PropertyLoader.getInstance().getValue(Constants.TERMINAlID_KEY).split(",");
      for (String string : tIDs) {
        String[] pair = string.split(":");
        if(pair.length == 2)
            mapTerminalID.put(pair[0].trim(), pair[1].trim());
      }
    }

    public static String getTerminalID(String srcProject) {
      return mapTerminalID.get(srcProject);
    }

    public static boolean containsSrcProjectName(String srcProject) {
      if (srcProject!=null && srcProject.length()>0) {
        return mapTerminalID.containsKey(srcProject);
      }
      return false;
    }
}



PropertyLoader.java
public class PropertyLoader {
  private static PropertyLoader instance = null;
  private Properties props = null;

  /* Singleton Design Pattern */
  private PropertyLoader() {
      try {
        props = new Properties();
        props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.PROPS_FILE_NAME));
      } catch (IOException e) {
        e.printStackTrace();
      }
  }

  public static synchronized PropertyLoader getInstance() {
      if (instance == null)
        instance = new PropertyLoader();
      return instance;
  }

  public String getValue(String propKey) {
      return this.props.getProperty(propKey);
  }
}



using example
LoadPropertyUtil.getTerminalID("abStoreA1")

沒有留言:

張貼留言