2018-03-29

Java中常用工具类

(1)生成随机ID和随机码-UUIDUtils

package com.chuang.utils;

import java.util.UUID;

public class UUIDUtils {
    /**
     * 随机生成id
     * @return
     */
    public static String getId(){
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }
    
    /**
     * 生成随机码
     * @return
     */
    public static String getCode(){
        return getId();
    }
    
    public static void main(String[] args) {
        System.out.println(getId());
    }
}

(2)生成随机验证码-带有干扰线效果-VerifyCode

package com.chuang.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {
    private int w = 70;
    private int h = 35;
    private Random r = new Random();
    // {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
    private String[] fontNames  = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
    private String codes  = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    private Color bgColor  = new Color(255, 255, 255);
    private String text ;
    
    private Color randomColor () {
        int red = r.nextInt(150);
        int green = r.nextInt(150);
        int blue = r.nextInt(150);
        return new Color(red, green, blue);
    }
    
    private Font randomFont () {
        int index = r.nextInt(fontNames.length);
        String fontName = fontNames[index];
        int style = r.nextInt(4);
        int size = r.nextInt(5) + 24; 
        return new Font(fontName, style, size);
    }
    
    private void drawLine (BufferedImage image) {
        int num  = 3;
        Graphics2D g2 = (Graphics2D)image.getGraphics();
        for(int i = 0; i < num; i++) {
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h); 
            g2.setStroke(new BasicStroke(1.5F)); 
            g2.setColor(Color.BLUE); 
            g2.drawLine(x1, y1, x2, y2);
        }
    }
    
    private char randomChar () {
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }
    
    private BufferedImage createImage () {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 
        Graphics2D g2 = (Graphics2D)image.getGraphics(); 
        g2.setColor(this.bgColor);
        g2.fillRect(0, 0, w, h);
        return image;
    }
    
    public BufferedImage getImage () {
        BufferedImage image = createImage(); 
        Graphics2D g2 = (Graphics2D)image.getGraphics();
        StringBuilder sb = new StringBuilder();
        // 向图片中画4个字符
        for(int i = 0; i < 4; i++)  {
            String s = randomChar() + ""; 
            sb.append(s); 
            float x = i * 1.0F * w / 4; 
            g2.setFont(randomFont()); 
            g2.setColor(randomColor()); 
            g2.drawString(s, x, h-5); 
        }
        this.text = sb.toString(); 
        drawLine(image); 
        return image;       
    }
    
    public String getText () {
        return text;
    }
    
    public static void output (BufferedImage image, OutputStream out) 
                throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}

(3)邮件发送工具-MailUtils

package com.chuang.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {

    public static void sendMail(String email, String emailMsg)
            throws AddressException, MessagingException {
        // 1.创建一个程序与邮件服务器会话对象 Session

        Properties props = new Properties();
        //设置发送的协议
        props.setProperty("mail.transport.protocol", "SMTP");
        
        //设置发送邮件的服务器
        props.setProperty("mail.host", "smtp.163.com");
        props.setProperty("mail.smtp.auth", "true");// 指定验证为true

        // 创建验证器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //设置发送人的帐号和密码
                return new PasswordAuthentication("[email protected]", "ljc04172530");
            }
        };

        Session session = Session.getInstance(props, auth);

        // 2.创建一个Message,它相当于是邮件内容
        Message message = new MimeMessage(session);

        //设置发送者
        message.setFrom(new InternetAddress("[email protected]"));

        //设置发送方式与接收者
        message.setRecipient(RecipientType.TO, new InternetAddress(email)); 

        //设置邮件主题
        message.setSubject("用户激活");
         
        //设置邮件内容
        message.setContent(emailMsg, "text/html;charset=utf-8");

        // 3.创建 Transport用于将邮件发送
        Transport.send(message);
    }
}

(4)支持事务的数据库连接获取工具-DataSourceUtils

