View Javadoc
1   package com.foxinmy.weixin4j.wxa.api;
2   
3   import java.util.Properties;
4   import java.util.ResourceBundle;
5   import java.util.regex.Matcher;
6   import java.util.regex.Pattern;
7   
8   import com.foxinmy.weixin4j.api.BaseApi;
9   
10  /**
11   * @since 1.8
12   */
13  abstract class WxaApi extends BaseApi {
14  
15  	private static final ResourceBundle WEIXIN_BUNDLE;
16  
17  	static {
18  		WEIXIN_BUNDLE = ResourceBundle
19  			.getBundle("com/foxinmy/weixin4j/wxa/api/weixin");
20  	}
21  
22  	private final Properties cache = new Properties();
23  	private final Properties properties;
24  	private final Pattern uriPattern = Pattern.compile("(\\{[^\\}]*\\})");
25  
26  	public WxaApi() {
27  		this(null);
28  	}
29  
30  	/**
31  	 * Constructs {@link WxaApi} with specified {@code properties}.
32  	 *
33  	 * @param properties the properties to override the {@link #weixinBundle()}.
34  	 */
35  	public WxaApi(Properties properties) {
36  		this.properties = properties;
37  	}
38  
39  	@Override
40  	protected ResourceBundle weixinBundle() {
41  		return WEIXIN_BUNDLE;
42  	}
43  
44  	@Override
45  	protected String getRequestUri(String key) {
46  		String url = this.cache.getProperty(key);
47  		if (url != null) {
48  			return url;
49  		}
50  
51  		if (this.properties != null && (url = this.properties.getProperty(key)) != null) {
52  			Matcher m = uriPattern.matcher(url);
53  			StringBuffer sb = new StringBuffer();
54  			String sub = null;
55  			while (m.find()) {
56  				sub = m.group();
57  				m.appendReplacement(sb,
58  					getRequestUri(sub.substring(1, sub.length() - 1)));
59  			}
60  			m.appendTail(sb);
61  			url = sb.toString();
62  		} else {
63  			url = super.getRequestUri(key);
64  		}
65  
66  		this.cache.setProperty(key, url);
67  
68  		return url;
69  	}
70  
71  	String getRequestUri(String key, Object... args) {
72  		return String.format(getRequestUri(key), args);
73  	}
74  
75  }