Java_工具类汇总

Java工具类汇总

访问限流

配置源码

/**
 *
 * 接口限流测试类
 */
@RestController
@RequestMapping("api")
public class LimitController {
    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();

    /**
     * 测试限流注解,下面配置说明该接口 60秒内最多只能访问 10次,保存到redis的键名为 limit_test,
     */
    @Limit(key = "test", period = 60, count = 10, name = "testLimit", prefix = "limit")
    @GetMapping("/limit")
    public int testLimit() {
        return ATOMIC_INTEGER.incrementAndGet();
    }
}

public enum LimitType {
    CUSTOMER,
    IP;
}

import me.zhengjie.aspect.LimitType;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author jacky
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Limit {

    // 资源名称,用于描述接口功能
    String name() default "";

    // 资源 key
    String key() default "";

    // key prefix
    String prefix() default "";

    // 时间的,单位秒
    int period();

    // 限制访问次数
    int count();

    // 限制类型
    LimitType limitType() default LimitType.CUSTOMER;

}


import com.google.common.collect.ImmutableList;
import me.zhengjie.annotation.Limit;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.RequestHolder;
import me.zhengjie.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class LimitAspect {
    @Autowired
    private RedisTemplate redisTemplate;
    private static final Logger logger = LoggerFactory.getLogger(LimitAspect.class);


    @Pointcut("@annotation(me.zhengjie.annotation.Limit)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method signatureMethod = signature.getMethod();
        Limit limit = signatureMethod.getAnnotation(Limit.class);
        LimitType limitType = limit.limitType();
        String key = limit.key();
        if (StringUtils.isEmpty(key)) {
            switch (limitType) {
                case IP:
                    key = StringUtils.getIP(request);
                    break;
                default:
                    key = signatureMethod.getName();
            }
        }

        ImmutableList keys = ImmutableList.of(StringUtils.join(limit.prefix(), "_", key, "_", request.getRequestURI().replaceAll("/", "_")));

        String luaScript = buildLuaScript();
        RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
        Number count = (Number) redisTemplate.execute(redisScript, keys, limit.count(), limit.period());
        if (null != count && count.intValue() <= limit.count()) {
            logger.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.name());
            return joinPoint.proceed();
        } else {
            throw new BadRequestException("访问次数受限制");
        }
    }

    /**
     * 限流脚本
     */
    private String buildLuaScript() {
        return "local c" +
                "\nc = redis.call('get',KEYS[1])" +
                "\nif c and tonumber(c) > tonumber(ARGV[1]) then" +
                "\nreturn c;" +
                "\nend" +
                "\nc = redis.call('incr',KEYS[1])" +
                "\nif tonumber(c) == 1 then" +
                "\nredis.call('expire',KEYS[1],ARGV[2])" +
                "\nend" +
                "\nreturn c;";
    }
}

HTTP请求工具

配置源码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

/**
 * HttpUtils
 */
public class HttpUtils {
	
	private HttpKit() {}
	
	/**
	 * https 域名校验
	 */
	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}
	
	/**
	 * https 证书管理
	 */
	private static class TrustAnyTrustManager implements X509TrustManager {
		public X509Certificate[] getAcceptedIssuers() {
			return null;  
		}
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}
	}
	
	private static final String GET  = "GET";
	private static final String POST = "POST";
	private static String CHARSET = "UTF-8";
	
	private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory();
	private static final TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpKit.TrustAnyHostnameVerifier();
	
	private static SSLSocketFactory initSSLSocketFactory() {
		try {
			TrustManager[] tm = {new HttpKit.TrustAnyTrustManager() };
			SSLContext sslContext = SSLContext.getInstance("TLS");	// ("TLS", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			return sslContext.getSocketFactory();
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void setCharSet(String charSet) {
		if (StrKit.isBlank(charSet)) {
			throw new IllegalArgumentException("charSet can not be blank.");
		}
		HttpKit.CHARSET = charSet;
	}
	
	private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		URL _url = new URL(url);
		//以下为设置代理服务访问指定url,需要指定proxy_ip和proxy_port
		//Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy_ip,Integer.parseInt(proxy_port)));  
        //HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
		HttpURLConnection conn = (HttpURLConnection)_url.openConnection();
		if (conn instanceof HttpsURLConnection) {
			((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory);
			((HttpsURLConnection)conn).setHostnameVerifier(trustAnyHostnameVerifier);
		}
		
		conn.setRequestMethod(method);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		
		conn.setConnectTimeout(30000);
		conn.setReadTimeout(30000);
		
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
		
		if (headers != null && !headers.isEmpty()) {
			for (Entry<String, String> entry : headers.entrySet()) {
				conn.setRequestProperty(entry.getKey(), entry.getValue());
			}
		}

		return conn;
	}
	
	/**
	 * Send GET request
	 */
	public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) {
		HttpURLConnection conn = null;
		try {
			conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), GET, headers);
			conn.connect();
			return readResponseString(conn);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
		finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	/**
	 * Send POST request
	 */
	public static String post(String url, Map<String, String> queryParas, Map<String, String> headers) {
		HttpURLConnection conn = null;
		try {
			conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), GET, headers);
			conn.connect();
			return readResponseString(conn);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
		finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}
	
	public static String get(String url, Map<String, String> queryParas) {
		return get(url, queryParas, null);
	}
	
	public static String get(String url) {
		return get(url, null, null);
	}
	
	/**
	 * Send PUT request
	 */	
	public static String put(String url,String data,Map<String, String> headers) {
		HttpURLConnection conn = null;
		try {
			conn = getHttpConnection(buildUrlWithQueryString(url, null), "PUT", headers);
			conn.connect();
			if (data != null) {
				OutputStream out = conn.getOutputStream();
				out.write(data.getBytes(CHARSET));
				out.flush();
				out.close();
			}
			return readResponseString(conn);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
		finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}
	
	/**
	 * Send POST request
	 */
	public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) {
		HttpURLConnection conn = null;
		try {
			conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
			conn.connect();
			
			if (data != null) {
				OutputStream out = conn.getOutputStream();
				out.write(data.getBytes(CHARSET));
				out.flush();
				out.close();
			}
			
			return readResponseString(conn);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
		finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}
	
	public static String post(String url, Map<String, String> queryParas, String data) {
		return post(url, queryParas, data, null);
	}
	
	public static String post(String url, String data, Map<String, String> headers) {
		return post(url, null, data, headers);
	}
	
	public static String post(String url, String data) {
		return post(url, null, data, null);
	}
	
	private static String readResponseString(HttpURLConnection conn) {
		BufferedReader reader = null;
		try {
			StringBuilder ret;
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET));
			String line = reader.readLine();
			if (line != null) {
				ret = new StringBuilder();
				ret.append(line);
			} else {
				return "";
			}
			
			while ((line = reader.readLine()) != null) {
				ret.append('\n').append(line);
			}
			return ret.toString();
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
		finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					LogKit.error(e.getMessage(), e);
				}
			}
		}
	}
	
	/**
	 * Build queryString of the url
	 */
	private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) {
		if (queryParas == null || queryParas.isEmpty()) {
			return url;
		}
		
		StringBuilder sb = new StringBuilder(url);
		boolean isFirst;
		if (url.indexOf('?') == -1) {
			isFirst = true;
			sb.append('?');
		}
		else {
			isFirst = false;
		}
		
		for (Entry<String, String> entry : queryParas.entrySet()) {
			if (isFirst) {
				isFirst = false;
			} else {
				sb.append('&');
			}
			
			String key = entry.getKey();
			String value = entry.getValue();
			if (StrKit.notBlank(value)) {
				try {value = URLEncoder.encode(value, CHARSET);} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}
			}
			sb.append(key).append('=').append(value);
		}
		return sb.toString();
	}
	
	public static String readData(HttpServletRequest request) {
		BufferedReader br = null;
		try {
			StringBuilder ret;
			br = request.getReader();
			
			String line = br.readLine();
			if (line != null) {
				ret = new StringBuilder();
				ret.append(line);
			} else {
				return "";
			}
			
			while ((line = br.readLine()) != null) {
				ret.append('\n').append(line);
			}
			
			return ret.toString();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		finally {
			if (br != null) {
				try {br.close();} catch (IOException e) {LogKit.error(e.getMessage(), e);}
			}
		}
	}
	
	@Deprecated
	public static String readIncommingRequestData(HttpServletRequest request) {
		return readData(request);
	}
}

