1. 程式人生 > >判斷手機和PC 的工具類等

判斷手機和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();
}
}
}