PropertiesHelper.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. package com.dashitech.utils;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.io.PrintStream;
  7. import java.io.PrintWriter;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.util.Collection;
  11. import java.util.Enumeration;
  12. import java.util.InvalidPropertiesFormatException;
  13. import java.util.Map;
  14. import java.util.Properties;
  15. import java.util.Set;
  16. import java.util.Map.Entry;
  17. /**
  18. * Properties的操作的工具类,为Properties提供一个代理增加相关工具方法如
  19. * getRequiredString(),getInt(),getBoolean()等方法
  20. * 并可以通过systemPropertiesMode属性指定是否搜索System.getProperty()及System.getenv()来查找值.
  21. * 默认不搜索系统属性
  22. *
  23. * <pre>
  24. * 使用1:
  25. * public class ConnectionUtils {
  26. * static Properties properties = new Properties();
  27. * // ... do load properties
  28. *
  29. * // delegate to properties
  30. * static PropertiesHelper props = new PropertiesHelper(properties);
  31. * public static Connection getConnection() {
  32. * // use getRequiredProperty()
  33. * DriverManager.getConnection(props.getRequiredString("jdbc.url"));
  34. * }
  35. * }
  36. * 指定是否搜索系统属性:
  37. * new PropertiesHelper(properties,PropertiesHelper.SYSTEM_PROPERTIES_MODE_OVERRIDE)
  38. * </pre>
  39. *
  40. * @author badqiu
  41. */
  42. public class PropertiesHelper {
  43. /**
  44. * 不使用系统属性,这个是默认值
  45. **/
  46. public static final int SYSTEM_PROPERTIES_MODE_NEVER = 0;
  47. /**
  48. * 如果在properties中没有找到属性值,则查找系统属性
  49. */
  50. public static final int SYSTEM_PROPERTIES_MODE_FALLBACK = 1;
  51. /**
  52. * 首先查找系统属性,如果没有找到值,再查找properties,这可以用于系统属性覆盖properties中的值
  53. */
  54. public static final int SYSTEM_PROPERTIES_MODE_OVERRIDE = 2;
  55. private int systemPropertiesMode = SYSTEM_PROPERTIES_MODE_NEVER;
  56. private Properties p;
  57. public PropertiesHelper(Properties p) {
  58. setProperties(p);
  59. }
  60. public PropertiesHelper(Properties p, int systemPropertiesMode) {
  61. setProperties(p);
  62. if (systemPropertiesMode != SYSTEM_PROPERTIES_MODE_NEVER && systemPropertiesMode != SYSTEM_PROPERTIES_MODE_FALLBACK
  63. && systemPropertiesMode != SYSTEM_PROPERTIES_MODE_OVERRIDE) {
  64. throw new IllegalArgumentException("error systemPropertiesMode mode:" + systemPropertiesMode);
  65. }
  66. this.systemPropertiesMode = systemPropertiesMode;
  67. }
  68. public Properties getProperties() {
  69. return p;
  70. }
  71. public void setProperties(Properties props) {
  72. if (props == null)
  73. throw new IllegalArgumentException("properties must be not null");
  74. this.p = props;
  75. }
  76. /**
  77. * 必须存在这个key的值,不然抛 IllegalStateException异常
  78. **/
  79. public String getRequiredProperty(String key) throws IllegalStateException {
  80. String value = getProperty(key);
  81. if (isBlankString(value)) {
  82. throw new IllegalStateException("required property is blank by key=" + key);
  83. }
  84. return value;
  85. }
  86. /**
  87. * 返回null,如果查值的属性值是blank
  88. *
  89. * @param key
  90. * @return
  91. */
  92. public String getNullIfBlank(String key) {
  93. String value = getProperty(key);
  94. if (isBlankString(value)) {
  95. return null;
  96. }
  97. return value;
  98. }
  99. /**
  100. * 返回null,如果查值的属性值是empty
  101. *
  102. * @param key
  103. * @return
  104. */
  105. public String getNullIfEmpty(String key) {
  106. String value = getProperty(key);
  107. if (value == null || "".equals(value)) {
  108. return null;
  109. }
  110. return value;
  111. }
  112. /**
  113. * 尝试从System.getProperty(key)及System.getenv(key)得到值
  114. *
  115. * @return
  116. */
  117. public String getAndTryFromSystem(String key) {
  118. String value = getProperty(key);
  119. if (isBlankString(value)) {
  120. value = getSystemProperty(key);
  121. }
  122. return value;
  123. }
  124. private String getSystemProperty(String key) {
  125. String value;
  126. value = System.getProperty(key);
  127. if (isBlankString(value)) {
  128. value = System.getenv(key);
  129. }
  130. return value;
  131. }
  132. public Integer getInteger(String key) {
  133. String value = getProperty(key);
  134. if (isBlankString(value)) {
  135. return null;
  136. }
  137. return Integer.parseInt(value);
  138. }
  139. public int getInt(String key, int defaultValue) {
  140. String value = getProperty(key);
  141. if (isBlankString(value)) {
  142. return defaultValue;
  143. }
  144. return Integer.parseInt(value);
  145. }
  146. /**
  147. * 必须存在这个key的值,不然抛 IllegalStateException异常
  148. **/
  149. public int getRequiredInt(String key) throws IllegalStateException {
  150. return Integer.parseInt(getRequiredProperty(key));
  151. }
  152. public Long getLong(String key) {
  153. String value = getProperty(key);
  154. if (isBlankString(value)) {
  155. return null;
  156. }
  157. return Long.parseLong(value);
  158. }
  159. public long getLong(String key, long defaultValue) {
  160. String value = getProperty(key);
  161. if (isBlankString(value)) {
  162. return defaultValue;
  163. }
  164. return Long.parseLong(value);
  165. }
  166. /**
  167. * 必须存在这个key的值,不然抛 IllegalStateException异常
  168. **/
  169. public long getRequiredLong(String key) throws IllegalStateException {
  170. return Long.parseLong(getRequiredProperty(key));
  171. }
  172. public Boolean getBoolean(String key) {
  173. String value = getProperty(key);
  174. if (isBlankString(value)) {
  175. return null;
  176. }
  177. return Boolean.parseBoolean(value);
  178. }
  179. public boolean getBoolean(String key, boolean defaultValue) {
  180. String value = getProperty(key);
  181. if (isBlankString(value)) {
  182. return defaultValue;
  183. }
  184. return Boolean.parseBoolean(value);
  185. }
  186. /**
  187. * 必须存在这个key的值,不然抛 IllegalStateException异常
  188. **/
  189. public boolean getRequiredBoolean(String key) throws IllegalStateException {
  190. return Boolean.parseBoolean(getRequiredProperty(key));
  191. }
  192. public Float getFloat(String key) {
  193. String value = getProperty(key);
  194. if (isBlankString(value)) {
  195. return null;
  196. }
  197. return Float.parseFloat(value);
  198. }
  199. public float getFloat(String key, float defaultValue) {
  200. String value = getProperty(key);
  201. if (isBlankString(value)) {
  202. return defaultValue;
  203. }
  204. return Float.parseFloat(value);
  205. }
  206. /**
  207. * 必须存在这个key的值,不然抛 IllegalStateException异常
  208. **/
  209. public float getRequiredFloat(String key) throws IllegalStateException {
  210. return Float.parseFloat(getRequiredProperty(key));
  211. }
  212. public Double getDouble(String key) {
  213. String value = getProperty(key);
  214. if (isBlankString(value)) {
  215. return null;
  216. }
  217. return Double.parseDouble(value);
  218. }
  219. public double getDouble(String key, double defaultValue) {
  220. String value = getProperty(key);
  221. if (isBlankString(value)) {
  222. return defaultValue;
  223. }
  224. return Double.parseDouble(value);
  225. }
  226. /**
  227. * 必须存在这个key的值,不然抛 IllegalStateException异常
  228. **/
  229. public double getRequiredDouble(String key) throws IllegalStateException {
  230. return Double.parseDouble(getRequiredProperty(key));
  231. }
  232. public URL getURL(String key) throws IllegalArgumentException {
  233. try {
  234. return new URL(getProperty(key));
  235. } catch (MalformedURLException e) {
  236. throw new IllegalArgumentException("Property " + key + " must be a valid URL (" + getProperty(key) + ")");
  237. }
  238. }
  239. public Object getClassInstance(String key) throws IllegalArgumentException {
  240. String s = (String) getProperty(key);
  241. if (s == null || "".equals(s.trim())) {
  242. throw new IllegalArgumentException("Property " + key + " must be a valid classname : " + key);
  243. }
  244. try {
  245. return Class.forName(s).newInstance();
  246. } catch (ClassNotFoundException nfe) {
  247. throw new IllegalArgumentException(s + ": invalid class name for key " + key, nfe);
  248. } catch (InstantiationException e) {
  249. throw new IllegalArgumentException(s + ": class could not be reflected " + s, e);
  250. } catch (IllegalAccessException e) {
  251. throw new IllegalArgumentException(s + ": class could not be reflected " + s, e);
  252. }
  253. }
  254. public Object getClassInstance(String key, Object defaultinstance) throws IllegalArgumentException {
  255. return (containsKey(key) ? getClassInstance(key) : defaultinstance);
  256. }
  257. /**
  258. * 将一个property按"逗号,空格,换行符"分隔,并返回一个String[]数组
  259. **/
  260. public String[] getStringArray(String key) {
  261. String v = getProperty(key);
  262. if (v == null) {
  263. return new String[0];
  264. } else {
  265. return org.springframework.util.StringUtils.tokenizeToStringArray(v, ", \t\n\r\f");
  266. }
  267. }
  268. /**
  269. * 将一个property按"逗号,空格,换行符"分隔,并返回一个int[]数组
  270. **/
  271. public int[] getIntArray(String key) {
  272. return toIntArray(getStringArray(key));
  273. }
  274. /**
  275. * 得到以某个前缀开始的所有属性,返回的属性值为移除前缀后的属性值.
  276. *
  277. * @param prefix
  278. * @return
  279. */
  280. public Properties getStartsWithProperties(String prefix) {
  281. if (prefix == null)
  282. throw new IllegalArgumentException("'prefix' must be not null");
  283. Properties props = getProperties();
  284. Properties result = new Properties();
  285. for (Entry<Object, Object> entry : props.entrySet()) {
  286. String key = (String) entry.getKey();
  287. if (key != null && key.startsWith(prefix)) {
  288. result.put(key.substring(prefix.length()), entry.getValue());
  289. }
  290. }
  291. return result;
  292. }
  293. /** setProperty(String key,int value) ... start */
  294. public Object setProperty(String key, int value) {
  295. return setProperty(key, String.valueOf(value));
  296. }
  297. public Object setProperty(String key, long value) {
  298. return setProperty(key, String.valueOf(value));
  299. }
  300. public Object setProperty(String key, float value) {
  301. return setProperty(key, String.valueOf(value));
  302. }
  303. public Object setProperty(String key, double value) {
  304. return setProperty(key, String.valueOf(value));
  305. }
  306. public Object setProperty(String key, boolean value) {
  307. return setProperty(key, String.valueOf(value));
  308. }
  309. /** delegate method start */
  310. public String getProperty(String key, String defaultValue) {
  311. String value = getProperty(key);
  312. if (isBlankString(value)) {
  313. return defaultValue;
  314. }
  315. return value;
  316. }
  317. public String getProperty(String key) {
  318. String propVal = null;
  319. if (systemPropertiesMode == SYSTEM_PROPERTIES_MODE_OVERRIDE) {
  320. propVal = getSystemProperty(key);
  321. }
  322. if (propVal == null) {
  323. propVal = p.getProperty(key);
  324. }
  325. if (propVal == null && systemPropertiesMode == SYSTEM_PROPERTIES_MODE_FALLBACK) {
  326. propVal = getSystemProperty(key);
  327. }
  328. return propVal == null ? null : propVal.trim();
  329. }
  330. public Object setProperty(String key, String value) {
  331. return p.setProperty(key, value);
  332. }
  333. public void clear() {
  334. p.clear();
  335. }
  336. public Set<Entry<Object, Object>> entrySet() {
  337. return p.entrySet();
  338. }
  339. public Enumeration<?> propertyNames() {
  340. return p.propertyNames();
  341. }
  342. public boolean contains(Object value) {
  343. return p.contains(value);
  344. }
  345. public boolean containsKey(Object key) {
  346. return p.containsKey(key);
  347. }
  348. public boolean containsValue(Object value) {
  349. return p.containsValue(value);
  350. }
  351. public Enumeration<Object> elements() {
  352. return p.elements();
  353. }
  354. public Object get(Object key) {
  355. return p.get(key);
  356. }
  357. public boolean isEmpty() {
  358. return p.isEmpty();
  359. }
  360. public Enumeration<Object> keys() {
  361. return p.keys();
  362. }
  363. public Set<Object> keySet() {
  364. return p.keySet();
  365. }
  366. public void list(PrintStream out) {
  367. p.list(out);
  368. }
  369. public void list(PrintWriter out) {
  370. p.list(out);
  371. }
  372. public void load(InputStream inStream) throws IOException {
  373. p.load(inStream);
  374. }
  375. public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException {
  376. p.loadFromXML(in);
  377. }
  378. public Object put(Object key, Object value) {
  379. return p.put(key, value);
  380. }
  381. public void putAll(Map<? extends Object, ? extends Object> t) {
  382. p.putAll(t);
  383. }
  384. public Object remove(Object key) {
  385. return p.remove(key);
  386. }
  387. /** @deprecated */
  388. public void save(OutputStream out, String comments) {
  389. p.save(out, comments);
  390. }
  391. public int size() {
  392. return p.size();
  393. }
  394. public void store(OutputStream out, String comments) throws IOException {
  395. p.store(out, comments);
  396. }
  397. public void storeToXML(OutputStream os, String comment, String encoding) throws IOException {
  398. p.storeToXML(os, comment, encoding);
  399. }
  400. public void storeToXML(OutputStream os, String comment) throws IOException {
  401. p.storeToXML(os, comment);
  402. }
  403. public Collection<Object> values() {
  404. return p.values();
  405. }
  406. public String toString() {
  407. return p.toString();
  408. }
  409. public static Properties restoreFromString(String str) {
  410. if (str == null)
  411. return new Properties();
  412. Properties p = new Properties();
  413. try {
  414. p.load(new ByteArrayInputStream(str.getBytes()));
  415. } catch (IOException e) {
  416. throw new IllegalStateException("restore properties from String occer error. str:" + str, e);
  417. }
  418. return p;
  419. }
  420. private static boolean isBlankString(String value) {
  421. return value == null || "".equals(value.trim());
  422. }
  423. private static int[] toIntArray(String[] array) {
  424. int[] result = new int[array.length];
  425. for (int i = 0; i < array.length; i++) {
  426. result[i] = Integer.parseInt(array[i]);
  427. }
  428. return result;
  429. }
  430. }