本地缓存

依赖pom.xml

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>18.0</version>
</dependency>

配置源码

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

/**
 * GuavaCache 本地缓存
 * 
 * 
 * @author vander
 * @date 2019年5月7日
 */
public class CacheUtils {
	
	private static LoadingCache<String, String> localCache = CacheBuilder.newBuilder()
			.initialCapacity(1000)  //缓存数据个数
			.maximumSize(10000)  //最大个数
			//expireAfterAccess:当缓存项在指定的时间段内没有被读或写就会被回收   expireAfterWrite:当缓存项在指定的时间段内没有更新就会被回收
			.expireAfterAccess(12, TimeUnit.HOURS) 
			.build(new CacheLoader<String, String>(){
				//通过key没有获取到对应的值,调用该方法
				@Override
				public String load(String key) throws Exception {
					return null;
				}
			});
	
	public static void set(String key,String value) {
		localCache.put(key, value);
	}
	
	public static String get(String key) {
		String value = "";
		try {
			value = localCache.get(key);
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return value;
	}

}

文件下载/上传

public class FileUtils {
	//文件下载
    public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException {
        response.setContentType("application/octet-stream");
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));			//保存的文件名,必须和页面编码一致,否则乱码
        response.addHeader("content-disposition","attachment;filename=" + returnName);
        response.setContentLength(byteArrayOutputStream.size());
        ServletOutputStream outputstream = response.getOutputStream();	//取得输出流
        byteArrayOutputStream.writeTo(outputstream);					//写到输出流
        byteArrayOutputStream.close();									//关闭
        outputstream.flush();											//刷数据
    }

	//文件上传
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception{
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}

POI报表处理

依赖pom.xml

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>4.0.1</version>
    </dependency>

配置源码

/**
 * 报表实体类注解
 * 
 * @author vander
 * @date 2019年4月12日
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAttribute {
    /** 对应的列名称 */
    String name() default "";

    /** excel列的索引 */
    int sort();

    /** 字段类型对应的格式 */
    String format() default "";
}

import com.plxc.domain.poi.ExcelAttribute;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.format.CellFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 报表导入
 * 
 * @author vander
 * @date 2019年4月12日
 * @param <T>
 */
public class ExcelImportUtil<T> {
 
    private Class clazz;
    private  Field fields[];

    //参数:
    public ExcelImportUtil(Class clazz) {
        this.clazz = clazz;
        fields = clazz.getDeclaredFields();
    }
 
    /**
     * 
     * 基于注解读取excel
     *      is     : 文件上传的流信息
     *      rowIndex:   读取数据的起始行
     *      cellIndex:  读取数据的其实单元格位置
     *
     */
    public List<T> readExcel(InputStream is, int rowIndex,int cellIndex) {
        List<T> list = new ArrayList<T>();
        T entity = null;
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);
            for (int rowNum = rowIndex; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                entity = (T) clazz.newInstance();
                for (int j = cellIndex; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j);
                    for (Field field : fields) {
                        if(field.isAnnotationPresent(ExcelAttribute.class)){
                            field.setAccessible(true);
                            ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
                            if(j == ea.sort()) {
                                field.set(entity, covertAttrType(field, cell));
                            }
                        }
                    }
                }
                list.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
 

    /**
     * 类型转换 将cell 单元格格式转为 字段类型
     */
    private Object covertAttrType(Field field, Cell cell) throws Exception {
        String fieldType = field.getType().getSimpleName();
        if ("String".equals(fieldType)) {
            return getValue(cell);
        }else if ("Date".equals(fieldType)) {
            return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(getValue(cell)) ;
        }else if ("int".equals(fieldType) || "Integer".equals(fieldType)) {
            return Integer.parseInt(getValue(cell));
        }else if ("double".equals(fieldType) || "Double".equals(fieldType)) {
            return Double.parseDouble(getValue(cell));
        }else {
            return null;
        }
    }
 
 
    /**
     * 格式转为String
     * @param cell
     * @return
     */
    public String getValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getRichStringCellValue().getString().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date dt = DateUtil.getJavaDate(cell.getNumericCellValue());
                    return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dt);
                } else {
                    // 防止数值变成科学计数法
                    String strCell = "";
                    Double num = cell.getNumericCellValue();
                    BigDecimal bd = new BigDecimal(num.toString());
                    if (bd != null) {
                        strCell = bd.toPlainString();
                    }
                    // 去除 浮点型 自动加的 .0
                    if (strCell.endsWith(".0")) {
                        strCell = strCell.substring(0, strCell.indexOf("."));
                    }
                    return strCell;
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }
}


import com.plxc.domain.poi.ExcelAttribute;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 导出Excel工具类
 *      基于模板打印的方式导出:
 */
@Getter
@Setter
public class ExcelExportUtil<T> {

    private int rowIndex;       //写入数据的起始行
    private int styleIndex;     //需要提取的样式所在的行号
    private Class clazz;        //对象的字节码
    private Field fields[];     //对象中的所有属性

    public ExcelExportUtil(Class clazz,int rowIndex,int styleIndex) {
        this.clazz = clazz;
        this.rowIndex = rowIndex;
        this.styleIndex = styleIndex;
        fields = clazz.getDeclaredFields();
    }

    /**
     * 基于注解导出
             参数:
                response:
                InputStream:模板的输入流
                objs:数据
                fileName:生成的文件名
     *
     */
    public void export(HttpServletResponse response,InputStream is, List<T> objs,String fileName) throws Exception {

        //1.根据模板创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        //2.读取工作表
        Sheet sheet = workbook.getSheetAt(0);
        //3.提取公共的样式
        CellStyle[] styles = getTemplateStyles(sheet.getRow(styleIndex));
        //4.根据数据创建每一行和每一个单元格的数据2
        AtomicInteger datasAi = new AtomicInteger(rowIndex); //数字
        for (T t : objs) {
            //datasAi.getAndIncrement()  :获取数字,并++    i++
            Row row = sheet.createRow(datasAi.getAndIncrement());
            for(int i=0;i<styles.length;i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(styles[i]);
                for (Field field : fields) {
                    if(field.isAnnotationPresent(ExcelAttribute.class)){
                        field.setAccessible(true);
                        ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
                        if(i == ea.sort()) {
                            if(field.get(t) != null) {
                                cell.setCellValue(field.get(t).toString());
                            }
                        }
                    }
                }
            }
        }
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("ISO8859-1")));
        response.setHeader("filename", fileName);
        workbook.write(response.getOutputStream());
    }

    public CellStyle[] getTemplateStyles(Row row) {
        CellStyle [] styles = new CellStyle[row.getLastCellNum()];
        for(int i=0;i<row.getLastCellNum();i++) {
            styles[i] = row.getCell(i).getCellStyle();
        }
        return styles;
    }
}