package com.chuang.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {
    private static ComboPooledDataSource ds=new ComboPooledDataSource();
    private static ThreadLocal tl=new ThreadLocal<>();
    
    /**
     * 获取数据源
     * @return 连接池
     */
    public static DataSource getDataSource(){
        return ds;
    }
    
    /**
     * 从线程中获取连接
     * @return 连接
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException{
        Connection conn = tl.get();
        //若是第一次获取 需要从池中获取一个连接,将这个连接和当前线程绑定
        if(conn==null){
            conn=ds.getConnection();
            
            //将这个连接和当前线程绑定
            tl.set(conn);
        }
        
        return conn;
    }
    
    
    
    /**
     * 释放资源
     * 
     * @param conn
     *            连接
     * @param st
     *            语句执行者
     * @param rs
     *            结果集
     */
    public static void closeResource(Connection conn, Statement st, ResultSet rs) {
        closeResultSet(rs);
        closeStatement(st);
        closeConn(conn);
    }

    /**
     * 释放连接
     * 
     * @param conn
     *            连接
     */
    public static void closeConn(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
                //和当前线程解绑
                tl.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }

    }

    /**
     * 释放语句执行者
     * 
     * @param st
     *            语句执行者
     */
    public static void closeStatement(Statement st) {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            st = null;
        }

    }

    /**
     * 释放结果集
     * 
     * @param rs
     *            结果集
     */
    public static void closeResultSet(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs = null;
        }

    }
    
    /**
     * 开始事务
     * @throws SQLException 
     */
    public static void startTransaction() throws SQLException{
        //1.获取连接
        Connection conn=getConnection();
        
        //2.开始
        conn.setAutoCommit(false);
    }
    
    /**
     * 事务提交
     */
    public static void commitAndClose(){
        try {
            //0.获取连接
            Connection conn = getConnection();
            
            //1.提交事务
            conn.commit();
            
            //2.关闭且移除
            closeConn(conn);
        } catch (SQLException e) {
        }
        
    }
    
    /**
     * 提交回顾
     */
    public static void rollbackAndClose(){
        try {
            //0.获取连接
            Connection conn = getConnection();
            
            //1.事务回顾
            conn.rollback();
            
            //2.关闭且移除
            closeConn(conn);
        } catch (SQLException e) {
        }
        
    }
}

使用c3p0连接池时所需的属性配置文件-c3p0.properties

c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/store38
c3p0.user=root
c3p0.password=admin

(5)文件上传工具-UploadUtils

package cn.chuang.utils;

import java.util.Random;
import java.util.UUID;

public class UploadUtils {
    /**
     * 获取文件真实名称
     * 由于浏览器的不同获取的名称可能为:c:/upload/1.jpg或者1.jpg 
     * 最终获取的为  1.jpg
     * @param name 上传上来的文件名称
     * @return  真实名称
     */
    public static String getRealName(String name){
        //获取最后一个"/"
        int index = name.lastIndexOf("\\");
        return name.substring(index+1);
    }
    
    
    /**
     * 获取随机名称
     * @param realName 真实名称
     * @return uuid 随机名称
     */
    public static String getUUIDName(String realName){
        //realname  可能是  1.jpg   也可能是  1
        //获取后缀名
        int index = realName.lastIndexOf(".");
        if(index==-1){
            return UUID.randomUUID().toString().replace("-", "").toUpperCase();
        }else{
            return UUID.randomUUID().toString().replace("-", "").toUpperCase()+realName.substring(index);
        }
    }
    
    
    /**
     * 获取文件目录,可以获取256个随机目录
     * @return 随机目录
     */
    public static String getDir(){
        String s="0123456789ABCDEF";
        Random r = new Random();
        return "/"+s.charAt(r.nextInt(16))+"/"+s.charAt(r.nextInt(16));
    }
    
    public static void main(String[] args) {
        //String s="G:\\day17-基础加强\\resource\\1.jpg";
        String s="1.jgp";
        String realName = getRealName(s);
        System.out.println(realName);
        
        String uuidName = getUUIDName(realName);
        System.out.println(uuidName);
        
        String dir = getDir();
        System.out.println(dir);
    }
}

(6)银行支付功能实现工具-PaymentUtils

