工具类集和_gblfy版本
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                工具类集和_gblfy版本
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                | Cookie | CookieUtil.java | 
| BigDecimal | BigDecimalUtil.java | 
| 日期 | DateTimeUtil.java | 
| FTP | FTPUtil.java | 
| Json | JsonUtil.java | 
| MD5 | MD5Util.java | 
| Properties | PropertiesUtil.java | 
CookieUtil.java
package com.mmall.util;import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils;import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;/*** Created by geely*/ @Slf4j public class CookieUtil {private final static String COOKIE_DOMAIN = ".happymmall.com";private final static String COOKIE_NAME = "mmall_login_token";public static String readLoginToken(HttpServletRequest request){Cookie[] cks = request.getCookies();if(cks != null){for(Cookie ck : cks){log.info("read cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());if(StringUtils.equals(ck.getName(),COOKIE_NAME)){log.info("return cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());return ck.getValue();}}}return null;}//X:domain=".happymmall.com"//a:A.happymmall.com cookie:domain=A.happymmall.com;path="/"//b:B.happymmall.com cookie:domain=B.happymmall.com;path="/"//c:A.happymmall.com/test/cc cookie:domain=A.happymmall.com;path="/test/cc"//d:A.happymmall.com/test/dd cookie:domain=A.happymmall.com;path="/test/dd"//e:A.happymmall.com/test cookie:domain=A.happymmall.com;path="/test"public static void writeLoginToken(HttpServletResponse response,String token){Cookie ck = new Cookie(COOKIE_NAME,token);ck.setDomain(COOKIE_DOMAIN);ck.setPath("/");//代表設(shè)置在根目錄ck.setHttpOnly(true);//單位是秒。//如果這個(gè)maxage不設(shè)置的話,cookie就不會(huì)寫入硬盤,而是寫在內(nèi)存。只在當(dāng)前頁(yè)面有效。ck.setMaxAge(60 * 60 * 24 * 365);//如果是-1,代表永久log.info("write cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());response.addCookie(ck);}public static void delLoginToken(HttpServletRequest request,HttpServletResponse response){Cookie[] cks = request.getCookies();if(cks != null){for(Cookie ck : cks){if(StringUtils.equals(ck.getName(),COOKIE_NAME)){ck.setDomain(COOKIE_DOMAIN);ck.setPath("/");ck.setMaxAge(0);//設(shè)置成0,代表刪除此cookie。log.info("del cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());response.addCookie(ck);return;}}}} }BigDecimalUtil.java
package com.mmall.util;import java.math.BigDecimal;/*** Created by geely*/ public class BigDecimalUtil {private BigDecimalUtil(){}public static BigDecimal add(double v1,double v2){BigDecimal b1 = new BigDecimal(Double.toString(v1));BigDecimal b2 = new BigDecimal(Double.toString(v2));return b1.add(b2);}public static BigDecimal sub(double v1,double v2){BigDecimal b1 = new BigDecimal(Double.toString(v1));BigDecimal b2 = new BigDecimal(Double.toString(v2));return b1.subtract(b2);}public static BigDecimal mul(double v1,double v2){BigDecimal b1 = new BigDecimal(Double.toString(v1));BigDecimal b2 = new BigDecimal(Double.toString(v2));return b1.multiply(b2);}public static BigDecimal div(double v1,double v2){BigDecimal b1 = new BigDecimal(Double.toString(v1));BigDecimal b2 = new BigDecimal(Double.toString(v2));return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//四舍五入,保留2位小數(shù)//除不盡的情況} }DateTimeUtil.java
package com.mmall.util;import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter;import java.util.Date;/*** Created by geely*/ public class DateTimeUtil {//joda-time//str->Date//Date->strpublic static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";public static Date strToDate(String dateTimeStr,String formatStr){DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);return dateTime.toDate();}public static String dateToStr(Date date,String formatStr){if(date == null){return StringUtils.EMPTY;}DateTime dateTime = new DateTime(date);return dateTime.toString(formatStr);}public static Date strToDate(String dateTimeStr){DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);return dateTime.toDate();}public static String dateToStr(Date date){if(date == null){return StringUtils.EMPTY;}DateTime dateTime = new DateTime(date);return dateTime.toString(STANDARD_FORMAT);}public static void main(String[] args) {System.out.println(DateTimeUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));System.out.println(DateTimeUtil.strToDate("2010-01-01 11:11:11","yyyy-MM-dd HH:mm:ss"));} }FTPUtil.java
package com.mmall.util;import lombok.extern.slf4j.Slf4j; import org.apache.commons.net.ftp.FTPClient;import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List;/*** Created by geely*/ @Slf4j public class FTPUtil {private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");private static String ftpUser = PropertiesUtil.getProperty("ftp.user");private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");public FTPUtil(String ip,int port,String user,String pwd){this.ip = ip;this.port = port;this.user = user;this.pwd = pwd;}public static boolean uploadFile(List<File> fileList) throws IOException {FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpUser,ftpPass);log.info("開始連接ftp服務(wù)器");boolean result = ftpUtil.uploadFile("img",fileList);log.info("開始連接ftp服務(wù)器,結(jié)束上傳,上傳結(jié)果:{}");return result;}private boolean uploadFile(String remotePath,List<File> fileList) throws IOException {boolean uploaded = true;FileInputStream fis = null;//連接FTP服務(wù)器if(connectServer(this.ip,this.port,this.user,this.pwd)){try {ftpClient.changeWorkingDirectory(remotePath);ftpClient.setBufferSize(1024);ftpClient.setControlEncoding("UTF-8");ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);ftpClient.enterLocalPassiveMode();for(File fileItem : fileList){fis = new FileInputStream(fileItem);ftpClient.storeFile(fileItem.getName(),fis);}} catch (IOException e) {log.error("上傳文件異常",e);uploaded = false;e.printStackTrace();} finally {fis.close();ftpClient.disconnect();}}return uploaded;}private boolean connectServer(String ip,int port,String user,String pwd){boolean isSuccess = false;ftpClient = new FTPClient();try {ftpClient.connect(ip);isSuccess = ftpClient.login(user,pwd);} catch (IOException e) {log.error("連接FTP服務(wù)器異常",e);}return isSuccess;}private String ip;private int port;private String user;private String pwd;private FTPClient ftpClient;public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public int getPort() {return port;}public void setPort(int port) {this.port = port;}public String getUser() {return user;}public void setUser(String user) {this.user = user;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public FTPClient getFtpClient() {return ftpClient;}public void setFtpClient(FTPClient ftpClient) {this.ftpClient = ftpClient;} }JsonUtil.java
package com.mmall.util;import com.google.common.collect.Lists; import com.mmall.pojo.Category; import com.mmall.pojo.TestPojo; import com.mmall.pojo.User; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; import org.codehaus.jackson.type.JavaType; import org.codehaus.jackson.type.TypeReference;import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map;/*** Created by geely*/ @Slf4j public class JsonUtil {private static ObjectMapper objectMapper = new ObjectMapper();static{//對(duì)象的所有字段全部列入objectMapper.setSerializationInclusion(Inclusion.ALWAYS);//取消默認(rèn)轉(zhuǎn)換timestamps形式objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);//忽略空Bean轉(zhuǎn)json的錯(cuò)誤objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);//所有的日期格式都統(tǒng)一為以下的樣式,即yyyy-MM-dd HH:mm:ssobjectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));//忽略 在json字符串中存在,但是在java對(duì)象中不存在對(duì)應(yīng)屬性的情況。防止錯(cuò)誤objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);}public static <T> String obj2String(T obj){if(obj == null){return null;}try {return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj);} catch (Exception e) {log.warn("Parse Object to String error",e);return null;}}public static <T> String obj2StringPretty(T obj){if(obj == null){return null;}try {return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);} catch (Exception e) {log.warn("Parse Object to String error",e);return null;}}public static <T> T string2Obj(String str,Class<T> clazz){if(StringUtils.isEmpty(str) || clazz == null){return null;}try {return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);} catch (Exception e) {log.warn("Parse String to Object error",e);return null;}}public static <T> T string2Obj(String str, TypeReference<T> typeReference){if(StringUtils.isEmpty(str) || typeReference == null){return null;}try {return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));} catch (Exception e) {log.warn("Parse String to Object error",e);return null;}}public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);try {return objectMapper.readValue(str,javaType);} catch (Exception e) {log.warn("Parse String to Object error",e);return null;}}public static void main(String[] args) {TestPojo testPojo = new TestPojo();testPojo.setName("Geely");testPojo.setId(666);//{"name":"Geely","id":666}String json = "{\"name\":\"Geely\",\"color\":\"blue\",\"id\":666}";TestPojo testPojoObject = JsonUtil.string2Obj(json,TestPojo.class); // String testPojoJson = JsonUtil.obj2String(testPojo); // log.info("testPojoJson:{}",testPojoJson);log.info("end");// User user = new User(); // user.setId(2); // user.setEmail("geely@happymmall.com"); // user.setCreateTime(new Date()); // String userJsonPretty = JsonUtil.obj2StringPretty(user); // log.info("userJson:{}",userJsonPretty);// User u2 = new User(); // u2.setId(2); // u2.setEmail("geelyu2@happymmall.com"); // // // // String user1Json = JsonUtil.obj2String(u1); // // String user1JsonPretty = JsonUtil.obj2StringPretty(u1); // // log.info("user1Json:{}",user1Json); // // log.info("user1JsonPretty:{}",user1JsonPretty); // // // User user = JsonUtil.string2Obj(user1Json,User.class); // // // List<User> userList = Lists.newArrayList(); // userList.add(u1); // userList.add(u2); // // String userListStr = JsonUtil.obj2StringPretty(userList); // // log.info("=================="); // // log.info(userListStr); // // // List<User> userListObj1 = JsonUtil.string2Obj(userListStr, new TypeReference<List<User>>() { // }); // // // List<User> userListObj2 = JsonUtil.string2Obj(userListStr,List.class,User.class);System.out.println("end");} }MD5Util.java
package com.mmall.util;import org.springframework.util.StringUtils;import java.security.MessageDigest;/*** Created by geely*/ public class MD5Util {private static String byteArrayToHexString(byte b[]) {StringBuffer resultSb = new StringBuffer();for (int i = 0; i < b.length; i++)resultSb.append(byteToHexString(b[i]));return resultSb.toString();}private static String byteToHexString(byte b) {int n = b;if (n < 0)n += 256;int d1 = n / 16;int d2 = n % 16;return hexDigits[d1] + hexDigits[d2];}/*** 返回大寫MD5** @param origin* @param charsetname* @return*/private static String MD5Encode(String origin, String charsetname) {String resultString = null;try {resultString = new String(origin);MessageDigest md = MessageDigest.getInstance("MD5");if (charsetname == null || "".equals(charsetname))resultString = byteArrayToHexString(md.digest(resultString.getBytes()));elseresultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));} catch (Exception exception) {}return resultString.toUpperCase();}public static String MD5EncodeUtf8(String origin) {origin = origin + PropertiesUtil.getProperty("password.salt", "");return MD5Encode(origin, "utf-8");}private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};}PropertiesUtil.java
package com.mmall.util;import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils;import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties;/*** Created by geely*/ @Slf4j public class PropertiesUtil {private static Properties props;static {String fileName = "mmall.properties";props = new Properties();try {props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));} catch (IOException e) {log.error("配置文件讀取異常",e);}}public static String getProperty(String key){String value = props.getProperty(key.trim());if(StringUtils.isBlank(value)){return null;}return value.trim();}public static String getProperty(String key,String defaultValue){String value = props.getProperty(key.trim());if(StringUtils.isBlank(value)){value = defaultValue;}return value.trim();} }總結(jié)
以上是生活随笔為你收集整理的工具类集和_gblfy版本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
                            
                        - 上一篇: 企业级实战01_ActiveMQ 下载、
 - 下一篇: 修改Gradle本地仓库的位置 方法