百度人脸识别

依赖pom.xml

<dependency>
	<groupId>com.baidu.aip</groupId>
	<artifactId>java-sdk</artifactId>
	<version>4.8.0</version>
</dependency>

配置源码

/**
 * 百度人脸识别工具类
 * 
 * @author vander
 * @date 2019年4月12日
 */
@Component
public class BaiduAiUtil {

    @Value("${ai.appId}")
    private String APP_ID;
    @Value("${ai.apiKey}")
    private String API_KEY;
    @Value("${ai.secretKey}")
    private String SECRET_KEY;
    @Value("${ai.imageType}")
    private String IMAGE_TYPE;
    @Value("${ai.groupId}")
    private String groupId;

    private AipFace client;

    private HashMap<String, String> options = new HashMap<String, String>();

    public BaiduAiUtil() {
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
    }

    @PostConstruct
    public void init() {
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
    }

    //判断用户是否已经注册了面部信息
    public Boolean faceExist(String userId) {
        //返回error_code:0 (存在),非0:不存在
        JSONObject res = client.getUser(userId, groupId, null);
        Integer errorCode = res.getInt("error_code");
        return errorCode == 0 ? true : false;
    }

    /**
     *  人脸注册 :将用户照片存入人脸库中
     */
    public Boolean faceRegister(String userId, String image) {
        // 人脸注册
        JSONObject res = client.addUser(image, IMAGE_TYPE, groupId, userId, options);
        Integer errorCode = res.getInt("error_code");
        return errorCode == 0 ? true : false;
    }

    /**
     *  人脸更新 :更新人脸库中的用户照片
     */
    public Boolean faceUpdate(String userId, String image) {
        // 人脸更新
        JSONObject res = client.updateUser(image, IMAGE_TYPE, groupId, userId, options);
        Integer errorCode = res.getInt("error_code");
        return errorCode == 0 ? true : false;
    }

    /**
     * 人脸检测:判断上传图片中是否具有面部头像
     */
    public Boolean faceCheck(String image) {
        JSONObject res = client.detect(image, IMAGE_TYPE, options);
        if (res.has("error_code") && res.getInt("error_code") == 0) {
            JSONObject resultObject = res.getJSONObject("result");
            Integer faceNum = resultObject.getInt("face_num");//检测的人脸数量
            return faceNum == 1?true:false;
        }else{
            return false;
        }
    }

    /**
     *  人脸查找:查找人脸库中最相似的人脸并返回数据
     *          处理:用户的匹配得分(score)大于80分,即可认为是同一个用户
     */
    public String faceSearch(String image) {
        JSONObject res = client.search(image, IMAGE_TYPE, groupId, options);
        if (res.has("error_code") && res.getInt("error_code") == 0) {
            JSONObject result = res.getJSONObject("result");
            JSONArray userList = result.getJSONArray("user_list");
            if (userList.length() > 0) {
                JSONObject user = userList.getJSONObject(0);
                double score = user.getDouble("score");
                if(score > 80) {
                    return user.getString("user_id");
                }
            }
        }
        return null;
    }
}

二维码

依赖pom.xml

<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>core</artifactId>
	<version>3.2.1</version>
</dependency>

<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>javase</artifactId>
	<version>3.2.1</version>
</dependency>

配置源码

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sun.org.apache.xml.internal.security.utils.Base64;

/**
 * 生成二维码
 * 
 * @author vander
 * @date 2019年4月12日
 */
@SuppressWarnings("restriction")
public class QRCodeUtils {

	public static void main(String[] args) throws IOException {
		System.err.println(crateQRCode("http://baidu.com"));
	}

	/**
	 * 生成Base64 二维码
	 */
	public static String crateQRCode(String content) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			QRCodeWriter writer = new QRCodeWriter();
			BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 200, 200);
			BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
			ImageIO.write(bufferedImage, "png", os);
			// 添加图片标识
			return new String("data:image/png;base64," + Base64.encode(os.toByteArray()));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			os.close();
		}
		return null;
	}

}

ID生成

依赖pom.xml

配置源码

/**
 * ID生成器
 * 
 * 
 * @author vander
 * @date 2018年11月28日
 */
public class TokenGenerator {

