Files
memberSystem/src/main/java/com/ifish/util/IfishUtil.java
T
2018-07-12 00:38:50 +08:00

356 lines
11 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.ifish.util;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.ifish.hibernate.Pagination;
import org.codehaus.jackson.type.JavaType;
public class IfishUtil {
private static final String formatDate = "yyyy-MM-dd HH:mm:ss";
private static final String formatDate1 = "yyyy-MM-dd";
/**
* Object转Json
*/
public static String ObjectToJson(Object value) {
try {
if (value == null) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
String js = mapper.writeValueAsString(value);
return js;
} catch (Exception ex) {
System.out.println("【异常信息】 >>> " + ex.toString());
return "Error";
}
}
/**
* 对象转Map
* @param obj
* @return
*/
public static Map<String,Object> objectToMap(Object obj){
Map<String,Object> map = new HashMap<String,Object>(1);
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(),field.get(obj));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return map;
}
/**
* Json转ObjectJavaBean
*
* @param json 需要转换的JSON字符串
* @param bean JavaBean,
* @return 拿到结果需要强转一次,因为你拿到的是Object, 例如这样调用和强转: School lst
* =(School)StringUtil.JsonToObjectList(value, School.class);
*/
public static Object JsonToBean(String json, Class<?> bean) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JavaType javaType = mapper.getTypeFactory().uncheckedSimpleType(bean);
return mapper.readValue(json, javaType);
}
/**
* 返回当前日期yyyy-MM-dd
*
* @return
* @throws ParseException
*/
public static Date getCurDate() {
DateFormat df = DateFormat.getDateInstance();
try {
return df.parse(df.format(new Date()));
} catch (ParseException e) {
}
return null;
}
/**
* 格式化日期yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String format(Date date) {
SimpleDateFormat format = new SimpleDateFormat(formatDate);
return format.format(date);
}
/**
* 格式化日期yyyy-MM-dd
*
* @param date
* @return
*/
public static String format1(Date date) {
SimpleDateFormat format = new SimpleDateFormat(formatDate1);
return format.format(date);
}
/**
* 生成编号
*
* @return
*/
public static String getCode() {
Calendar calendar = Calendar.getInstance();
String hexYear = String.format("%04d", calendar.get(Calendar.YEAR));
String hexMonth = String.format("%02d", (calendar.get(Calendar.MONTH) + 1));
String hexDate = String.format("%02d", calendar.get(Calendar.DATE));
String hexHours = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY));
String hexMinutes = String.format("%02d", calendar.get(Calendar.MINUTE));
String hexSeconds = String.format("%02d", calendar.get(Calendar.SECOND));
String millisecond = String.format("%03d", calendar.get(Calendar.MILLISECOND));
String code = "BH" + hexYear + hexMonth + hexDate + "_" + hexHours + hexMinutes + hexSeconds + millisecond;
return code;
}
/**
* 字符串转换成日期
*
* @param str
* @return date
*/
public static Date StrToDate(String str) {
SimpleDateFormat format = new SimpleDateFormat(formatDate1);
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 字符串转换成日期
*
* @param str
* @return date
*/
public static Date StrToDate1(String str) {
SimpleDateFormat format = new SimpleDateFormat(formatDate);
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
//返回时分秒的时间字符串
public static String TimestampToStringAndSecond(Object timestamp) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return (format.format(timestamp));
} catch (Exception e) {
System.out.println("【isGaokaoYearExpire 异常】:" + e);
return "";
}
}
/**
* 随机生成字母与数字组合
*
* @param length
* @return
*/
public static String getCharAndNumr(int length) {
String val = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
// 输出字母还是数字
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
// 字符串
if ("char".equalsIgnoreCase(charOrNum)) {
// 取得大写字母还是小写字母
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char) (choice + random.nextInt(26));
// 数字
} else if ("num".equalsIgnoreCase(charOrNum)) {
val += String.valueOf(random.nextInt(10));
}
}
return val;
}
/**
* MD5实现方法
*
* @param str
* @return
*/
public static String GetMD5(String str) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
e.printStackTrace();
return "";
}
char[] charArray = str.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++) {
byteArray[i] = (byte) charArray[i];
}
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 返回分页数据
* @return
*/
public static Object returnPageData(Pagination<?> page, String sEcho) {
Map<String, Object> map = new HashMap<String, Object>();
//实际的行数
map.put("iTotalRecords", page.getTotalCount());
//过滤之后,实际的行数。
map.put("iTotalDisplayRecords", page.getTotalCount());
//来自客户端,无变化
map.put("sEcho", sEcho);
//列名,可选
//map.put("sColumns", null);
//数据
map.put("aaData", page.getList());
return map;
}
/**
* 对字节数组字符串进行Base64解码并生成图片
*
* @param imgStr
* @return
*/
public static boolean GenerateImage(String imgStr, String imgName) {
if (imgStr == null || imgStr.equals("") || imgStr.contains("http")) {
return false;
}
Integer index = imgStr.indexOf(",") + 1;
imgStr = imgStr.substring(index, imgStr.length());
BASE64Decoder decoder = new BASE64Decoder();
FileOutputStream out = null;
try {
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
//生成png图片
String imgFilePath = IfishFileDirectory.path_img_vender + "/" + imgName;
File file = new File(imgFilePath);
//新生成的图片
out = new FileOutputStream(file);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
}
}
}
/**
* 图片转化成base64字符串
*
* @return
*/
public static String GetImageStr(String imgPath) {
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
//返回Base64编码过的字节数组字符串
return encoder.encode(data);
}
/**
* 生成微信分享页
* @return
*/
public static String getHtmlFile(String htmlName, String ueditorTitle, String ueditorContent) {
try {
if (ueditorTitle != null && !ueditorTitle.equals("")) {
//读取模板文件
FileInputStream fileinputstream = new FileInputStream(IfishFileDirectory.ueditor_path + htmlName);
int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
fileinputstream.close();
String templateContent = new String(bytes);
//替换掉模板中相应的地方
templateContent = templateContent.replaceAll("###ueditorTitle###", ueditorTitle);
templateContent = templateContent.replaceAll("###ueditorContent###", ueditorContent);
//根据时间得文件名
Calendar calendar = Calendar.getInstance();
String fileName = String.valueOf(calendar.getTimeInMillis());
fileName = fileName + ".html";
//建立文件输出流
FileOutputStream fileoutputstream = new FileOutputStream(IfishFileDirectory.ueditor_path + fileName);
byte tag_bytes[] = templateContent.getBytes();
fileoutputstream.write(tag_bytes);
fileoutputstream.close();
return fileName;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return "";
}
}