规范部分代码

This commit is contained in:
Binary Wang
2017-12-16 18:50:07 +08:00
parent d804d153fc
commit b1aafae6da
12 changed files with 69 additions and 53 deletions

View File

@@ -5,9 +5,9 @@
* The ASF licenses this file to You under the Apache License, Version 2.0 * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,9 +23,6 @@ package me.chanjar.weixin.common.session;
* *
* @author Craig R. McClanahan * @author Craig R. McClanahan
*/ */
public class Constants { public class Constants {
public static final String PACKAGE = "me.chanjar.weixin.common.session";
public static final String Package = "me.chanjar.weixin.common.session";
} }

View File

@@ -11,13 +11,12 @@ public class StandardSession implements WxSession, InternalSession {
/** /**
* The string manager for this package. * The string manager for this package.
*/ */
protected static final StringManager sm = StringManager.getManager(Constants.Package); protected static final StringManager SM = StringManager.getManager(Constants.PACKAGE);
/** /**
* Type array. * Type array.
*/ */
private static final String[] EMPTY_ARRAY = new String[0]; private static final String[] EMPTY_ARRAY = new String[0];
// ------------------------------ WxSession
protected Map<String, Object> attributes = new ConcurrentHashMap<>(); protected Map<String, Object> attributes = new ConcurrentHashMap<>();
/** /**
* The session identifier of this Session. * The session identifier of this Session.
@@ -73,7 +72,7 @@ public class StandardSession implements WxSession, InternalSession {
if (!isValidInternal()) { if (!isValidInternal()) {
throw new IllegalStateException throw new IllegalStateException
(sm.getString("sessionImpl.getAttribute.ise")); (SM.getString("sessionImpl.getAttribute.ise"));
} }
if (name == null) { if (name == null) {
@@ -86,7 +85,7 @@ public class StandardSession implements WxSession, InternalSession {
@Override @Override
public Enumeration<String> getAttributeNames() { public Enumeration<String> getAttributeNames() {
if (!isValidInternal()) { if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("sessionImpl.getAttributeNames.ise")); throw new IllegalStateException(SM.getString("sessionImpl.getAttributeNames.ise"));
} }
Set<String> names = new HashSet<>(); Set<String> names = new HashSet<>();
@@ -98,7 +97,7 @@ public class StandardSession implements WxSession, InternalSession {
public void setAttribute(String name, Object value) { public void setAttribute(String name, Object value) {
// Name cannot be null // Name cannot be null
if (name == null) { if (name == null) {
throw new IllegalArgumentException(sm.getString("sessionImpl.setAttribute.namenull")); throw new IllegalArgumentException(SM.getString("sessionImpl.setAttribute.namenull"));
} }
// Null value is the same as removeAttribute() // Null value is the same as removeAttribute()
@@ -109,7 +108,7 @@ public class StandardSession implements WxSession, InternalSession {
// Validate our current state // Validate our current state
if (!isValidInternal()) { if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("sessionImpl.setAttribute.ise", getIdInternal())); throw new IllegalStateException(SM.getString("sessionImpl.setAttribute.ise", getIdInternal()));
} }
this.attributes.put(name, value); this.attributes.put(name, value);
@@ -123,8 +122,9 @@ public class StandardSession implements WxSession, InternalSession {
@Override @Override
public void invalidate() { public void invalidate() {
if (!isValidInternal()) if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("sessionImpl.invalidate.ise")); throw new IllegalStateException(SM.getString("sessionImpl.invalidate.ise"));
}
// Cause this session to expire // Cause this session to expire
expire(); expire();

View File

@@ -13,8 +13,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
*/ */
public class StandardSessionManager implements WxSessionManager, InternalSessionManager { public class StandardSessionManager implements WxSessionManager, InternalSessionManager {
protected static final StringManager sm = protected static final StringManager SM = StringManager.getManager(Constants.PACKAGE);
StringManager.getManager(Constants.Package);
/** /**
* The descriptive name of this Manager implementation (for logging). * The descriptive name of this Manager implementation (for logging).
*/ */
@@ -82,7 +81,7 @@ public class StandardSessionManager implements WxSessionManager, InternalSession
public WxSession getSession(String sessionId, boolean create) { public WxSession getSession(String sessionId, boolean create) {
if (sessionId == null) { if (sessionId == null) {
throw new IllegalStateException throw new IllegalStateException
(sm.getString("sessionManagerImpl.getSession.ise")); (SM.getString("sessionManagerImpl.getSession.ise"));
} }
InternalSession session = findSession(sessionId); InternalSession session = findSession(sessionId);
@@ -124,25 +123,24 @@ public class StandardSessionManager implements WxSessionManager, InternalSession
@Override @Override
public InternalSession findSession(String id) { public InternalSession findSession(String id) {
if (id == null) {
if (id == null)
return (null); return (null);
}
return this.sessions.get(id); return this.sessions.get(id);
} }
@Override @Override
public InternalSession createSession(String sessionId) { public InternalSession createSession(String sessionId) {
if (sessionId == null) { if (sessionId == null) {
throw new IllegalStateException throw new IllegalStateException
(sm.getString("sessionManagerImpl.createSession.ise")); (SM.getString("sessionManagerImpl.createSession.ise"));
} }
if ((this.maxActiveSessions >= 0) && if ((this.maxActiveSessions >= 0) &&
(getActiveSessions() >= this.maxActiveSessions)) { (getActiveSessions() >= this.maxActiveSessions)) {
this.rejectedSessions++; this.rejectedSessions++;
throw new TooManyActiveSessionsException( throw new TooManyActiveSessionsException(
sm.getString("sessionManagerImpl.createSession.tmase"), SM.getString("sessionManagerImpl.createSession.tmase"),
this.maxActiveSessions); this.maxActiveSessions);
} }
@@ -230,8 +228,9 @@ public class StandardSessionManager implements WxSessionManager, InternalSession
@Override @Override
public void backgroundProcess() { public void backgroundProcess() {
this.count = (this.count + 1) % this.processExpiresFrequency; this.count = (this.count + 1) % this.processExpiresFrequency;
if (this.count == 0) if (this.count == 0) {
processExpires(); processExpires();
}
} }
/** /**
@@ -243,16 +242,18 @@ public class StandardSessionManager implements WxSessionManager, InternalSession
InternalSession sessions[] = findSessions(); InternalSession sessions[] = findSessions();
int expireHere = 0; int expireHere = 0;
if (this.log.isDebugEnabled()) if (this.log.isDebugEnabled()) {
this.log.debug("Start expire sessions {} at {} sessioncount {}", getName(), timeNow, sessions.length); this.log.debug("Start expire sessions {} at {} sessioncount {}", getName(), timeNow, sessions.length);
for (int i = 0; i < sessions.length; i++) { }
if (sessions[i] != null && !sessions[i].isValid()) { for (InternalSession session : sessions) {
if (session != null && !session.isValid()) {
expireHere++; expireHere++;
} }
} }
long timeEnd = System.currentTimeMillis(); long timeEnd = System.currentTimeMillis();
if (this.log.isDebugEnabled()) if (this.log.isDebugEnabled()) {
this.log.debug("End expire sessions {} processingTime {} expired sessions: {}", getName(), timeEnd - timeNow, expireHere); this.log.debug("End expire sessions {} processingTime {} expired sessions: {}", getName(), timeEnd - timeNow, expireHere);
}
this.processingTime += (timeEnd - timeNow); this.processingTime += (timeEnd - timeNow);
} }

View File

@@ -28,10 +28,10 @@ import java.util.Random;
*/ */
public class WxCryptUtil { public class WxCryptUtil {
private static final Base64 base64 = new Base64(); private static final Base64 BASE64 = new Base64();
private static final Charset CHARSET = StandardCharsets.UTF_8; private static final Charset CHARSET = StandardCharsets.UTF_8;
private static final ThreadLocal<DocumentBuilder> builderLocal = new ThreadLocal<DocumentBuilder>() { private static final ThreadLocal<DocumentBuilder> BUILDER_LOCAL = new ThreadLocal<DocumentBuilder>() {
@Override @Override
protected DocumentBuilder initialValue() { protected DocumentBuilder initialValue() {
try { try {
@@ -65,7 +65,7 @@ public class WxCryptUtil {
static String extractEncryptPart(String xml) { static String extractEncryptPart(String xml) {
try { try {
DocumentBuilder db = builderLocal.get(); DocumentBuilder db = BUILDER_LOCAL.get();
Document document = db.parse(new InputSource(new StringReader(xml))); Document document = db.parse(new InputSource(new StringReader(xml)));
Element root = document.getDocumentElement(); Element root = document.getDocumentElement();
@@ -192,7 +192,7 @@ public class WxCryptUtil {
byte[] encrypted = cipher.doFinal(unencrypted); byte[] encrypted = cipher.doFinal(unencrypted);
// 使用BASE64对加密后的字符串进行编码 // 使用BASE64对加密后的字符串进行编码
return base64.encodeToString(encrypted); return BASE64.encodeToString(encrypted);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@@ -4,5 +4,16 @@ package me.chanjar.weixin.common.util.http;
* Created by ecoolper on 2017/4/28. * Created by ecoolper on 2017/4/28.
*/ */
public enum HttpType { public enum HttpType {
JODD_HTTP, APACHE_HTTP, OK_HTTP; /**
* jodd-http.
*/
JODD_HTTP,
/**
* apache httpclient.
*/
APACHE_HTTP,
/**
* okhttp.
*/
OK_HTTP
} }

View File

@@ -46,8 +46,7 @@ import java.util.*;
*/ */
public class StringManager { public class StringManager {
private static final Map<String, Map<Locale, StringManager>> managers = private static final Map<String, Map<Locale, StringManager>> MANAGERS = new Hashtable<>();
new Hashtable<>();
private static int LOCALE_CACHE_SIZE = 10; private static int LOCALE_CACHE_SIZE = 10;
/** /**
* The ResourceBundle for this StringManager. * The ResourceBundle for this StringManager.
@@ -118,16 +117,16 @@ public class StringManager {
public static final synchronized StringManager getManager( public static final synchronized StringManager getManager(
String packageName, Locale locale) { String packageName, Locale locale) {
Map<Locale, StringManager> map = managers.get(packageName); Map<Locale, StringManager> map = MANAGERS.get(packageName);
if (map == null) { if (map == null) {
/* /*
* Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE. * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE.
* Expansion occurs when size() exceeds capacity. Therefore keep * Expansion occurs when size() exceeds capacity. Therefore keep
* size at or below capacity. * size at or below capacity.
* removeEldestEntry() executes after insertion therefore the test * removeEldestEntry() executes after insertion therefore the test
* for removal needs to use one less than the maximum desired size * for removal needs to use one less than the maximum desired size
* *
*/ */
map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 1, true) { map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 1, true) {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@@ -137,7 +136,7 @@ public class StringManager {
return size() > (LOCALE_CACHE_SIZE - 1); return size() > (LOCALE_CACHE_SIZE - 1);
} }
}; };
managers.put(packageName, map); MANAGERS.put(packageName, map);
} }
StringManager mgr = map.get(locale); StringManager mgr = map.get(locale);

View File

@@ -16,8 +16,14 @@ import java.util.List;
@Data @Data
public class WxCpUser implements Serializable { public class WxCpUser implements Serializable {
public enum Gender { public enum Gender {
/**
* 男
*/
MALE("", "1"), MALE("", "1"),
FEMAIL("", "2"); /**
* 女
*/
FEMALE("", "2");
private String genderName; private String genderName;
private String code; private String code;
@@ -40,7 +46,7 @@ public class WxCpUser implements Serializable {
return Gender.MALE; return Gender.MALE;
} }
if ("2".equals(code)) { if ("2".equals(code)) {
return Gender.FEMAIL; return Gender.FEMALE;
} }
return null; return null;

View File

@@ -37,7 +37,7 @@ public class WxCpUserServiceImplTest {
user.setName("Some Woman"); user.setName("Some Woman");
user.setDepartIds(new Integer[]{2}); user.setDepartIds(new Integer[]{2});
user.setEmail("none@none.com"); user.setEmail("none@none.com");
user.setGender(WxCpUser.Gender.FEMAIL); user.setGender(WxCpUser.Gender.FEMALE);
user.setMobile("13560084979"); user.setMobile("13560084979");
user.setPosition("woman"); user.setPosition("woman");
user.setTelephone("3300393"); user.setTelephone("3300393");

View File

@@ -213,7 +213,7 @@ public class WxMpCardServiceImpl implements WxMpCardService {
WxMpCardResult cardResult = WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement, WxMpCardResult cardResult = WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement,
new TypeToken<WxMpCardResult>() { new TypeToken<WxMpCardResult>() {
}.getType()); }.getType());
if (!cardResult.getErrorCode().equals("0")) { if (!"0".equals(cardResult.getErrorCode())) {
this.log.warn("朋友的券mark失败{}", cardResult.getErrorMsg()); this.log.warn("朋友的券mark失败{}", cardResult.getErrorMsg());
} }
} }

View File

@@ -227,6 +227,7 @@ public abstract class WxMpServiceAbstractImpl<H, P> implements WxMpService, Requ
/** /**
* 向微信端发送请求在这里执行的策略是当发生access_token过期时才去刷新然后重新执行请求而不是全局定时请求 * 向微信端发送请求在这里执行的策略是当发生access_token过期时才去刷新然后重新执行请求而不是全局定时请求
*/ */
@Override
public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException { public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException {
int retryTimes = 0; int retryTimes = 0;
do { do {

View File

@@ -30,7 +30,7 @@ import java.util.Map;
* @author <a href="https://github.com/007gzs">007</a> * @author <a href="https://github.com/007gzs">007</a>
*/ */
public class WxOpenComponentServiceImpl implements WxOpenComponentService { public class WxOpenComponentServiceImpl implements WxOpenComponentService {
private static final Map<String, WxMpService> wxOpenMpServiceMap = new Hashtable<>(); private static final Map<String, WxMpService> WX_OPEN_MP_SERVICE_MAP = new Hashtable<>();
protected final Logger log = LoggerFactory.getLogger(this.getClass()); protected final Logger log = LoggerFactory.getLogger(this.getClass());
private WxOpenService wxOpenService; private WxOpenService wxOpenService;
@@ -40,14 +40,14 @@ public class WxOpenComponentServiceImpl implements WxOpenComponentService {
@Override @Override
public WxMpService getWxMpServiceByAppid(String appId) { public WxMpService getWxMpServiceByAppid(String appId) {
WxMpService wxMpService = wxOpenMpServiceMap.get(appId); WxMpService wxMpService = WX_OPEN_MP_SERVICE_MAP.get(appId);
if (wxMpService == null) { if (wxMpService == null) {
synchronized (wxOpenMpServiceMap) { synchronized (WX_OPEN_MP_SERVICE_MAP) {
wxMpService = wxOpenMpServiceMap.get(appId); wxMpService = WX_OPEN_MP_SERVICE_MAP.get(appId);
if (wxMpService == null) { if (wxMpService == null) {
wxMpService = new WxOpenMpServiceImpl(this, appId, getWxOpenConfigStorage().getWxMpConfigStorage(appId)); wxMpService = new WxOpenMpServiceImpl(this, appId, getWxOpenConfigStorage().getWxMpConfigStorage(appId));
wxOpenMpServiceMap.put(appId, wxMpService); WX_OPEN_MP_SERVICE_MAP.put(appId, wxMpService);
} }
} }
} }

View File

@@ -30,6 +30,7 @@ public abstract class WxOpenServiceAbstractImpl<H, P> implements WxOpenService,
return wxOpenConfigStorage; return wxOpenConfigStorage;
} }
@Override
public void setWxOpenConfigStorage(WxOpenConfigStorage wxOpenConfigStorage) { public void setWxOpenConfigStorage(WxOpenConfigStorage wxOpenConfigStorage) {
this.wxOpenConfigStorage = wxOpenConfigStorage; this.wxOpenConfigStorage = wxOpenConfigStorage;
} }