判断手机和PC 的工具类等

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.servlet.http.HttpServletRequest;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;


import com.c2bcms.app.components.file.FileType;
import com.c2bcms.app.components.file.FileTypeResolve;
import com.c2bcms.app.domain.entity.ApiException;
import com.c2bcms.app.domain.entity.AppConstant;
import com.c2bcms.app.utils.security.Md5Utils;


import sun.misc.BASE64Decoder;


/**
 * @author zheng 工具类
 */
public class BaseUtil {

public static boolean isMoblie(HttpServletRequest request) {
boolean isMoblie = false;
String[] mobileAgents = { "iphone", "android", "phone", "mobile", "wap", "netfront", "java", "opera mobi",
"opera mini", "ucweb", "windows ce", "symbian", "series", "webos", "sony", "blackberry", "dopod",
"nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma",
"docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos",
"techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem",
"wellcom", "bunjalloo", "maui", "smartphone", "iemobile", "spice", "bird", "zte-", "longcos", "pantech",
"gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320", "240x320",
"176x220", "w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac", "blaz",
"brew", "cell", "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs", "kddi",
"keji", "leno", "lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi", "mot-",
"moto", "mwbp", "nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port", "prox",
"qwap", "sage", "sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem", "smal",
"smar", "sony", "sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v", "voda",
"wap-", "wapa", "wapi", "wapp", "wapr", "webc", "winw", "winw", "xda", "xda-", "Googlebot-Mobile" };
if (request.getHeader("User-Agent") != null) {
for (String mobileAgent : mobileAgents) {
System.out.println(request.getHeader("User-Agent"));
if (request.getHeader("User-Agent").toLowerCase().indexOf(mobileAgent) >= 0 && !request.getHeader("User-Agent").contains("Windows")&& !request.getHeader("User-Agent").contains("Macintosh")) {
isMoblie = true;
break;
}
}
}
return isMoblie;
}


/**
* @return 唯一标识

*/
public static String getUniqueId() {
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return timeFormat.format(new Date()) + RandomUtils.nextInt(1000, 9999);
}


public static String randomString(int length) {
if (length < 1) {
return null;
}
Random randGen = null;
char[] numbersAndLetters = null;
if (randGen == null) {
randGen = new Random();
numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
.toCharArray();
}
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
}
return new String(randBuffer);
}


/**
* 创建32位GUID

* @return
*/
public static String createGuid() {
return UUID.randomUUID().toString().replace("-", "");
}


public static String filterJson(String json) {
if (!json.startsWith("({")) {
json = json.substring(json.indexOf("({"), json.length());
}
if (json.startsWith("(") && json.endsWith(")")) {
json = json.substring(1, json.length() - 1);
}
return json;
}


/**

* 获取两字符之间字符串

* @param str
* @param start
* @param end
* @return
*/
public static String getBetweenStr(String str, String start, String end) {
start = start.contains("(") ? start.replace("(", "\\(") : start;
end = end.contains(")") ? end.replace(")", "\\)") : end;
Matcher m = Pattern.compile(start + "(.*?)" + end).matcher(str);
while (m.find()) {
return m.group(1);
}
return "";
}


/**
* 根据身份证获取生日,返回格式:1990-01-01

* @param ID
* @return
*/
public static String getFormatBirthday(String ID) {
if (ID == null) {
throw new NullPointerException("ID must not be null");
}
String birthday = ID.substring(ID.length() - 12, ID.length() - 4);
birthday = birthday.substring(0, 4) + "-" + birthday.substring(4, 6) + "-"
+ birthday.substring(6, birthday.length());
return birthday;
}


/**
* 根据身份证获取生日,返回格式:0605

* @param ID
* @return
*/
public static String getBirthdayByID(String ID) {
if (ID == null) {
throw new NullPointerException("ID must not be null");
}
return ID.substring(ID.length() - 8, ID.length() - 4);
}


/**
* 根据身份证判断性别:1为男,0为女

* @param ID
* @return
*/
public static String getGenderByID(String ID) {
if (ID == null) {
throw new NullPointerException("ID must not be null");
}
String sex = ID.substring(16, 17);
return Integer.parseInt(sex) % 2 == 0 ? "0" : "1";
}


/**
* @param date
* @param format
* @return
*/
public static String dateFormat(Date date, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(date);
}


public static Date dateFormat(String dateStr, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
try {
return simpleDateFormat.parse(dateStr);
} catch (ParseException e) {
System.out.println("时间转换异常:" + e.getMessage());
return null;
}
}


public static Date toDate(String str) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(str);
} catch (ParseException e1) {
e1.printStackTrace();
}
return null;
}


/**
* 根据文件名获取文件对象

* @param filename
* @return
*/
public static File getFileByName(String filename) {
if (filename == null) {
throw new NullPointerException("filename must not be null");
}
String filePath = BaseUtil.class.getClassLoader().getResource(filename).getPath();
if (filePath.startsWith("/")) {
filePath = filePath.substring(1, filePath.length());
}
return new File(filePath);
}


