View Javadoc

1   package net.sourceforge.argval.utils.impl;
2   
3   
4   import java.io.File;
5   import java.io.FileInputStream;
6   import java.io.IOException;
7   import java.util.ArrayList;
8   import java.util.Enumeration;
9   import java.util.HashMap;
10  import java.util.Iterator;
11  import java.util.List;
12  import java.util.Map;
13  import java.util.Properties;
14  import java.util.Set;
15  import java.util.TreeSet;
16  
17  import net.sourceforge.argval.collection.CollectionUtil;
18  import net.sourceforge.argval.collection.CollectionUtilConfig;
19  import net.sourceforge.argval.collection.CollectionUtilConfigFactory;
20  import net.sourceforge.argval.utils.PropertiesUtil;
21  import net.sourceforge.argval.utils.StringUtil;
22  
23  
24  /**
25   * Utility class for the <code>Properties</code> class.
26   * 
27   * @author $Author: verha001 $
28   * @version $Revision: 1.2 $
29   * Last modified: $Date: 2006/11/16 11:23:02 $
30   */
31  public class PropertiesUtilImpl implements PropertiesUtil {
32      private final static CollectionUtilConfig keyConfig;
33      
34  
35      static {
36          CollectionUtilConfigFactory collFactory = new CollectionUtilConfigFactory();
37          keyConfig = collFactory.getConfig(CollectionUtilConfigFactory.CONFIG_PROPERTY_KEY_SEPARATOR);
38      }
39  
40      
41      /* (non-Javadoc)
42       * @see net.sourceforge.argval.utils.impl.PropertiesUtil#createKey(java.lang.String, java.lang.String)
43       */
44      public String createKey(String key, String keyPart) {
45          return key + PROP_SEP + keyPart;
46      }
47  
48  
49      /* (non-Javadoc)
50       * @see net.sourceforge.argval.utils.impl.PropertiesUtil#createKey(java.lang.String, java.lang.String, java.lang.String)
51       */
52      public String createKey(String key, String firstKeyPart, String secondKeyPart) {
53          return createKey(createKey(key, firstKeyPart), secondKeyPart);
54      }
55  
56  
57      /* (non-Javadoc)
58       * @see net.sourceforge.argval.utils.impl.PropertiesUtil#createKey(java.lang.String[])
59       */
60      public String createKey(String keyArray[]) {
61          // TODO polish keyArray check for startWith / endsWith '.' PROP_SEP
62          return CollectionUtil.toString(keyArray, keyConfig);
63      }
64  
65  
66      /* (non-Javadoc)
67       * @see net.sourceforge.argval.utils.impl.PropertiesUtil#loadProperties(java.io.File)
68       */
69      public Properties loadProperties(File propertyFile) {
70          final Properties properties = new Properties();
71          FileInputStream is = null;
72          try {
73              is = new FileInputStream(propertyFile);
74              properties.load(is);
75          }
76          catch (IOException ioe) {
77              throw new RuntimeException("Unable to load properties from file '"
78                      + propertyFile + "'.", ioe);
79          }
80          finally {
81              if (is != null) {
82                  try {
83                      is.close();
84                  }
85                  catch (final Exception e) {
86                      // TODO
87                  }
88              }
89          }
90          return properties;
91      }
92  
93      
94      /* (non-Javadoc)
95       * @see net.sourceforge.argval.utils.impl.PropertiesUtil#getPropertyAsSet(java.util.Properties, java.lang.String)
96       */
97      public Set<String> getPropertyAsSet(Properties properties, String key) {
98          return getPropertyAsSet(properties, key, null);
99      }
100     /* (non-Javadoc)
101      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#getPropertyAsSet(java.util.Properties, java.lang.String, java.lang.String)
102      */
103     public Set<String> getPropertyAsSet(Properties properties, String key, String separator) {
104     	return StringUtil.convertToSet(properties.getProperty(key), separator);
105 //        Set<String> valueSet = new TreeSet<String>();
106 //        if (properties.getProperty(key) != null) {
107 //            StringTokenizer tokenizer = (separator == null) 
108 //                    ? new StringTokenizer(properties.getProperty(key))
109 //                    : new StringTokenizer(properties.getProperty(key), separator);
110 //            while (tokenizer.hasMoreTokens()) {
111 //                valueSet.add(tokenizer.nextToken());
112 //            }
113 //        }
114 //        return valueSet;
115     }
116 
117     public List<String> getPropertyAsList(Properties properties, String key) {
118         return getPropertyAsList(properties, key, null);
119     }
120     public List<String> getPropertyAsList(Properties properties, String key, String separator) {
121     	return StringUtil.convertToList(properties.getProperty(key), separator);
122     }
123 
124     
125     /* (non-Javadoc)
126      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#toString(java.util.Properties)
127      */
128     public String toString(Properties properties) {
129         StringBuffer strBuf = new StringBuffer();
130         for (Iterator<String> iter = new TreeSet<String>(convert(properties.keySet())).iterator(); iter.hasNext(); ) {
131             Object key = iter.next();
132             strBuf.append(key).append(" = ").append(properties.get(key)).append(StringUtil.LINE_SEPARATOR);
133         }
134         return strBuf.toString();
135     }
136 
137 
138     /* (non-Javadoc)
139      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#getProperties(java.lang.String, java.util.Properties)
140      */
141     public Properties getProperties(String baseKey, Properties prop) {
142         Properties newProp = new Properties();
143         if (! baseKey.endsWith(PROP_SEP)) {
144             baseKey += PROP_SEP;
145         }
146         Enumeration<?> propertyNames = prop.propertyNames();
147         List<String> fullKeyList = new ArrayList<String>();
148         while (propertyNames.hasMoreElements()) {
149             fullKeyList.add(propertyNames.nextElement().toString());
150         }
151         
152         for (Iterator<?> iter = fullKeyList.iterator(); iter.hasNext();) {
153             String key = (String) iter.next();
154             if (key.startsWith(baseKey)) {
155                 String newKey = StringUtil.polish(key.substring(baseKey.length()));
156                 if (newKey != null) {
157                     newProp.setProperty(newKey, prop.getProperty(key));
158                 }
159             }
160         }
161         return newProp;
162     }
163 
164 
165     /* (non-Javadoc)
166      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#getProperties(java.lang.Class, java.util.Properties)
167      */
168     public Properties getProperties(Class<?> clazz, Properties prop) {
169     	return getProperties(clazz.getName(), prop);
170     }
171 
172 
173     /* (non-Javadoc)
174      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#addProperties(java.util.Properties, java.lang.String, java.util.Properties)
175      */
176     public Properties addProperties(Properties prop, String baseKey, Properties extraProp) {
177         for (Iterator<?> iter = extraProp.keySet().iterator(); iter.hasNext();) {
178             String key = (String) iter.next();
179             prop.setProperty(createKey(baseKey, key), extraProp.getProperty(key));
180         }
181         return prop;
182     }
183 
184 
185     /* (non-Javadoc)
186      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#addProperties(java.util.Properties, java.lang.Class, java.util.Properties)
187      */
188     public Properties addProperties(Properties prop, Class<?> clazz, Properties extraProp) {
189     	return addProperties(prop, clazz.getName(), extraProp);
190     }
191 
192 
193 	/* (non-Javadoc)
194      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#getPropertiesList(java.util.Properties, java.lang.String)
195      */
196 	public List<Properties> getPropertiesList(Properties prop, String listPrefixKey) {
197 		if (listPrefixKey == null || "".equals(listPrefixKey)) {
198 			throw new IllegalArgumentException("Argument 'listKey' can not be null.");
199 		}
200 		return getPropertiesList(prop, listPrefixKey, "[", "]");
201 	}
202 	
203 	
204 	/* (non-Javadoc)
205      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#getPropertiesList(java.util.Properties, java.lang.String, java.lang.String, java.lang.String)
206      */
207 	public List<Properties> getPropertiesList(Properties prop, String listPrefixKey, String openingBracket, String closingBracket) {
208 		Map<String, Properties> propMap = getPropertiesMap(prop, listPrefixKey, openingBracket, closingBracket);
209 		
210 		Map<Integer, String> indexMap = new HashMap<Integer, String>();
211 		int maxIndex = -1;
212 //		boolean isZeroIndexAvailable = false; 
213 		for (Iterator<String> iter = propMap.keySet().iterator(); iter.hasNext(); ) {
214 			String indexNumberStr = (String) iter.next();
215 			try {
216 				int index = Integer.parseInt(indexNumberStr);
217 				if (index == 0) {
218 //					isZeroIndexAvailable = true;
219 				}
220 				if (index > maxIndex) {
221 					maxIndex = index;
222 				}
223 				indexMap.put(new Integer(index), indexNumberStr);
224 			}
225 			catch (NumberFormatException nfe) {
226 			}
227 		}
228 		
229 //		if (isZeroIndexAvailable) {
230 //			maxIndex += 1;
231 //		}
232 		System.out.println("maxIndex " + maxIndex);
233 		
234 		List<Properties> propList = new ArrayList<Properties>();
235 		for (int index = 0; index <= maxIndex; index++) {
236 			if (! indexMap.keySet().contains(new Integer(index))) {
237 //				System.out.println("map index " + index + " contains nothing");
238 				propList.add(new Properties());
239 			}
240 			else {
241 //				System.out.println("map index " + index + " contains properties");
242 				propList.add(propMap.get(indexMap.get(new Integer(index))));
243 			}
244 		}
245 		
246 		
247 //		((ArrayList)propList).ensureCapacity(maxIndex + 1);
248 //		System.out.println("propList capacity: " + propList.size());
249 //		for (Iterator iter = propMap.keySet().iterator(); iter.hasNext(); ) {
250 //			String indexNumberStr = (String) iter.next();
251 //			try {
252 //				int index = Integer.parseInt(indexNumberStr);
253 //				System.out.println("Will add index # " + index + " to the list.");
254 //				try {
255 //					Thread.sleep(2000);
256 //				} catch (InterruptedException e) {
257 //					// TODO Auto-generated catch block
258 //					e.printStackTrace();
259 //				}
260 //				propList.add(index, propMap.get(indexNumberStr));
261 //			}
262 //			catch (NumberFormatException nfe) {
263 //			}
264 //		}
265 		
266 		return propList;
267 	}
268 	
269 	
270 	/* (non-Javadoc)
271      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#getPropertiesMap(java.util.Properties, java.lang.String)
272      */
273 	public Map<String, Properties> getPropertiesMap(Properties prop, String mapPrefixKey) {
274 		if (mapPrefixKey == null || "".equals(mapPrefixKey)) {
275 			throw new IllegalArgumentException("Argument 'mapKey' can not be null.");
276 		}
277 		return getPropertiesMap(prop, mapPrefixKey, "[", "]");
278 	}
279 	
280 	
281 	/* (non-Javadoc)
282      * @see net.sourceforge.argval.utils.impl.PropertiesUtil#getPropertiesMap(java.util.Properties, java.lang.String, java.lang.String, java.lang.String)
283      */
284 	public Map<String, Properties> getPropertiesMap(Properties prop, String mapPrefixKey, String openingBracket, String closingBracket) {
285 		if (mapPrefixKey == null || "".equals(mapPrefixKey)) {
286 			throw new IllegalArgumentException("Argument 'listKey' can not be null.");
287 		}
288 		
289 		Map<String, Properties> propMap = new HashMap<String, Properties>();
290 		Enumeration<?> enumeration = prop.propertyNames();
291 		while (enumeration.hasMoreElements()) {
292 			String key = (String) enumeration.nextElement();
293 			if (key.startsWith(mapPrefixKey)) {
294 				String xxx = key.substring(mapPrefixKey.length());
295 				int openingBracketIndex = xxx.indexOf(openingBracket);
296 				int closingBracketIndex = xxx.indexOf(closingBracket);
297 //				System.out.println("The 'list' sub key '" + xxx 
298 //						+ "'  '" + openingBracket + "' @ " + openingBracketIndex
299 //						+ "  '" + closingBracket + "' @ " + closingBracketIndex);
300 				if (openingBracketIndex == 0 && closingBracketIndex > 0 
301 						&& Character.valueOf(xxx.charAt(closingBracketIndex + 1)).equals('.')) {
302 					String indexNumberStr = xxx.substring(openingBracketIndex + 1, closingBracketIndex);
303 					
304 					if (! propMap.containsKey(indexNumberStr)) {
305 						try {
306 							//Integer.parseInt(indexNumberStr);
307 							Properties ppp = getProperties(mapPrefixKey + openingBracket + indexNumberStr + closingBracket, prop);
308 //							System.out.println("Properties '" + indexNumberStr + "' \n" + toString(ppp) + "\n");
309 							
310 							propMap.put(indexNumberStr, ppp);
311 						}
312 						catch (NumberFormatException nfe) {
313 							// TODO: handle exception
314 							System.out.println(nfe);
315 						}
316 					}
317 				}
318 			}
319 			
320 		}
321 		return propMap;
322 	}
323 
324 
325     private static Set<String> convert(Set<Object> originalSet) {
326         final Set<String> newSet = new TreeSet<String>();
327         for (Object object : originalSet) {
328             newSet.add(object.toString());
329         }
330         return newSet;
331     }
332 
333 }