1 packagecom.tixa.wedding.util;2
3 importjava.security.MessageDigest;4 importjava.util.Calendar;5 importjava.util.Date;6 importjava.util.HashMap;7 importjava.util.Map;8 importjava.util.Map.Entry;9 importjava.util.concurrent.Executors;10 importjava.util.concurrent.ScheduledExecutorService;11 importjava.util.concurrent.TimeUnit;12
13 importorg.apache.log4j.Logger;14
15
16
17 public classTokenUtil {18
19 private static final int INTERVAL = 7;//token过期时间间隔 天
20 private static final String YAN = "testMRf1$789787aadfjkds//*-+'[]jfeu;384785*^*&%^%$%";//加盐
21 private static final int HOUR = 3;//检查token过期线程执行时间 时
22
23 private static Logger logger = Logger.getLogger("visit");24
25 private static Map tokenMap = new HashMap();26 private static TokenUtil tokenUtil = null;27 static ScheduledExecutorService scheduler =Executors.newSingleThreadScheduledExecutor();28
29 static{30 logger.info("\n===============进入TokenUtil静态代码块==================");31 listenTask();32 }33
34
35 public staticTokenUtil getTokenUtil() {36 if (tokenUtil == null) {37 synInit();38 }39
40 returntokenUtil;41 }42
43 private static synchronized voidsynInit() {44 if (tokenUtil == null) {45 tokenUtil = newTokenUtil();46 }47 }48
49 publicTokenUtil() {50 }51
52
53
54 public static MapgetTokenMap() {55 returntokenMap;56 }57
58 /**
59 * 产生一个token60 */
61 public static Token generateToken(String uniq,intid) {62 Token token = new Token(MD5(System.currentTimeMillis()+YAN+uniq+id), System.currentTimeMillis());63 synchronized(tokenMap) {64 tokenMap.put(id, token);65 }66 returntoken;67 }68
69
70 /**
71 * @Title: removeToken72 * @Description: 去除token73 *@param @paramnonce74 *@param @return参数75 *@returnboolean 返回类型76 */
77 public static boolean removeToken(intid) {78 synchronized(tokenMap) {79 tokenMap.remove(id);80 logger.info(tokenMap.get(id) == null ? "\n=========已注销========": "\n++++++++注销失败+++++++++++++++");81 }82 return true;83 }84
85 /**
86 * @Title: volidateToken87 * @Description: 校验token88 *@param @paramsignature89 *@param @paramnonce90 *@param @return参数91 *@returnboolean 返回类型92 */
93 public static boolean volidateToken(String signature, intid) {94 boolean flag = false;95 Token token =(Token) tokenMap.get(id);96 if (token != null &&token.getSignature().equals(signature)) {97 logger.info("\n=====已在线=======");98 flag = true;99 }100
101 returnflag;102 }103
104 /**
105 *106 * @Title: MD5107 * @Description: 加密108 *@param @params109 *@param @return参数110 *@returnString 返回类型111 */
112 public final staticString MD5(String s) {113 try{114 byte[] btInput =s.getBytes();115 //获得MD5摘要算法的 MessageDigest 对象
116 MessageDigest mdInst = MessageDigest.getInstance("MD5");117 //使用指定的字节更新摘要
118 mdInst.update(btInput);119 //获得密文
120 returnbyte2hex(mdInst.digest());121 } catch(Exception e) {122 e.printStackTrace();123 return null;124 }125 }126
127 /**
128 * 将字节数组转换成16进制字符串129 *@paramb130 *@return
131 */
132 private static String byte2hex(byte[] b) {133 StringBuilder sbDes = newStringBuilder();134 String tmp = null;135 for (int i = 0; i < b.length; i++) {136 tmp = (Integer.toHexString(b[i] & 0xFF));137 if (tmp.length() == 1) {138 sbDes.append("0");139 }140 sbDes.append(tmp);141 }142 returnsbDes.toString();143 }144
145 /**
146 * @Title: listenTask147 * @Description: 定时执行token过期清除任务148 *@param参数149 *@returnvoid 返回类型150 */
151 public static voidlistenTask(){152 Calendar calendar =Calendar.getInstance();153 int year =calendar.get(Calendar.YEAR);154 int month =calendar.get(Calendar.MONTH);155 int day =calendar.get(Calendar.DAY_OF_MONTH);156 //定制每天的HOUR点,从明天开始
157 calendar.set(year, month, day+1, HOUR, 0, 0);158 // calendar.set(year, month, day, 17, 11, 40);159 Date date =calendar.getTime();160
161 scheduler.scheduleAtFixedRate( new ListenToken(), (date.getTime()-System.currentTimeMillis())/1000, 60*60*24, TimeUnit.SECONDS);162 }163
164
165
166 /**
167 * @ClassName: ListenToken168 * @Description: 监听token过期线程runnable实现169 *@authormrf170 * @date 2015-10-21 下午02:22:24171 *172 */
173 static class ListenToken implementsRunnable {174 publicListenToken() {175 super();176 }177
178 public voidrun() {179 logger.info("\n**************************执行监听token列表****************************");180 try{181 synchronized(tokenMap) {182 for (int i = 0; i < 5; i++) {183 if (tokenMap != null && !tokenMap.isEmpty()) {184 for (Entryentry : tokenMap.entrySet()) {185 Token token =(Token) entry.getValue();186 logger.info("\n==============已登录用户有:"+entry + "=====================");187 //try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
188 int interval = (int) ((System.currentTimeMillis() - token.getTimestamp()) / 1000 / 60 / 60 / 24);189 if (interval >INTERVAL) {190 tokenMap.remove(entry.getKey());191 logger.info("\n==============移除token:" + entry+ "=====================");192 }193
194 }195 }196 }197
198 }199 } catch(Exception e) {200 logger.error("token监听线程错误:"+e.getMessage());201 e.printStackTrace();202 }203 }204 }205
206
207
208 public static voidmain(String[] args) {209 System.out.println(generateToken( "s",1));210 System.out.println(generateToken( "q",1));211 System.out.println(generateToken( "s3",2));212 System.out.println(generateToken( "s4",3));213 System.out.println(removeToken(3));214 System.out.println(getTokenMap());215 }216
217 }218
219