	/**
	 * 获取唯一id
	 * @return
	 */
    public static String generateUuid() {
        try {
			return generateValue(UUID.randomUUID().toString());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
        return null;
    }

    private static final char[] hexCode = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] data) {
        if(data == null) {
            return null;
        }
        StringBuilder r = new StringBuilder(data.length*2);
        for ( byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    /**
     * Token生成
     * 
     * @param param
     * @return
     * @throws NoSuchAlgorithmException 
     */
    public static String generateValue(String param) throws NoSuchAlgorithmException {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(param.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
    }
    
    public static void main(String[] args) throws NoSuchAlgorithmException {
    	System.err.println(generateUuid());
    	System.err.println(generateValue("dawdaddawdw"));
	}
}

DOM文件操作(xml)

依赖pom.xml

	<dependency>
		<groupId>dom4j</groupId>
		<artifactId>dom4j</artifactId>
	</dependency>
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
	</dependency>

配置源码

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * xml相关的工具类
 *
 */
@SuppressWarnings("all")
public class XmlUtil {

    /**
     * xml字符串转换成bean对象
     *
     * @param xmlStr xml字符串
     * @param clazz  待转换的class
     * @return 转换后的对象
     */
    public static Object xmlStrToBean(String xmlStr, Class clazz) {
        Object obj = null;
        try {
            // 将xml格式的数据转换成Map对象
            Map<String, Object> map = xmlStrToMap(xmlStr);
            // 将map对象的数据转换成Bean对象
            obj = mapToBean(map, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 将xml格式的字符串转换成Map对象
     *
     * @param xmlStr xml格式的字符串
     * @return Map对象
     * @throws Exception 异常
     */
    public static Map<String, Object> xmlStrToMap(String xmlStr) throws Exception {
        if (StringUtils.isBlank(xmlStr)) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        // 将xml格式的字符串转换成Document对象
        Document doc = DocumentHelper.parseText(xmlStr);
        // 获取根节点
        Element root = doc.getRootElement();
        // 获取根节点下的所有元素
        List children = root.elements();
        // 循环所有子元素
        if (children != null && children.size() > 0) {
            for (int i = 0; i < children.size(); i++) {
                Element child = (Element) children.get(i);
                map.put(child.getName(), child.getTextTrim());
            }
        }
        return map;
    }

    /**
     * 将xml格式字符串转换成Bean对象
     * 多级子节点递归遍历
     *
     * @param xmlStr
     * @param clazz
     * @return
     * @throws Exception
     */
    public static Object xmlStrToJavaBean(String xmlStr, Class clazz) {
        if (StringUtils.isBlank(xmlStr)) {
            return null;
        }
        Object obj = null;
        Map<String, Object> map = new HashMap<String, Object>();
        // 将xml格式的字符串转换成Document对象
        Document doc;
        try {
            doc = DocumentHelper.parseText(xmlStr);

            // 获取根节点
            Element root = doc.getRootElement();
            map = elementToMap(root, map);
            // 将map对象的数据转换成Bean对象
            obj = mapToBean(map, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 递归遍历xml子节点,转换Map
     *
     * @param element
     * @param map
     * @return
     */
    public static Map<String, Object> elementToMap(Element element, Map<String, Object> map) {
        if (element == null || map == null)
            return null;
        List children = element.elements();
        if (children != null && children.size() > 0) {
            for (int i = 0; i < children.size(); i++) {
                Element child = (Element) children.get(i);
                if (child.elements() != null && child.elements().size() > 0)
                    elementToMap(child, map);
                else
                    map.put(child.getName(), child.getTextTrim());
            }
        }
        return map;
    }

    /**
     * 将Map对象通过反射机制转换成Bean对象
     *
     * @param map   存放数据的map对象
     * @param clazz 待转换的class
     * @return 转换后的Bean对象
     * @throws Exception 异常
     */
    public static Object mapToBean(Map<String, Object> map, Class clazz) throws Exception {
        Object obj = clazz.newInstance();
        if (map != null && map.size() > 0) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String propertyName = entry.getKey();
                Object value = entry.getValue();
                String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
                Field field = getClassField(clazz, propertyName);
                if (field != null) {
                    Class fieldTypeClass = field.getType();
                    value = convertValType(value, fieldTypeClass);
                    clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
                }
            }
        }
        return obj;
    }

    /**
     * 将Object类型的值,转换成bean对象属性里对应的类型值
     *
     * @param value          Object对象值
     * @param fieldTypeClass 属性的类型
     * @return 转换后的值
     */
    private static Object convertValType(Object value, Class fieldTypeClass) {
        Object retVal = null;
        if (Long.class.getName().equals(fieldTypeClass.getName())
                || long.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Long.parseLong(value.toString());
        } else if (Integer.class.getName().equals(fieldTypeClass.getName())
                || int.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Integer.parseInt(value.toString());
        } else if (Float.class.getName().equals(fieldTypeClass.getName())
                || float.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Float.parseFloat(value.toString());
        } else if (Double.class.getName().equals(fieldTypeClass.getName())
                || double.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Double.parseDouble(value.toString());
        } else {
            retVal = value;
        }
        return retVal;
    }

    /**
     * 获取指定字段名称查找在class中的对应的Field对象(包括查找父类)
     *
     * @param clazz     指定的class
     * @param fieldName 字段名称
     * @return Field对象
     */
    private static Field getClassField(Class clazz, String fieldName) {
        if (Object.class.getName().equals(clazz.getName())) {
            return null;
        }
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }

        Class superClass = clazz.getSuperclass();
        if (superClass != null) {// 简单的递归一下
            return getClassField(superClass, fieldName);
        }
        return null;
    }

    public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);

        return documentBuilderFactory.newDocumentBuilder();
    }

    public static org.w3c.dom.Document newDocument() throws ParserConfigurationException {
        return newDocumentBuilder().newDocument();
    }
    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     */
    public static String getMap2Xml(Map<String, Object> data) {


        org.w3c.dom.Document document = null;
        try {
            document = newDocument();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e.getLocalizedMessage());
        }
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            Object value = entry.getValue();
            if (value == null) {
                value = "";
            }
            value = value.toString().trim();
            org.w3c.dom.Element filed = document.createElement(entry.getKey());
            filed.appendChild(document.createTextNode(value.toString()));
            root.appendChild(filed);
        }
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
            String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }


        return "";
    }
    /**
     * 获取子结点的xml
     *
     * @param children 集合
     * @return String 子结点的xml
     */
    public static JSON getChildren(NodeList children) {
        JSON json = null;
        for (int idx = 0; idx < children.getLength(); ++idx) {
            Node node = children.item(idx);
            NodeList nodeList = node.getChildNodes();
            if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() <= 1) {
                if (null == json) {
                    json = new JSONObject();
                }
                ((JSONObject) json).put(node.getNodeName(), node.getTextContent());
            } else if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() > 1) {
                if (null == json) {
                    json = new JSONObject();
                }
                if (json instanceof JSONObject) {
                    JSONObject j = ((JSONObject) json);
                    if (j.containsKey(node.getNodeName())) {
                        JSONArray array = new JSONArray();
                        array.add(json);
                        json = array;
                    } else {
                        j.put(node.getNodeName(), getChildren(nodeList));
                    }
                }

                if (json instanceof JSONArray) {
                    JSONObject c = new JSONObject();
                    c.put(node.getNodeName(), getChildren(nodeList));
                    ((JSONArray) json).add(c);
                }
            }
        }

        return json;
    }
    /**
     * @param in xml输入流
     * @param m  参数集
     * @return 整理完成的参数集
     * @throws IOException xml io转化异常
     */
    public static Map inputStream2Map(InputStream in, Map m) throws IOException {
        if (null == m) {
            m = new JSONObject();
        }
        try {
            DocumentBuilder documentBuilder = newDocumentBuilder();
            org.w3c.dom.Document doc = documentBuilder.parse(in);
            doc.getDocumentElement().normalize();
            NodeList children = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < children.getLength(); ++idx) {
                Node node = children.item(idx);
                NodeList nodeList = node.getChildNodes();
                if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() <= 1) {
                    m.put(node.getNodeName(), node.getTextContent());
                } else if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() > 1) {
                    m.put(node.getNodeName(), getChildren(nodeList));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            in.close();
        }
        return m;
    }

}

压缩解压

依赖pom.xml

<dependency>
	<groupId>net.lingala.zip4j</groupId>
	<artifactId>zip4j</artifactId>
	<version>1.3.1</version>
</dependency>

配置源码

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;

/**
 * 压缩工具类
 * 
 * @author vander
 *
 */
public class ZipUtil {

    /**
     * 解压zip文件
     * @param zipFilePath
     * @param targetPath
     * @throws ZipException
     */
    public static void unzip(String zipFilePath,String targetPath) throws Exception{
        ZipFile zipFile = new ZipFile(zipFilePath);
        zipFile.extractAll(targetPath);
    }

    /**
     * 解压zip文件(带密码)
     * @param zipFilePath
     * @param targetPath
     * @param password
     * @throws ZipException
     */
    public static void unzip(String zipFilePath,String password,String targetPath) throws Exception{
        ZipFile zipFile = new ZipFile(zipFilePath);
        if (zipFile.isEncrypted()) {
            zipFile.setPassword(password);
        }
        zipFile.extractAll(targetPath);
    }

    public static void main(String[] args) throws Exception {
        ZipUtil.unzip("F:\\develop\\upload\\upload.zip","F:\\develop\\upload\\zip\\");
    }
}

代理上网

依赖pom.xml

配置源码

/**
 * http/https请求客户端
 *
 * @author: vander
 * @create: 2018/12/11 9:37
 */
@SuppressWarnings("all")
public class ProxyHttpClient {

    private final static String CHARSET = "UTF-8";
    private final static int TIMEOUT_COUNT = 3;//超时次数
    private static Logger logger = LoggerFactory.getLogger(ProxyHttpClient.class);
    private static boolean isProxy = false;
    private static String host;
    private static String port;

