package com.shensu.captcha.test.demo;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.NumberUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
1. Created by yansheng on 2014/6/29.
*/
@Slf4j
@Controller
@RequestMapping("/validate")
public class ValidateController {
/**
* 生成验证码
*
* @return
*/
@RequestMapping(value = "/init")
@ResponseBody
public JSONObject init() throws IOException {
JSONObject object = new JSONObject();
/*redis实现:使用base64编码转化成字符串处理*/
// List<String> imgList = JedisUtils.getList(JedisConfig.KEY_VALIDATE_IMG);
// List<String> tpllist = JedisUtils.getList(JedisConfig.KEY_VALIDATE_TPL);
// if (null == imgList || imgList.size() < 1 || tpllist == null || tpllist.size() < 1) {
// imgList = new ArrayList<String>();
// tpllist = new ArrayList<String>();
// initValidateResources(imgList,tpllist);
// JedisUtils.setList(JedisConfig.KEY_VALIDATE_IMG,imgList,JedisConfig.JEDIS_EXPIRE*3);
// JedisUtils.setList(JedisConfig.KEY_VALIDATE_TPL,tpllist,JedisConfig.JEDIS_EXPIRE*3);
// }
/*本地缓存实现*/
List<byte[]> imgList = ValidateCache.get(JedisConfig.KEY_VALIDATE_IMG);
List<byte[]> tpllist = ValidateCache.get(JedisConfig.KEY_VALIDATE_TPL);
if (null == imgList || imgList.size() < 1 || tpllist == null || tpllist.size() < 1) {
imgList = new ArrayList<byte[]>();
tpllist = new ArrayList<byte[]>();
initValidateResources(imgList,tpllist);
ValidateCache.set(JedisConfig.KEY_VALIDATE_IMG,imgList);
ValidateCache.set(JedisConfig.KEY_VALIDATE_TPL,tpllist);
}
byte[] targetIS = null;
byte[] templateIS = null;
Random ra = new Random();
if (null != imgList){
int rd = ra.nextInt(imgList.size());
targetIS = imgList.get(rd);
}
if (null != tpllist){
int rd = ra.nextInt(tpllist.size());
templateIS = tpllist.get(rd);
}
Map<String, Object> pictureMap = null;
try {
pictureMap = VerifyImageUtil.pictureTemplatesCut(templateIS,targetIS , "png", "jpg");
String newImage = Base64Utils.encodeToString((byte[]) pictureMap.get("newImage"));
String sourceImage = Base64Utils.encodeToString((byte[]) pictureMap.get("oriCopyImage"));
int X = (int) pictureMap.get("X");
int Y = (int) pictureMap.get("Y");
object.put("newImage", newImage);
object.put("sourceImage", sourceImage);
//object.put("X", X);
object.put("Y", Y);
String token = UUID.randomUUID().toString().replaceAll("-", "");
Map<String, Object> tokenObj = new HashMap<String, Object>();
tokenObj.put("token", token);
tokenObj.put("X", X);
tokenObj.put("Y", Y);
//token 保存2分钟
// JedisUtils.setObjectMap(JedisConfig.KEY_VALIDATE_TOKEN + ":" + token, tokenObj, 120000);
object.put("token", token);
} catch (Exception e) {
log.error("",e);
}
return object;
}
/**
* 初始化验证图形生成资源
* @param imgList
* @param tpllist
*/
private void initValidateResources(List<byte[]> imgList, List<byte[]> tpllist) throws IOException {
/*加载验证原图*/
String target = URLDecoder.decode(ValidateController.class.getClassLoader().getResource("static/image/validate/targets").getPath(),"UTF-8");
byte[] targetIS = null;
byte[] templateIS = null;
if (target.indexOf("!/") != -1) {//jar包
String jarPath = "jar:" + target;
log.debug(jarPath);
URL jarURL = new URL(jarPath);
JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection();
JarFile jarFile = jarCon.getJarFile();
Enumeration<JarEntry> jarEntrys = jarFile.entries();
while (jarEntrys.hasMoreElements()) {
JarEntry entry = jarEntrys.nextElement();
String name = entry.getName();
if (name.startsWith("static/image/validate/targets") && !name.equals("static/image/validate/targets/") && (name.endsWith(".jpg") || name.endsWith(".png"))) {
log.debug("targets=" + name);
InputStream isTemplates = jarFile.getInputStream(entry);
targetIS = IOUtils.toByteArray(jarFile.getInputStream(entry));
imgList.add(targetIS);
} else if (name.startsWith("static/image/validate/templates") && !name.equals("static/image/validate/templates/") && (name.endsWith(".jpg") || name.endsWith(".png"))) {
log.debug("templates=" + name);
InputStream isTemplates = jarFile.getInputStream(entry);
templateIS = IOUtils.toByteArray(jarFile.getInputStream(entry));
tpllist.add(templateIS);
}
}
} else {
File targetBaseFile = new File(target);
if (null != targetBaseFile) {
File[] fs = targetBaseFile.listFiles();
// Random ra = new Random();
// if (null != fs && fs.length > 0) {
// int random = ra.nextInt(fs.length);
// targetIS = IOUtils.toByteArray(new FileInputStream(fs[random]));
// }
for (File f : fs){
targetIS = IOUtils.toByteArray(new FileInputStream(f));
imgList.add(targetIS);
}
}
/*加载切图模板*/
String template = URLDecoder.decode(ValidateController.class.getClassLoader().getResource("static/image/validate/templates").getFile(),"UTF-8");
File templateBaseFile = new File(template);
if (null != templateBaseFile) {
File[] fs = templateBaseFile.listFiles();
// Random ra = new Random();
// if (null != fs && fs.length > 0) {
// int random = ra.nextInt(fs.length);
// templateIS = IOUtils.toByteArray(new FileInputStream(fs[random]));
// }
for (File f : fs){
templateIS = IOUtils.toByteArray(new FileInputStream(f));
tpllist.add(templateIS);
}
}
}
log.info("initValidateResources:template size:" + tpllist.size() + "target size:" + imgList.size());
}
/**
* 验证方法 (有验证码的方法提交,有时候也可以带上验证参数,做后端二次验证)
*
* @return
*/
@RequestMapping(value = "check",method = RequestMethod.POST)
@Respon