ConvertUtil.java
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.myproject.util;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.myproject.model.LabelValue;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
/**
* Utility class to convert one object to another.
*
* @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
*/
public final class ConvertUtil {
private static final Log log = LogFactory.getLog(ConvertUtil.class);
/**
* Checkstyle rule: utility classes should not have public constructor
*/
private ConvertUtil() {
}
/**
* Method to convert a ResourceBundle to a Map object.
*
* @param rb a given resource bundle
* @return Map a populated map
*/
public static Map<String, String> convertBundleToMap(ResourceBundle rb) {
Map<String, String> map = new HashMap<String, String>();
Enumeration<String> keys = rb.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
map.put(key, rb.getString(key));
}
return map;
}
/**
* Convert a java.util.List of LabelValue objects to a LinkedHashMap.
*
* @param list the list to convert
* @return the populated map with the label as the key
*/
public static Map<String, String> convertListToMap(List<LabelValue> list) {
Map<String, String> map = new LinkedHashMap<String, String>();
for (LabelValue option : list) {
map.put(option.getLabel(), option.getValue());
}
return map;
}
/**
* Method to convert a ResourceBundle to a Properties object.
*
* @param rb a given resource bundle
* @return Properties a populated properties object
*/
public static Properties convertBundleToProperties(ResourceBundle rb) {
Properties props = new Properties();
for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
String key = keys.nextElement();
props.put(key, rb.getString(key));
}
return props;
}
/**
* Convenience method used by tests to populate an object from a
* ResourceBundle
*
* @param obj an initialized object
* @param rb a resource bundle
* @return a populated object
*/
public static Object populateObject(Object obj, ResourceBundle rb) {
try {
Map<String, String> map = convertBundleToMap(rb);
BeanUtils.copyProperties(obj, map);
} catch (Exception e) {
e.printStackTrace();
log.error("Exception occurred populating object: " + e.getMessage());
}
return obj;
}
}