    private ProxyHttpClient(boolean isProxy){
        this.isProxy = isProxy;
    }

    private ProxyHttpClient(boolean isProxy,String host,String port){
        this.host = host;
        this.port = port;
        this.isProxy = isProxy;
    }

    public static ProxyHttpClient getInstance(boolean isProxy,String host,String port){
        return new ProxyHttpClient(isProxy);
    }

    public static ProxyHttpClient getInstance(){
        return new ProxyHttpClient(false);
    }

    /**
     * post请求
     *
     * @param url
     * @param param
     * @return
     * @throws Exception
     */
    public String requestServer(String url, Map<String, Object> param)
            throws Exception {
        String sdate = DateUtils.format(new Date(), DateUtils.DATE_TIME);
        param.put("reqTime", sdate);
        if (url == null)
            throw new Exception("Unsupported request type, URL is null");
        if (url.startsWith("http://"))
            return doPostHttp(url, param,null,null);
        if (url.startsWith("https://")) {
            return doPostHttps(url, param,null,null);
        }
        throw new Exception("Unsupported request type, URL is [ " + url + " ]");
    }

    /**
     * get方式请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetHttp(String url,Map<String, String> headers) throws Exception {
        Properties proxy = null;
        if (isProxy){
            proxy = Proxy.getInstance(host, port).setUpAgent();
        }
        URL restServiceURL = new URL(url);
        logger.info("####" + DateUtils.format(new Date(), DateUtils.DATE_TIME) + "请求OTC接口URL" + url);
        HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.setConnectTimeout(5000);
        httpConnection.setReadTimeout(8000);
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("Accept-Charset", CHARSET);
        addheaders(httpConnection,headers);
        try {
            if (httpConnection.getResponseCode() != 200) {
                System.out.println("响应错误,代码: " + httpConnection.getResponseCode() + ",信息: " + httpConnection.getResponseMessage());
                throw new RuntimeException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
            }
        } catch (SocketTimeoutException e) {
            System.out.println("读取响应超时,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage() + ",异常信息: " + e.getMessage());
            throw new SocketTimeoutException("读取响应超时,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage());
        }
        BufferedReader responseBuffer = null;
        for (int i = 0; i < TIMEOUT_COUNT; i++) {
            try {
                responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), "UTF-8"));
                break;
            } catch (SocketTimeoutException e) {
                System.out.println("读取响应超时,重新读取,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new SocketTimeoutException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new Exception(e.getMessage());
                }
            }
        }
        StringBuffer result = new StringBuffer();
        String output = "";
        while (null != (output = responseBuffer.readLine())) {
            result.append(output);
        }
        responseBuffer.close();
        httpConnection.disconnect();
        if (null == result || "".equals(result)) {
            throw new Exception();
        }
        if (isProxy){
            if (proxy!=null){
                Proxy.getInstance(host,port).removeProxy(proxy);
            }
        }
        return result.toString();
    }
    /**
     * get方式请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public  String doGetHttps(String url,Map<String, String> headers) throws Exception {
        Properties proxy = null;
        if (isProxy){
            proxy = Proxy.getInstance(host, port).setUpAgent();
        }
        URL restServiceURL = new URL(url);
        logger.info("####" + DateUtils.format(new Date(), DateUtils.DATE_TIME) + "请求OTC接口URL" + url);
        System.setProperty("jsse.enableSNIEXtension", "false");
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        HttpsURLConnection httpConnection = (HttpsURLConnection) restServiceURL.openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.setConnectTimeout(5000);
        httpConnection.setReadTimeout(8000);
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("Accept-Charset", CHARSET);
        httpConnection.setSSLSocketFactory(ssf);
        addheaders(httpConnection,headers);
        try {
            if (httpConnection.getResponseCode() != 200) {
                System.out.println("响应错误,代码: " + httpConnection.getResponseCode() + ",信息: " + httpConnection.getResponseMessage());
                throw new RuntimeException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
            }
        } catch (SocketTimeoutException e) {
            System.out.println("读取响应超时,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage() + ",异常信息: " + e.getMessage());
            throw new SocketTimeoutException("读取响应超时,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage());
        }
        BufferedReader responseBuffer = null;
        for (int i = 0; i < TIMEOUT_COUNT; i++) {
            try {
                responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), "UTF-8"));
                break;
            } catch (SocketTimeoutException e) {
                System.out.println("读取响应超时,重新读取,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new SocketTimeoutException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new Exception(e.getMessage());
                }
            }
        }
        StringBuffer result = new StringBuffer();
        String output = "";
        while (null != (output = responseBuffer.readLine())) {
            result.append(output);
        }
        responseBuffer.close();
        httpConnection.disconnect();
        if (null == result || "".equals(result)) {
            throw new Exception();
        }
        if (isProxy){
            if (proxy!=null){
                Proxy.getInstance(host,port).removeProxy(proxy);
            }
        }
        return result.toString();
    }
    /**
     * 发送http请求-添加签名desSign参数---放篡改
     *
     * @param url
     * @param headers  头变量,无null
     * @param param  参数
     * @param password  签名密码-8位
     * @return
     * @throws Exception
     */
    public String doPostHttp(String url,Map<String, Object> param,Map<String, String> headers,String password) throws Exception {
        Properties proxy = null;
        if (isProxy){
            proxy = Proxy.getInstance(host, port).setUpAgent();
        }
        URL restServiceURL = new URL(url);
        StringBuffer params = new StringBuffer();
        if (param != null && param.size() > 0) {
            Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> element = it.next();
                params.append((String) element.getKey()).append("=").append(element.getValue()).append("&");
            }
            if (params.length() > 0) {
                if (StringUtils.isNotBlank(password)&&password.trim().length()==8){
                    String sign = DES.getInstance().encryptDes(params.toString(),password.trim());////参数DES签名加密处理,防止篡改
                    params.append("desSign=" + sign);
                }
            }
        }
        logger.info(url + "\n\t原始数据---" + param + "\n\t格式化后数据---" + params);
        HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(200000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setRequestProperty("Accept-Charset", CHARSET);
        addheaders(httpConnection,headers);
        //httpConnection.setRequestProperty("Accept", "text/json");
        PrintWriter printWriter = null;
        for (int i = 1; i <= TIMEOUT_COUNT; i++) {
            try {
                printWriter = new PrintWriter(new OutputStreamWriter(httpConnection.getOutputStream(), CHARSET));
                printWriter.write(params.toString());
                break;
            } catch (ConnectException e) {
                logger.error("连接超时,重新连接,次数: " + (i) + ",异常信息: " + e.getMessage());
                if (i == TIMEOUT_COUNT) {
                    throw new ConnectException("连接超时,次数已用完,次数: " + (i) + ",异常信息: " + e.getMessage());
                }
            } catch (SocketTimeoutException e) {
                logger.error("请求超时,重新请求,次数: " + (i) + ",异常信息: " + e.getMessage());
                if (i == TIMEOUT_COUNT) {
                    throw new SocketTimeoutException("请求超时,次数已用完,请求次数: " + (i) + ",异常信息: " + e.getMessage());
                }
            } catch (Exception e) {
                logger.error("", e);
                if (i == TIMEOUT_COUNT) {
                    throw e;
                }
            } finally {
                if (printWriter != null) {
                    printWriter.flush();
                    printWriter.close();
                }
            }
        }
        for (int i = 1; i <= TIMEOUT_COUNT; i++) {
            try {
                if (httpConnection.getResponseCode() != 200) {
                    logger.error("响应错误,代码: " + httpConnection.getResponseCode() + ",信息: " + httpConnection.getResponseMessage());
                    if (i == TIMEOUT_COUNT) {
                        throw new RuntimeException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
                    }
                    Thread.sleep(2000);
                }
            } catch (SocketTimeoutException e) {
                logger.error("读取响应超时,重新读取,次数: " + (i) + ",响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage() + ",异常信息: " + e.getMessage(), e);
                if (i == TIMEOUT_COUNT) {
                    throw new SocketTimeoutException("读取响应超时,次数已用完,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage());
                }
                Thread.sleep(2000);
            }
        }

        BufferedReader responseBuffer = null;

        for (int i = 1; i <= TIMEOUT_COUNT; i++) {
            try {
                responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), CHARSET));
                break;
            } catch (SocketTimeoutException e) {
                logger.error("读取响应超时,重新读取,次数: " + (i) + ",异常信息: " + e.getMessage(), e);
                if (i == TIMEOUT_COUNT) {
                    throw new SocketTimeoutException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
                }
            } catch (Exception e) {
                logger.error("", e);
                if (i == TIMEOUT_COUNT) {
                    throw e;
                }
            }
        }
        StringBuffer result = new StringBuffer();
        String output = "";
        logger.debug("Output from timedtask Server:  \n");
        while ((output = responseBuffer.readLine()) != null) {
            logger.info(output);
            result.append(output);
        }
        if (responseBuffer != null) {
            responseBuffer.close();
        }
        httpConnection.disconnect();
        if (null == result || "".equals(result)) {
            throw new Exception("系统错误或请求超时,请稍后再试");
        }
        if (isProxy){
            if (proxy!=null){
                Proxy.getInstance(host,port).removeProxy(proxy);
            }
        }
        return result.toString();
    }

    /**
     * 发送https请求-添加签名desSign参数---放篡改
     *
     * @param url
     * @param headers  头变量,无null
     * @param param  参数
     * @param password  签名密码-8位
     * @return
     * @throws Exception
     */
    public String doPostHttps(String url,Map<String, Object> param,Map<String, String> headers,String password) throws Exception {
        Properties proxy = null;
        if (isProxy){
            proxy = Proxy.getInstance(host, port).setUpAgent();
        }
        URL restServiceURL = new URL(url);
        StringBuffer params = new StringBuffer();
        if (param != null && param.size() > 0) {
            Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> element = it.next();
                params.append(element.getKey()).append("=").append(element.getValue()).append("&");
            }
            if (params.length() > 0) {
                if (StringUtils.isNotBlank(password) && password.trim().length()==8){
                    String sign = DES.getInstance().encryptDes(params.toString(),password.trim());
                    params.append("desSign=" + sign);
                }
            }
        }
        logger.info(url + "\n\t原始数据---" + param + "\n\t格式化后数据---" + params);
        System.setProperty("jsse.enableSNIEXtension", "false");
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        HttpsURLConnection httpConnection = (HttpsURLConnection) restServiceURL.openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(500000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setRequestProperty("Accept-Charset", CHARSET);
        httpConnection.setSSLSocketFactory(ssf);
        PrintWriter printWriter = null;
        addheaders(httpConnection,headers);
        for (int i = 0; i < TIMEOUT_COUNT; i++) {
            try {
                printWriter = new PrintWriter(new OutputStreamWriter(httpConnection.getOutputStream(), CHARSET));
                printWriter.write(params.toString());
                break;
            } catch (ConnectException e) {
                logger.error("连接超时,重新连接,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new ConnectException("连接超时,重新连接,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
                }
            } catch (SocketTimeoutException e) {
                logger.error("请求超时,重新请求,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new SocketTimeoutException("请求超时,请求次数: " + (i + 1) + ",异常信息: " + e.getMessage());
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new Exception(e.getMessage());
                }
            } finally {
                if (printWriter != null) {
                    printWriter.flush();
                    printWriter.close();
                }
            }
        }
        for (int i = 0; i < TIMEOUT_COUNT; i++) {
            try {
                if (httpConnection.getResponseCode() != 200) {
                    logger.error("响应错误,代码: " + httpConnection.getResponseCode() + ",信息: " + httpConnection.getResponseMessage());
                    if (i == TIMEOUT_COUNT - 1) {
                        throw new RuntimeException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
                    }
                    Thread.sleep(2000);
                }
            } catch (SocketTimeoutException e) {
                logger.error("读取响应超时,重新读取,次数: " + (i + 1) + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage() + ",异常信息: " + e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new SocketTimeoutException("读取响应超时,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage());
                }
                Thread.sleep(2000);
            }
        }
        BufferedReader responseBuffer = null;
        for (int i = 0; i < TIMEOUT_COUNT; i++) {
            try {
                responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), CHARSET));
                break;
            } catch (SocketTimeoutException e) {
                logger.error("读取响应超时,重新读取,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new SocketTimeoutException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                if (i == TIMEOUT_COUNT - 1) {
                    throw new Exception(e.getMessage());
                }
            }
        }
        StringBuffer result = new StringBuffer();
        String output = "";
        logger.debug("Output from timedtask Server:  \n");
        while ((output = responseBuffer.readLine()) != null) {
            logger.info(output);
            result.append(output);
        }
        if (responseBuffer != null) {
            responseBuffer.close();
        }
        httpConnection.disconnect();
        if (null == result || "".equals(result)) {
            throw new Exception("系统错误或请求超时,请稍后再试");
        }
        if (isProxy){
            if (proxy!=null){
                Proxy.getInstance(host,port).removeProxy(proxy);
            }
        }
        return result.toString();
    }


    private void addheaders(HttpsURLConnection httpConnection, Map<String, String> headers) {
        if(headers==null){
            return;
        }
        for (Map.Entry<String,String> header:headers.entrySet()) {
            httpConnection.addRequestProperty(header.getKey(),header.getValue());
        }
    }

    private void addheaders(HttpURLConnection httpConnection, Map<String, String> headers) {
        if(headers==null){
            return;
        }
        for (Map.Entry<String,String> header:headers.entrySet()) {
            httpConnection.addRequestProperty(header.getKey(),header.getValue());
        }
    }

}


    /**
     * 代理上网
     * 使用:
     * 获取连接前--Properties proxy = Proxy.getInstance(host,port).setUpAgent();
     * 返回数据前--Proxy.getInstance(host,port).removeProxy(proxy);
     *
     *
     * @author: vander
     * @create: 2018/12/11 10:56
     */
    public class Proxy {
    
        private String host;
        private String port;
    
        private Proxy(String host, String port){
            this.host = host;
            this.port = port;
        }
        public static Proxy getInstance(String host, String port){
            return new Proxy(host,port);
        }
        public Properties setUpAgent(){
            Properties properties = System.getProperties();
            properties.setProperty("http.proxySet","true");
            properties.setProperty("http.proxyHost",host);
            properties.setProperty("http.proxyPort",port);
            properties.setProperty("https.proxyHost",host);
            properties.setProperty("https.proxyPort",port);
            return properties;
        }
        public void removeProxy(Properties proxy){
            proxy.remove("http.proxyHost");
            proxy.remove("http.proxyHost");
            proxy.remove("https.proxyHost");
            proxy.remove("https.proxyHost");
        }
    }

