1 package com.foxinmy.weixin4j.util;
2
3 import java.util.MissingResourceException;
4 import java.util.ResourceBundle;
5 import java.util.logging.Level;
6
7 import com.alibaba.fastjson.JSON;
8 import com.foxinmy.weixin4j.model.WeixinAccount;
9
10
11
12
13
14
15
16
17
18
19 public class Weixin4jConfigUtil {
20 private final static String CLASSPATH_PREFIX = "classpath:";
21 private final static String CLASSPATH_VALUE;
22 public final static ClassLoader CLASSLOADER;
23 private static ResourceBundle weixinBundle;
24 static {
25 CLASSLOADER = Thread.currentThread().getContextClassLoader();
26 CLASSPATH_VALUE = CLASSLOADER.getResource("").getPath();
27 try {
28 weixinBundle = ResourceBundle.getBundle(Consts.WEIXIN4J);
29 } catch (MissingResourceException e) {
30 ;
31 }
32 }
33
34 private final static String WEIXIN4J_PREFIX = "weixin4j";
35
36 private static String wrapKeyName(String key) {
37 if (!key.startsWith(WEIXIN4J_PREFIX)) {
38 return String.format("%s.%s", WEIXIN4J_PREFIX, key);
39 }
40 return key;
41 }
42
43
44
45
46
47
48
49 public static String getValue(String key) {
50 String wrapKey = wrapKeyName(key);
51 return System.getProperty(wrapKey, weixinBundle.getString(wrapKey));
52 }
53
54
55
56
57
58
59
60
61 public static String getValue(String key, String defaultValue) {
62 String value = defaultValue;
63 try {
64 value = getValue(key);
65 if (StringUtil.isBlank(value)) {
66 value = defaultValue;
67 }
68 } catch (MissingResourceException e) {
69 ;
70 } catch (NullPointerException e) {
71 ;
72 }
73 return value;
74 }
75
76
77
78
79
80
81
82 public static String getClassPathValue(String key) {
83 return replaceClassPathValue(getValue(key));
84 }
85
86
87
88
89
90
91
92 public static String getClassPathValue(String key, String defaultValue) {
93 return replaceClassPathValue(getValue(key, defaultValue));
94 }
95
96 public static String replaceClassPathValue(String value) {
97 return value.replaceFirst(CLASSPATH_PREFIX, CLASSPATH_VALUE);
98 }
99
100
101
102
103
104
105 public static WeixinAccount getWeixinAccount() {
106 WeixinAccount account = null;
107 try {
108 account = JSON.parseObject(getValue("account"), WeixinAccount.class);
109 } catch (NullPointerException e) {
110 System.err.println("'weixin4j.account' key not found in weixin4j.properties.");
111 } catch (MissingResourceException e) {
112 System.err.println("'weixin4j.account' key not found in weixin4j.properties.");
113 }
114 return account;
115 }
116
117 public static Level getJdkLoggerLevel(){
118 try {
119 Level level = Level.parse(getValue("jdkLogger.level", "OFF"));
120 return level;
121 }catch (IllegalArgumentException ex){
122 return Level.OFF;
123 }
124 }
125 }