/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

/**
 * @author 田平 create 2016年12月30日下午3:00:35
 * 
 *         <pre>
 * local启动的时候，加载Properties的list属性
 * </pre>
 */
public class PropListUtil {

	public static void main(String[] args) {
		Properties props = new Properties();
		props.put("tomcat.servers[0].processName", "accept");
		props.put("tomcat.servers[0].hostAddr", "136.6.177.27");
		props.put("tomcat.servers[0].username", "cqpf");
		props.put("tomcat.servers[0].password", "cqpf");

		props.put("tomcat.servers[1].processName", "audit");
		props.put("tomcat.servers[1].hostAddr", "136.6.177.27");
		props.put("tomcat.servers[1].username", "cqpf");
		props.put("tomcat.servers[1].password", "cqpf");

		List<Map<String, String>> list = getListMap("tomcat.servers", props);
		for (Map<String, String> m : list) {
			System.out.println(m);
		}
	}

	public static List<Map<String, String>> getListMap(String prefix, Properties props) {
		List<Entry<Object, Object>> kv = new ArrayList<Entry<Object, Object>>();
		Set<String> set = new HashSet<String>();
		for (Entry<Object, Object> entry : props.entrySet()) {
			String key = entry.getKey().toString();
			if (key.startsWith(prefix)) {
				kv.add(entry);
				set.add(key.substring(0, key.lastIndexOf(".")));
			}
		}
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();

		for (String k : set) {
			Map<String, String> map = new HashMap<String, String>();
			for (Entry<Object, Object> entry : kv) {
				String key = entry.getKey().toString();
				if (key.startsWith(k)) {
					String originalValue = entry.getValue().toString();
					if (JasyptEncryptorUtil.isEncryptedValue(originalValue)) {
						originalValue = JasyptEncryptorUtil.decrypt(originalValue.substring(JasyptEncryptorUtil.encryptPrefix.length()));
					}
					map.put(key.substring(key.lastIndexOf(".") + 1), originalValue);
				}
			}
			result.add(map);
		}
		return result;
	}
}