获取IP地址

依赖pom.xml

配置源码

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * ip
 * 
 * 
 * @author vander
 * @date 2018年11月28日
 */
public class IPUtils {

	/**
	 * 获取IP地址
	 * 
	 * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
	 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
    	String ip = null;
        ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
//        //使用代理,则获取第一个IP地址
//        if(StringUtils.isEmpty(ip) && ip.length() > 15) {
//			if(ip.indexOf(",") > 0) {
//				ip = ip.substring(0, ip.indexOf(","));
//			}
//		}
        return ip;
    }
}

Cookie

依赖pom.xml

配置源码

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Cookie工具类
 *
 * @author vander
 * @date 2018年11月15日
 */
public class CookieUtil {

    /**
     * 设置cookie
     *
     * @param response
     * @param name     cookie名字
     * @param value    cookie值
     * @param maxAge   cookie生命周期 以秒为单位
     */
    public static void addCookie(HttpServletResponse response,String domain,String path, String name,
                                 String value, int maxAge,boolean httpOnly) {
        Cookie cookie = new Cookie(name, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        cookie.setHttpOnly(httpOnly);
        response.addCookie(cookie);
    }



    /**
     * 根据cookie名称读取cookie
     * @param request
     * @param cookieName1,cookieName2
     * @return map<cookieName,cookieValue>
     */

    public static Map<String,String> readCookie(HttpServletRequest request,String ... cookieNames) {
        Map<String,String> cookieMap = new HashMap<String,String>();
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String cookieName = cookie.getName();
                    String cookieValue = cookie.getValue();
                    for(int i=0;i<cookieNames.length;i++){
                        if(cookieNames[i].equals(cookieName)){
                            cookieMap.put(cookieName,cookieValue);
                        }
                    }
                }
            }
        return cookieMap;

    }
}