package cn.chuang.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class PaymentUtil {

    private static String encodingCharset = "UTF-8";
    
    /**
     * 生成hmac方法
     * 
     * @param p0_Cmd 业务类型
     * @param p1_MerId 商户编号
     * @param p2_Order 商户订单号
     * @param p3_Amt 支付金额
     * @param p4_Cur 交易币种
     * @param p5_Pid 商品名称
     * @param p6_Pcat 商品种类
     * @param p7_Pdesc 商品描述
     * @param p8_Url 商户接收支付成功数据的地址
     * @param p9_SAF 送货地址
     * @param pa_MP 商户扩展信息
     * @param pd_FrpId 银行编码
     * @param pr_NeedResponse 应答机制
     * @param keyValue 商户密钥
     * @return
     */
    public static String buildHmac(String p0_Cmd,String p1_MerId,
            String p2_Order, String p3_Amt, String p4_Cur,String p5_Pid, String p6_Pcat,
            String p7_Pdesc,String p8_Url, String p9_SAF,String pa_MP,String pd_FrpId,
            String pr_NeedResponse,String keyValue) {
        StringBuilder sValue = new StringBuilder();
        // 业务类型
        sValue.append(p0_Cmd);
        // 商户编号
        sValue.append(p1_MerId);
        // 商户订单号
        sValue.append(p2_Order);
        // 支付金额
        sValue.append(p3_Amt);
        // 交易币种
        sValue.append(p4_Cur);
        // 商品名称
        sValue.append(p5_Pid);
        // 商品种类
        sValue.append(p6_Pcat);
        // 商品描述
        sValue.append(p7_Pdesc);
        // 商户接收支付成功数据的地址
        sValue.append(p8_Url);
        // 送货地址
        sValue.append(p9_SAF);
        // 商户扩展信息
        sValue.append(pa_MP);
        // 银行编码
        sValue.append(pd_FrpId);
        // 应答机制
        sValue.append(pr_NeedResponse);
        
        return PaymentUtil.hmacSign(sValue.toString(), keyValue);
    }
    
    /**
     * 返回校验hmac方法
     * 
     * @param hmac 支付网关发来的加密验证码
     * @param p1_MerId 商户编号
     * @param r0_Cmd 业务类型
     * @param r1_Code 支付结果
     * @param r2_TrxId 易宝支付交易流水号
     * @param r3_Amt 支付金额
     * @param r4_Cur 交易币种
     * @param r5_Pid 商品名称
     * @param r6_Order 商户订单号
     * @param r7_Uid 易宝支付会员ID
     * @param r8_MP 商户扩展信息
     * @param r9_BType 交易结果返回类型
     * @param keyValue 密钥
     * @return
     */
    public static boolean verifyCallback(String hmac, String p1_MerId,
            String r0_Cmd, String r1_Code, String r2_TrxId, String r3_Amt,
            String r4_Cur, String r5_Pid, String r6_Order, String r7_Uid,
            String r8_MP, String r9_BType, String keyValue) {
        StringBuilder sValue = new StringBuilder();
        // 商户编号
        sValue.append(p1_MerId);
        // 业务类型
        sValue.append(r0_Cmd);
        // 支付结果
        sValue.append(r1_Code);
        // 易宝支付交易流水号
        sValue.append(r2_TrxId);
        // 支付金额
        sValue.append(r3_Amt);
        // 交易币种
        sValue.append(r4_Cur);
        // 商品名称
        sValue.append(r5_Pid);
        // 商户订单号
        sValue.append(r6_Order);
        // 易宝支付会员ID
        sValue.append(r7_Uid);
        // 商户扩展信息
        sValue.append(r8_MP);
        // 交易结果返回类型
        sValue.append(r9_BType);
        String sNewString = PaymentUtil.hmacSign(sValue.toString(), keyValue);
        return sNewString.equals(hmac);
    }
    
    /**
     * @param aValue
     * @param aKey
     * @return
     */
    public static String hmacSign(String aValue, String aKey) {
        byte k_ipad[] = new byte[64];
        byte k_opad[] = new byte[64];
        byte keyb[];
        byte value[];
        try {
            keyb = aKey.getBytes(encodingCharset);
            value = aValue.getBytes(encodingCharset);
        } catch (UnsupportedEncodingException e) {
            keyb = aKey.getBytes();
            value = aValue.getBytes();
        }

        Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
        Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
        for (int i = 0; i < keyb.length; i++) {
            k_ipad[i] = (byte) (keyb[i] ^ 0x36);
            k_opad[i] = (byte) (keyb[i] ^ 0x5c);
        }

        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {

            return null;
        }
        md.update(k_ipad);
        md.update(value);
        byte dg[] = md.digest();
        md.reset();
        md.update(k_opad);
        md.update(dg, 0, 16);
        dg = md.digest();
        return toHex(dg);
    }

    public static String toHex(byte input[]) {
        if (input == null)
            return null;
        StringBuffer output = new StringBuffer(input.length * 2);
        for (int i = 0; i < input.length; i++) {
            int current = input[i] & 0xff;
            if (current < 16)
                output.append("0");
            output.append(Integer.toString(current, 16));
        }

        return output.toString();
    }

    /**
     * 
     * @param args
     * @param key
     * @return
     */
    public static String getHmac(String[] args, String key) {
        if (args == null || args.length == 0) {
            return (null);
        }
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < args.length; i++) {
            str.append(args[i]);
        }
        return (hmacSign(str.toString(), key));
    }

    /**
     * @param aValue
     * @return
     */
    public static String digest(String aValue) {
        aValue = aValue.trim();
        byte value[];
        try {
            value = aValue.getBytes(encodingCharset);
        } catch (UnsupportedEncodingException e) {
            value = aValue.getBytes();
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return toHex(md.digest(value));

    }
    
//  public static void main(String[] args) {
//      System.out.println(hmacSign("AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp杩?4564868265473632445648682654736324511","8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t"));
//  }
}