/**
* 保留两位小数

* @param val
* @return
*/
public static BigDecimal toDecimal(Object val) {
if (null == val) {
return BigDecimal.valueOf(0);
}
BigDecimal ret = null;
if (val instanceof BigDecimal) {
ret = new BigDecimal(val.toString());
ret = ret.setScale(2, BigDecimal.ROUND_HALF_UP);
} else if (val instanceof String) {
ret = new BigDecimal((String) val);
} else if (val instanceof BigInteger) {
ret = new BigDecimal((BigInteger) val);
} else if (val instanceof Number) {
ret = new BigDecimal(((Number) val).doubleValue());
} else {
throw new ClassCastException(
"Not possible to coerce [" + val + "] from class " + val.getClass() + " into a BigDecimal.");
}
return ret;
}


public static Timestamp toTimestamp(Object val) {
return Timestamp.valueOf(val.toString());
}


public static Date toDate(Object val) {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
if (val instanceof Timestamp) {
return (Date) val;
}
return format.parse(val.toString());
} catch (ParseException e) {
e.printStackTrace();
return new Date();
}
}


/**
* @param obj
* @return yyyy/MM/dd HH:mm:ss
*/
public static String toDateString(Object obj) {
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format((Date) obj);
}


public static Boolean toBoolean(Object obj) {
return ((Boolean) obj).booleanValue();
}


public static String toString(Object obj) {
if (null == obj)
return "";
return obj.toString();
}


/**
* 判断字符串是否是整数
*/
public static boolean isInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}


public static Integer toInt(Object obj) {
if (null == obj)
return 0;
return Integer.valueOf(obj.toString());
}


/**
* 如果转化失败返回null

* @param str
* @return
*/
public static Integer toInt(String str) {
Integer num = null;
try {
num = str != null ? Integer.parseInt(str) : null;
} catch (NumberFormatException e) {
num = null;
}
return num;
}


public static Long toLong(Object obj) {
if (null == obj)
return (long) 0;
return Long.valueOf(obj.toString());
}


public static String excludeSqlInjection(String str) {
return str.replace("'", "");
}


public static boolean isNullOrEmpty(String val) {
if (null == val || StringUtils.isBlank(val)) {
return true;
}
return false;
}


public static boolean isNullOrEmpty(Object val) {
if (null == val || StringUtils.isBlank(val.toString())) {
return true;
}
return false;
}