日期时间

依赖pom.xml

配置源码

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 日期处理
 * 
 * 
 * @author vander
 * @date 2018年12月1日
 */
public class DateUtils {

	/** 时间格式(yyyy-MM-dd) */
	public final static String DATE = "yyyy-MM-dd";
	/** 时间格式(HH:mm:ss) */
	public final static String TIME = "HH:mm:ss";
	/** 时间格式(yyyy-MM-dd HH:mm:ss) */
	public final static String DATE_TIME = "yyyy-MM-dd HH:mm:ss";
	
	private static ThreadLocal<SimpleDateFormat> threadLocal= new  ThreadLocal<SimpleDateFormat>();
 
	private static SimpleDateFormat getSimpleDateFormat(String pattern) {
		SimpleDateFormat dateFormat = threadLocal.get();
		if(dateFormat == null) {
			dateFormat = new SimpleDateFormat(pattern);
			threadLocal.set(dateFormat);
		}
		return dateFormat;
	}

	public static String format(Date date, String pattern) throws ParseException {
		return getSimpleDateFormat(pattern).format(date);
	}
	
	public static Date parse(String date, String pattern) throws ParseException {
		return getSimpleDateFormat(pattern).parse(date);
	}
	
	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for(int i = 0;i<100;i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					try {
						Date parse =DateUtils.parse("2019-03-"+new Random().nextInt(31), DateUtils.DATE);
						DateUtils.format(parse, DateUtils.DATE);
						System.err.println(Thread.currentThread().getName()+":"+parse);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			});
		}
		ExecutorService executorService1 = Executors.newFixedThreadPool(3);
		for(int i = 0;i<100;i++) {
			executorService1.execute(new Runnable() {
				@Override
				public void run() {
					try {
						Date parse = DateUtils.parse("2019-04-"+new Random().nextInt(30), DateUtils.DATE);
						System.err.println(Thread.currentThread().getName()+":"+parse);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			});
		}
		executorService.shutdown();
		executorService1.shutdown();
	}
}

数据库操作

单数据链接操作

依赖pom.xml

<dependency>
	<groupId>commons-dbutils</groupId>
	<artifactId>commons-dbutils</artifactId>
</dependency>

配置源码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

public class DbUtil {

	private static final QueryRunner runner = new QueryRunner();