(7)Json格式数据处理工具-JsonUtils

package cn.chuang.utils;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.xml.XMLSerializer;

/**
 * 处理json数据格式的工具类
 * 
 * @Date 2013-3-31
 * @version 1.0
 */
public class JsonUtil {
    /**
     * 将数组转换成String类型的JSON数据格式
     * 
     * @param objects
     * @return
     */
    public static String array2json(Object[] objects){
        
        JSONArray jsonArray = JSONArray.fromObject(objects);
        return jsonArray.toString();
        
    }
    
    /**
     * 将list集合转换成String类型的JSON数据格式
     * 
     * @param list
     * @return
     */
    public static String list2json(List list){
        
        JSONArray jsonArray = JSONArray.fromObject(list);
        return jsonArray.toString();
        
    }
    
    /**
     * 将map集合转换成String类型的JSON数据格式
     * 
     * @param map
     * @return
     */
    public static String map2json(Map map){
        
        JSONObject jsonObject = JSONObject.fromObject(map);
        return jsonObject.toString();
        
    }
    
    /**
     * 将Object对象转换成String类型的JSON数据格式
     * 
     * @param object
     * @return
     */
    public static String object2json(Object object){
        
        JSONObject jsonObject = JSONObject.fromObject(object);
        return jsonObject.toString();
        
    }
    
    /**
     * 将XML数据格式转换成String类型的JSON数据格式
     * 
     * @param xml
     * @return
     */
    public static String xml2json(String xml){
        
        JSONArray jsonArray = (JSONArray) new XMLSerializer().read(xml);
        return jsonArray.toString();
        
    }
    
    /**
      * 除去不想生成的字段(特别适合去掉级联的对象)
      *
      * @param excludes
      * @return
    */
    public static JsonConfig configJson(String[] excludes) {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(excludes);
        jsonConfig.setIgnoreDefaultExcludes(true);
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        return jsonConfig;
    }
    
}

(8)Redis缓存方式获取数据库连接工具-JedisUtils

package cn.chuang.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtils {
    //创建连接池
    private static final JedisPoolConfig config;
    private static final JedisPool pool;
    
    static{
        config=new JedisPoolConfig();
        config.setMaxTotal(30);
        config.setMaxIdle(2);
        
        pool=new JedisPool(config, "192.168.17.136", 6379);
    }
    
    
    //获取连接的方法
    public static Jedis getJedis(){
        return pool.getResource();
    }
    
    
    //释放连接
    public static void closeJedis(Jedis j){
        if(j!=null){
            j.close();
        }
    }
}

(9)解耦合思想之工厂方式注入Service和Dao工具-BeanFactory

package cn.chuang.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 获取javabean的工厂
 * @author Administrator
 *
 */
public class BeanFactory {

    public static Object getBean(String id){
        try {
            //1.获取document对象
            Document doc=new SAXReader().read(BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml"));
            
            //2.调用api selectSingleNode(表达式)
            Element beanEle=(Element) doc.selectSingleNode("//bean[@id='"+id+"']");
            
            //3.获取元素的class属性
            String classValue = beanEle.attributeValue("class");
            
            //4.通过反射返回实现类的对象
            Object newInstance = Class.forName(classValue).newInstance();
            return newInstance;
        }  catch (Exception e) {
            e.printStackTrace();
            System.out.println("获取bean失败");
        }
        return null;
    }
    
    public static void main(String[] args) throws Exception {
        System.out.println(getBean("ProductDao1"));
    }
}

工厂类所需的配置文件-beans.xml(要放在src目录下,以便编译时加载到类路径中)



   
   
   
   
   
   
   
   
   

你可能感兴趣的:(2018-03-29)