/**
* 下载远程文件并保存到本地

* @param remoteFilePath
*            远程文件路径
* @param localFilePath
*            本地文件路径
*/
public static void downloadFile(String remoteFilePath, String localFilePath) {
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File f = new File(localFilePath);
try {
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


/**
* 获取图片重命名

* @param file
* @return
*/
public static String getImgRename(MultipartFile file) {
String imgRename = "";
/* 从当时时间MD5强制重命名图片 */
String imgType = file.getContentType();
imgRename = Md5Utils.md5_32(BaseUtil.getUniqueId());
if (imgType.equals("image/jpeg")) {
imgRename = imgRename.concat(".jpg");
} else if (imgType.equals("image/png")) {
imgRename = imgRename.concat(".png");
} else if (imgType.equals("image/bmp")) {
imgRename = imgRename.concat(".bmp");
} else if (imgType.equals("image/gif")) {
imgRename = imgRename.concat(".gif");
} else
imgRename = imgRename.concat(".jpg");
System.out.println("img name:" + imgRename);
return imgRename;
}


public static Boolean uploadFile(String destinationDir, MultipartFile file, String filename) throws Exception {
try {
SaveFileFromInputStream(file.getInputStream(), destinationDir, filename);
} catch (IOException e) {
return false;
}
return true;
}


/**
* 保存文件

* @param stream
* @param path
* @param filename
* @throws IOException
*/
private static void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
FileOutputStream outputStream = new FileOutputStream(path + "/" + filename);
int byteCount = 0;
byte[] bytes = new byte[1024];
while ((byteCount = stream.read(bytes)) != -1) {
outputStream.write(bytes, 0, byteCount);
}
outputStream.close();
stream.close();
}


public static String unescapeContent(String content) {
try {
content = java.net.URLDecoder.decode(content, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
content = content.replace("& lt;", "<").replace("& gt;", ">");
if (content.contains("<p>,</p>")) {
content = content.replace("<p>,</p>", "<p></p>");
} else if (content.startsWith(",")) {
content = content.substring(1, content.length() == 1 ? 1 : content.length() - 1);
}
return content;
}


public static String unescapeContent2(String content) {
try {
content = java.net.URLDecoder.decode(content, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
content = content.replace("& lt;", "<").replace("& gt;", ">");
content = content.replace("& #40;", "(").replace("& #41;", ")");
if (content.contains("<p>,</p>")) {
content = content.replace("<p>,</p>", "<p></p>");
} else if (content.startsWith(",")) {
content = content.substring(1, content.length() == 1 ? 1 : content.length() - 1);
}
return content;
}

public static String GenerateImage(String folderPath, String base64Str) {
return GenerateFile(folderPath, base64Str, ".jpg");
}


public static String GenerateRar(String folderPath, String base64Str) {
return GenerateFile(folderPath, base64Str, ".rar");
}


/**
* 返回文件路径

* @param folderPath
* @param base64Str
* @param fileSuffix
* @return
*/
public static String GenerateFile(String folderPath, String base64Str, String fileSuffix) { // 对字节数组字符串进行Base64解码并生成图片
if (base64Str == null) // 图像数据为空
return "";
if (folderPath.endsWith("/")) {
folderPath = folderPath.substring(0, folderPath.length() - 1);
}
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
.replace("/WEB-INF/classes", "/static" + folderPath);
@SuppressWarnings("restriction")
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
@SuppressWarnings("restriction")
byte[] b = decoder.decodeBuffer(base64Str);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
String fileName = Md5Utils.md5_32(com.c2bcms.app.utils.BaseUtil.getUniqueId()) + fileSuffix;
String imgFilePath = rootPath + fileName;
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return folderPath + "/" + fileName;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}


public static String unescapeHtml(String content) {
content = StringEscapeUtils.unescapeHtml4(content);
content = content.replace("& lt;", "<").replace("& gt;", ">");
if (content.contains("<p>,</p>")) {
content = content.replace("<p>,</p>", "<p></p>");
} else if (content.startsWith(",")) {
content = content.substring(1, content.length() - 1);
}
return content;
}


public static void writeBase64StrToFile(File file, String fileBase64Str) {
if (fileBase64Str == null) // 图像数据为空
return;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] bytes = decoder.decodeBuffer(fileBase64Str);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
FileUtils.writeByteArrayToFile(file, bytes);
} catch (Exception e) {
e.printStackTrace();
return;
}
}


public static byte[] getByteArray(String fileBase64Str) {
if (fileBase64Str == null) // 图像数据为空
return null;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] bytes = decoder.decodeBuffer(fileBase64Str);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
return bytes;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


public static void validImg(MultipartFile img) throws ApiException {
FileType type;
try {
type = FileTypeResolve.getType(img.getInputStream());
if (!type.equals(FileType.JPEG) && !type.equals(FileType.PNG) && !type.equals(FileType.GIF)) {
throw new ApiException("上传的主题文件只能为图片格式!");
}
} catch (IOException e) {
e.printStackTrace();
}
}


public static String saveImg(MultipartFile imgFile, String rootPath) {
// 上传图片
String imgRename = "";
if (imgFile.getSize() > 0) {
imgRename = BaseUtil.getImgRename(imgFile);
File file = new File(rootPath, imgRename);
try {
FileUtils.writeByteArrayToFile(file, imgFile.getBytes());
} catch (IOException e) {
e.printStackTrace();
return "";
}
return AppConstant.commonFolderPath + imgRename;
}
return imgRename;
}


public static void delImg(String rootPath, String imgName) {
if (StringUtils.isBlank(imgName)) {
return;
}
int lastIndex = imgName.lastIndexOf("/");
int totalIndex = imgName.length();
String imgPath = "";
if (lastIndex > -1) {
// 得到 /39ec3cab95de2da330fce782bd3527cb.jpg
imgPath = imgName.substring(lastIndex, totalIndex);
} else {
imgPath = "/" + imgName;
}
File file = new File(rootPath, imgPath);
if (file.exists()) {
file.delete();
}
}


/**
* 保存图片 此处的图片纯文件名

* @param imgFile
* @param imgRename
* @return
*/
public static boolean savePictrue(MultipartFile imgFile, String folderPath, String imgRename) {
if (folderPath.endsWith("/")) {
folderPath = folderPath.substring(0, folderPath.length() - 1);
}
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
.replace("/WEB-INF/classes", "/static" + folderPath);
File file = new File(rootPath, imgRename);
try {
FileUtils.writeByteArrayToFile(file, imgFile.getBytes());
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}


public static void delPictrue(String folderPath, String imgName) {
if (imgName.length() <= 5) {
return;
}
if (folderPath.endsWith("/")) {
folderPath = folderPath.substring(0, folderPath.length() - 1);
}
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
.replace("/WEB-INF/classes", "/static" + folderPath);
int lastIndex = imgName.lastIndexOf("/");
int totalIndex = imgName.length();
String imgPath = "";
if (lastIndex > -1) {
imgPath = imgName.substring(lastIndex, totalIndex);
} else {
imgPath = "/" + imgName;
}
File file = new File(rootPath, imgPath);
if (file.exists()) {
file.delete();
}
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值