	/* 打开数据库连接(type: MySQL,Oracle,SQLServer) */
	public static Connection openConn(String type, String host, String port, String name, String username,
			String password) {
		Connection conn = null;
		try {
			String driver;
			String url;
			if (type.equalsIgnoreCase("MySQL")) {
				driver = "com.mysql.jdbc.Driver";
				url = "jdbc:mysql://" + host + ":" + port + "/" + name;
			} else if (type.equalsIgnoreCase("Oracle")) {
				driver = "oracle.jdbc.driver.OracleDriver";
				url = "jdbc:oracle:thin:@" + host + ":" + port + ":" + name;
			} else if (type.equalsIgnoreCase("SQLServer")) {
				driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
				url = "jdbc:sqlserver://" + host + ":" + port + ";databaseName=" + name;
			} else {
				throw new RuntimeException();
			}
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	/* 关闭数据库连接 */
	public static void closeConn(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/* 查询(返回Array结果) */
	public static Object[] queryArray(Connection conn, String sql, Object... params) {
		Object[] result = null;
		try {
			result = runner.query(conn, sql, new ArrayHandler(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 查询(返回ArrayList结果) */
	public static List<Object[]> queryArrayList(Connection conn, String sql, Object... params) {
		List<Object[]> result = null;
		try {
			result = runner.query(conn, sql, new ArrayListHandler(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 查询(返回Map结果) */
	public static Map<String, Object> queryMap(Connection conn, String sql, Object... params) {
		Map<String, Object> result = null;
		try {
			result = runner.query(conn, sql, new MapHandler(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 查询(返回MapList结果) */
	public static List<Map<String, Object>> queryMapList(Connection conn, String sql, Object... params) {
		List<Map<String, Object>> result = null;
		try {
			result = runner.query(conn, sql, new MapListHandler(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 查询(返回Bean结果) */
	public static <T> T queryBean(Class<T> cls, Map<String, String> map, Connection conn, String sql,
			Object... params) {
		T result = null;
		try {
			if (map != null) {
				result = runner.query(conn, sql, new BeanHandler<T>(cls, new BasicRowProcessor(new BeanProcessor(map))),
						params);
			} else {
				result = runner.query(conn, sql, new BeanHandler<T>(cls), params);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 查询(返回BeanList结果) */
	public static <T> List<T> queryBeanList(Class<T> cls, Map<String, String> map, Connection conn, String sql,
			Object... params) {
		List<T> result = null;
		try {
			if (map != null) {
				result = runner.query(conn, sql,
						new BeanListHandler<T>(cls, new BasicRowProcessor(new BeanProcessor(map))), params);
			} else {
				result = runner.query(conn, sql, new BeanListHandler<T>(cls), params);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 查询指定列名的值(单条数据) */
	public static <T> T queryColumn(String column, Connection conn, String sql, Object... params) {
		T result = null;
		try {
			result = runner.query(conn, sql, new ScalarHandler<T>(column), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 查询指定列名的值(多条数据) */
	public static <T> List<T> queryColumnList(String column, Connection conn, String sql, Object... params) {
		List<T> result = null;
		try {
			result = runner.query(conn, sql, new ColumnListHandler<T>(column), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 查询指定列名对应的记录映射 */
	public static <T> Map<T, Map<String, Object>> queryKeyMap(String column, Connection conn, String sql,
			Object... params) {
		Map<T, Map<String, Object>> result = null;
		try {
			result = runner.query(conn, sql, new KeyedHandler<T>(column), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/* 更新(包括UPDATE、INSERT、DELETE,返回受影响的行数) */
	public static int update(Connection conn, String sql, Object... params) {
		int result = 0;
		try {
			result = runner.update(conn, sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
}

DES对称加密

依赖pom.xml

配置源码

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 * DES对称加密工具类
 * 
 * @author vander
 *
 */
public class DESUtil {
	
	public static void main(String[] args) throws Exception {
		String decrypt = DESUtil.encrypt("dawdadawdeq2eqfqrqfaa", "111", "dawdawfa");
		System.err.println(decrypt);
		System.err.println(DESUtil.decrypt("4217bec4984f5e2178b8483f5d4e60270886e08120a91dae", "111", "dawdawfa"));
	}
	
	private final static String charset = "UTF-8";

	/**
	 * JAVA6支持以下任意一种算法 PBEWITHMD5ANDDES PBEWITHMD5ANDTRIPLEDES
	 * PBEWITHSHAANDDESEDE PBEWITHSHA1ANDRC2_40 PBKDF2WITHHMACSHA1
	 * */

	/**
	 * PBEWithMD5AndDES
	 * 定义使用的算法为:PBEWITHMD5andDES算法
	 */
	private static final String ALGORITHM = "PBEWithMD5AndDES";//加密算法

	/**
	 * 定义迭代次数为1000次
	 */
	private static final int ITERATIONCOUNT = 1000;

	/**
	 * 根据PBE密码生成一把密钥
	 * 
	 * @param password
	 *            生成密钥时所使用的密码
	 * @return Key PBE算法密钥
	 * */
	private static Key getPBEKey(String password) {
		// 实例化使用的算法
		SecretKeyFactory keyFactory;
		SecretKey secretKey = null;
		try {
			keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
			// 设置PBE密钥参数
			PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
			// 生成密钥
			secretKey = keyFactory.generateSecret(keySpec);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return secretKey;
	}

	/**
	 * 加密
	 * 
	 * @param plaintext  原文
	 * @param password 密码
	 * @param salt 盐  需要8个字符
	 * @return 密文
	 * @throws Exception 加密失败抛出异常
	 */
	public static String encrypt(String plaintext, String password, String salt) throws Exception{
		Key key = getPBEKey(password);
		byte[] encipheredData = null;
		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.substring(0, 8).getBytes(charset), ITERATIONCOUNT);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
		encipheredData = cipher.doFinal(plaintext.getBytes());
		return bytesToHexString(encipheredData);
	}

	/**
	 * 解密
	 * 
	 * @param ciphertext 密文
	 * @param password 密码
	 * @param salt 盐  需要8个字符
	 * @return 原文
	 * @throws Exception
	 */
	public static String decrypt(String ciphertext, String password, String salt) throws Exception {
		Key key = getPBEKey(password);
		byte[] passDec = null;
		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.substring(0, 8).getBytes(charset), ITERATIONCOUNT);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
		passDec = cipher.doFinal(hexStringToBytes(ciphertext));
		return new String(passDec);
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * 
	 * @param src
	 *            字节数组
	 * @return
	 */
	private static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * 将十六进制字符串转换为字节数组
	 * 
	 * @param hexString
	 *            十六进制字符串
	 * @return
	 */
	private static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
}

AES对称加密

依赖pom.xml

配置源码

/**
 * AES对称加密
 * 
 * @author vander
 * @Date 2019年3月29日
 */
public class AESUtil {
	public static final String sqlkey = "xBgGIoUx7SqtrC1KJHRA5Q==";
	public static void main(String[] args) throws Exception {
		String sql = "delete * from tx_jfinal_excel_test1 where 1=1";
		String encryptAES = encryptAES(sql, sqlkey);
		String encode = URLEncoder.encode(encryptAES, "utf-8");
		System.err.println(encode);
	}
	private static String byte2base64(byte[] bytes){
		return Base64Kit.encode(bytes);
	}
	private static byte[] base642byte(String base64) throws IOException{
		return Base64Kit.decode(base64);
	}
	/**
	* 加密
	* 
	* @param source
	* @param aesKeyStr
	* @return
	* @throws Exception
	*/
	public static String encryptAES(String source,String aesKeyStr)throws Exception{
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, loadKeyAES(aesKeyStr));
		byte[] bytes = cipher.doFinal(source.getBytes());
		return byte2base64(bytes);
	}
	/**
	* 解密
	* 
	* @param source
	* @param key
	* @return
	* @throws Exception
	*/
	public static String decryptAES(String aesEnStr,String key) throws Exception{
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, loadKeyAES(key));
		byte[] bytes = cipher.doFinal(base642byte(aesEnStr));
		return new String(bytes);
	}
	private static SecretKey loadKeyAES(String base64Key) throws Exception{
		byte[] bytes = base642byte(base64Key);
		SecretKey key = new SecretKeySpec(bytes, "AES");
		return key;
	}
	
	/**
	* 获取密钥
	* 
	* @return
	* @throws Exception
	*/
	public static String genKeyAES() throws Exception{
		KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		keyGen.init(128);
		SecretKey key = keyGen.generateKey();
		String base64Str = byte2base64(key.getEncoded());
		return base64Str;
	}
}
原文:https://github.com/yangchenjava/com.yangc.utils cache EhCacheUtils - 基于ehcache的工具类 LruCacheUtils - 基于LinkedHashMap实现LRU缓存的工具类 MemcachedUtils - 基于memcached的工具类 RedisUtils - 基于redis的工具类,与redis的集群配置无缝结合 db JdbcUtils - 操作jdbc的工具类 MongodbUtils - 操作mongodb的工具类 email EmailUtils - 邮件工具类,支持发送带附件的邮件 encryption AesUtils - 实现AES加密解密 Base64Utils - 实现Base64加密解密 Md5Utils - 获取字符串或文件的md5 excel ReadExcel2003 - 以model方式读2003版Excel(大数据) ReadExcel2007 - 以sax方式读2007版Excel(大数据) WriteExcel - 写Excel image CaptchaUtils - 生成验证码 ImageUtils - 图片压缩、截图 QRCodeUtils - 生成二维码、解析二维码 io SerializeUtils - 序列化、反序列化对象 ZipUtils - 压缩、解压文件 json JsonUtils - json格式转换 lang CharsetDetectorUtils - 获取文本文件编码格式 ChineseCalendar - 农历日历 ConvertUtils - 高低字节转换 DateUtils - 日期工具类 HtmlFilterUtils - 过滤html标签 JsoupUtils - 基于jsoup过滤html标签 MoneyUtils - 获取大写金额 NumberUtils - 数字工具类 PinyinUtils - 汉字转拼音 media MediaUtils - 基于ffmpeg,qtfaststart,yamdi的多媒体工具类 net AttachmentUtils - HTTP文件下载防止中文乱码 FastDFSUtils - 操作FastDFS的工具类 FtpUtils - 操作FTP的工具类(基于sun自家的包,jdk7以后不建议使用) FtpUtilsApache - 基于apache操作FTP的工具类 HttpUtils - 发送HTTP请求 IpUtils - 获取IP SFtpUtils - 操作SFTP的工具类 prop PropertiesUtils - 操作properties配置文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值