Java中常用工具類
(1)生成隨機(jī)ID和隨機(jī)碼-UUIDUtils
package com.chuang.utils;
import java.util.UUID;
public class UUIDUtils {
/**
* 隨機(jī)生成id
* @return
*/
public static String getId(){
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
/**
* 生成隨機(jī)碼
* @return
*/
public static String getCode(){
return getId();
}
public static void main(String[] args) {
System.out.println(getId());
}
}
(2)生成隨機(jī)驗(yàn)證碼-帶有干擾線效果-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個(gè)字符
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)郵件發(fā)送工具-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.創(chuàng)建一個(gè)程序與郵件服務(wù)器會(huì)話對(duì)象 Session
Properties props = new Properties();
//設(shè)置發(fā)送的協(xié)議
props.setProperty("mail.transport.protocol", "SMTP");
//設(shè)置發(fā)送郵件的服務(wù)器
props.setProperty("mail.host", "smtp.163.com");
props.setProperty("mail.smtp.auth", "true");// 指定驗(yàn)證為true
// 創(chuàng)建驗(yàn)證器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//設(shè)置發(fā)送人的帳號(hào)和密碼
return new PasswordAuthentication("15637038571@163.com", "ljc04172530");
}
};
Session session = Session.getInstance(props, auth);
// 2.創(chuàng)建一個(gè)Message发绢,它相當(dāng)于是郵件內(nèi)容
Message message = new MimeMessage(session);
//設(shè)置發(fā)送者
message.setFrom(new InternetAddress("15637038571@163.com"));
//設(shè)置發(fā)送方式與接收者
message.setRecipient(RecipientType.TO, new InternetAddress(email));
//設(shè)置郵件主題
message.setSubject("用戶激活");
//設(shè)置郵件內(nèi)容
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.創(chuàng)建 Transport用于將郵件發(fā)送
Transport.send(message);
}
}
(4)支持事務(wù)的數(shù)據(jù)庫(kù)連接獲取工具-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<Connection> tl=new ThreadLocal<>();
/**
* 獲取數(shù)據(jù)源
* @return 連接池
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 從線程中獲取連接
* @return 連接
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
Connection conn = tl.get();
//若是第一次獲取 需要從池中獲取一個(gè)連接,將這個(gè)連接和當(dāng)前線程綁定
if(conn==null){
conn=ds.getConnection();
//將這個(gè)連接和當(dāng)前線程綁定
tl.set(conn);
}
return conn;
}
/**
* 釋放資源
*
* @param conn
* 連接
* @param st
* 語句執(zhí)行者
* @param rs
* 結(jié)果集
*/
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();
//和當(dāng)前線程解綁
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
/**
* 釋放語句執(zhí)行者
*
* @param st
* 語句執(zhí)行者
*/
public static void closeStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}
}
/**
* 釋放結(jié)果集
*
* @param rs
* 結(jié)果集
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}
/**
* 開始事務(wù)
* @throws SQLException
*/
public static void startTransaction() throws SQLException{
//1.獲取連接
Connection conn=getConnection();
//2.開始
conn.setAutoCommit(false);
}
/**
* 事務(wù)提交
*/
public static void commitAndClose(){
try {
//0.獲取連接
Connection conn = getConnection();
//1.提交事務(wù)
conn.commit();
//2.關(guān)閉且移除
closeConn(conn);
} catch (SQLException e) {
}
}
/**
* 提交回顧
*/
public static void rollbackAndClose(){
try {
//0.獲取連接
Connection conn = getConnection();
//1.事務(wù)回顧
conn.rollback();
//2.關(guān)閉且移除
closeConn(conn);
} catch (SQLException e) {
}
}
}
使用c3p0連接池時(shí)所需的屬性配置文件-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 {
/**
* 獲取文件真實(shí)名稱
* 由于瀏覽器的不同獲取的名稱可能為:c:/upload/1.jpg或者1.jpg
* 最終獲取的為 1.jpg
* @param name 上傳上來的文件名稱
* @return 真實(shí)名稱
*/
public static String getRealName(String name){
//獲取最后一個(gè)"/"
int index = name.lastIndexOf("\\");
return name.substring(index+1);
}
/**
* 獲取隨機(jī)名稱
* @param realName 真實(shí)名稱
* @return uuid 隨機(jī)名稱
*/
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個(gè)隨機(jī)目錄
* @return 隨機(jī)目錄
*/
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-基礎(chǔ)加強(qiáng)\\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)銀行支付功能實(shí)現(xiàn)工具-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 業(yè)務(wù)類型
* @param p1_MerId 商戶編號(hào)
* @param p2_Order 商戶訂單號(hào)
* @param p3_Amt 支付金額
* @param p4_Cur 交易幣種
* @param p5_Pid 商品名稱
* @param p6_Pcat 商品種類
* @param p7_Pdesc 商品描述
* @param p8_Url 商戶接收支付成功數(shù)據(jù)的地址
* @param p9_SAF 送貨地址
* @param pa_MP 商戶擴(kuò)展信息
* @param pd_FrpId 銀行編碼
* @param pr_NeedResponse 應(yīng)答機(jī)制
* @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();
// 業(yè)務(wù)類型
sValue.append(p0_Cmd);
// 商戶編號(hào)
sValue.append(p1_MerId);
// 商戶訂單號(hào)
sValue.append(p2_Order);
// 支付金額
sValue.append(p3_Amt);
// 交易幣種
sValue.append(p4_Cur);
// 商品名稱
sValue.append(p5_Pid);
// 商品種類
sValue.append(p6_Pcat);
// 商品描述
sValue.append(p7_Pdesc);
// 商戶接收支付成功數(shù)據(jù)的地址
sValue.append(p8_Url);
// 送貨地址
sValue.append(p9_SAF);
// 商戶擴(kuò)展信息
sValue.append(pa_MP);
// 銀行編碼
sValue.append(pd_FrpId);
// 應(yīng)答機(jī)制
sValue.append(pr_NeedResponse);
return PaymentUtil.hmacSign(sValue.toString(), keyValue);
}
/**
* 返回校驗(yàn)hmac方法
*
* @param hmac 支付網(wǎng)關(guān)發(fā)來的加密驗(yàn)證碼
* @param p1_MerId 商戶編號(hào)
* @param r0_Cmd 業(yè)務(wù)類型
* @param r1_Code 支付結(jié)果
* @param r2_TrxId 易寶支付交易流水號(hào)
* @param r3_Amt 支付金額
* @param r4_Cur 交易幣種
* @param r5_Pid 商品名稱
* @param r6_Order 商戶訂單號(hào)
* @param r7_Uid 易寶支付會(huì)員ID
* @param r8_MP 商戶擴(kuò)展信息
* @param r9_BType 交易結(jié)果返回類型
* @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();
// 商戶編號(hào)
sValue.append(p1_MerId);
// 業(yè)務(wù)類型
sValue.append(r0_Cmd);
// 支付結(jié)果
sValue.append(r1_Code);
// 易寶支付交易流水號(hào)
sValue.append(r2_TrxId);
// 支付金額
sValue.append(r3_Amt);
// 交易幣種
sValue.append(r4_Cur);
// 商品名稱
sValue.append(r5_Pid);
// 商戶訂單號(hào)
sValue.append(r6_Order);
// 易寶支付會(huì)員ID
sValue.append(r7_Uid);
// 商戶擴(kuò)展信息
sValue.append(r8_MP);
// 交易結(jié)果返回類型
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格式數(shù)據(jù)處理工具-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數(shù)據(jù)格式的工具類
*
* @Date 2013-3-31
* @version 1.0
*/
public class JsonUtil {
/**
* 將數(shù)組轉(zhuǎn)換成String類型的JSON數(shù)據(jù)格式
*
* @param objects
* @return
*/
public static String array2json(Object[] objects){
JSONArray jsonArray = JSONArray.fromObject(objects);
return jsonArray.toString();
}
/**
* 將list集合轉(zhuǎn)換成String類型的JSON數(shù)據(jù)格式
*
* @param list
* @return
*/
public static String list2json(List list){
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
}
/**
* 將map集合轉(zhuǎn)換成String類型的JSON數(shù)據(jù)格式
*
* @param map
* @return
*/
public static String map2json(Map map){
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject.toString();
}
/**
* 將Object對(duì)象轉(zhuǎn)換成String類型的JSON數(shù)據(jù)格式
*
* @param object
* @return
*/
public static String object2json(Object object){
JSONObject jsonObject = JSONObject.fromObject(object);
return jsonObject.toString();
}
/**
* 將XML數(shù)據(jù)格式轉(zhuǎn)換成String類型的JSON數(shù)據(jù)格式
*
* @param xml
* @return
*/
public static String xml2json(String xml){
JSONArray jsonArray = (JSONArray) new XMLSerializer().read(xml);
return jsonArray.toString();
}
/**
* 除去不想生成的字段(特別適合去掉級(jí)聯(lián)的對(duì)象)
*
* @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緩存方式獲取數(shù)據(jù)庫(kù)連接工具-JedisUtils
package cn.chuang.utils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisUtils {
//創(chuàng)建連接池
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對(duì)象
Document doc=new SAXReader().read(BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml"));
//2.調(diào)用api selectSingleNode(表達(dá)式)
Element beanEle=(Element) doc.selectSingleNode("http://bean[@id='"+id+"']");
//3.獲取元素的class屬性
String classValue = beanEle.attributeValue("class");
//4.通過反射返回實(shí)現(xiàn)類的對(duì)象
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目錄下沈条,以便編譯時(shí)加載到類路徑中)
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="ProductDao" class="cn.chuang.dao.impl.ProductDaoImpl"/>
<bean id="UserDao" class="cn.chuang.dao.impl.UserDaoImpl"/>
<bean id="CategoryDao" class="cn.chuang.dao.impl.CategoryDaoImpl"/>
<bean id="OrderDao" class="cn.chuang.dao.impl.OrderDaoImpl"/>
<bean id="ProductService" class="cn.chuang.service.impl.ProductServiceImpl"/>
<bean id="UserService" class="cn.chuang.service.impl.UserServiceImpl"/>
<bean id="CategoryService" class="cn.chuang.service.impl.CategoryServiceImpl"/>
<bean id="OrderService" class="cn.chuang.service.impl.OrderServiceImpl"/>
</beans>