Commit effd9974 authored by yanghailong's avatar yanghailong

增加工具类

parent 7c6a639c
kernels-cloud/kernels-cloud-eureka/target/
kernels-ribbon/kernels-ribbon-system/target/
.idea/
iloomo-eureka/target/
iloomo-ribbon/target/classes/
iloomo-ribbon/target/
This diff is collapsed.
package com.iloomo.interceptor.shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
* 2015-3-6
*/
public class ShiroRealm extends AuthorizingRealm {
/*
* 登录信息和用户验证信息验证(non-Javadoc)
* @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal(); //得到用户名
String password = new String((char[])token.getCredentials()); //得到密码
if(null != username && null != password){
return new SimpleAuthenticationInfo(username, password, getName());
}else{
return null;
}
}
/*
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法(non-Javadoc)
* @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
System.out.println("========2");
return null;
}
}
......@@ -4,7 +4,6 @@ import java.math.BigInteger;
/**
* 权限计算帮助类
qq 3 1 3 5 96790[青苔]
* 修改日期:2015/11/2
*/
public class RightsHelper {
......
......@@ -11,13 +11,6 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>template</artifactId>
<dependencies>
<dependency><!--引入自定义工具jar-->
<groupId>com.iloomo.kernels.util</groupId>
<artifactId>core-util</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
......@@ -131,11 +124,11 @@
</dependency>
<!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>-->
<!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>-->
</dependencies>
<build>
......
package com.iloomo.controller;
import com.iloomo.entity.Page;
import com.iloomo.util.Logger;
import com.iloomo.util.PageData;
import com.iloomo.util.UuidUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
*
*/
public class BaseController {
protected Logger logger = Logger.getLogger(this.getClass());
private static final long serialVersionUID = 6357869213649815390L;
/** new PageData对象
* @return
*/
public PageData getPageData(){
return new PageData(this.getRequest());
}
/**得到request对象
* @return
*/
public HttpServletRequest getRequest() {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
return request;
}
/**得到32位的uuid
* @return
*/
public String get32UUID(){
return UuidUtil.get32UUID();
}
/**得到分页列表的信息
* @return
*/
public Page getPage(){
return new Page();
}
public static void logBefore(Logger logger, String interfaceName){
logger.info("");
logger.info("start");
logger.info(interfaceName);
}
public static void logAfter(Logger logger){
logger.info("end");
logger.info("");
}
}
package com.iloomo.dao;
/**
*
*/
public interface DAO {
/**
* 保存对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object save(String str, Object obj) throws Exception;
/**
* 修改对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object update(String str, Object obj) throws Exception;
/**
* 删除对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object delete(String str, Object obj) throws Exception;
/**
* 查找对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object findForObject(String str, Object obj) throws Exception;
/**
* 查找对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object findForList(String str, Object obj) throws Exception;
/**
* 查找对象封装成Map
* @param s
* @param obj
* @return
* @throws Exception
*/
public Object findForMap(String sql, Object obj, String key, String value) throws Exception;
}
package com.iloomo.dao;
import com.iloomo.util.PageData;
import com.iloomo.util.PagerModel;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
*/
@Repository("daoSupport")
public class DaoSupport implements DAO {
@Resource(name = "sqlSessionTemplate")
private SqlSessionTemplate sqlSessionTemplate;
/**
* 保存对象
*
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object save(String str, Object obj) throws Exception {
sqlSessionTemplate.getConnection();
return sqlSessionTemplate.insert(str, obj);
}
/**
* 批量更新
*
* @param str
* @param objs
* @return
* @throws Exception
*/
public Object batchSave(String str, List objs) throws Exception {
SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
// 批量执行器
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
try {
if (objs != null) {
for (int i = 0, size = objs.size(); i < size; i++) {
sqlSession.insert(str, objs.get(i));
}
sqlSession.flushStatements();
sqlSession.commit();
sqlSession.clearCache();
}
} finally {
sqlSession.close();
}
return 1;
}
/**
* 修改对象
*
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object update(String str, Object obj) throws Exception {
return sqlSessionTemplate.update(str, obj);
}
/**
* 批量更新
*
* @param str
* @param objs
* @return
* @throws Exception
*/
public void batchUpdate(String str, List objs) throws Exception {
SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
// 批量执行器
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
try {
if (objs != null) {
for (int i = 0, size = objs.size(); i < size; i++) {
sqlSession.update(str, objs.get(i));
}
sqlSession.flushStatements();
sqlSession.commit();
sqlSession.clearCache();
}
} finally {
sqlSession.close();
}
}
/**
* 批量更新
*
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object batchDelete(String str, List objs) throws Exception {
return sqlSessionTemplate.delete(str, objs);
}
/**
* 删除对象
*
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object delete(String str, Object obj) throws Exception {
return sqlSessionTemplate.delete(str, obj);
}
/**
* 查找对象
*
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object findForObject(String str, Object obj) throws Exception {
return sqlSessionTemplate.selectOne(str, obj);
}
/**
* 查找对象
*
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object findForList(String str, Object obj) throws Exception {
return sqlSessionTemplate.selectList(str, obj);
}
/**
* 分页查询
*
* @param selectList
* @param selectCount
* @param param
* @return
* @throws Exception
*/
public PagerModel selectPageList(String selectList, String selectCount, Object param) {
List list = sqlSessionTemplate.selectList(selectList, param);
PagerModel pm = new PagerModel();
PageData pData = (PageData)param;
pm.setPageNo(pData.getString("page")=="" || pData.getString("page")==null ? 1:Integer.parseInt(pData.getString("page")));
pm.setPageSize(pData.getString("rows")==null || pData.getString("rows")==""? pm.getPageSize():Integer.parseInt(pData.getString("rows")));
pm.setList(list);
int oneC = 0;
try {
oneC = selectCount(selectCount, param);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (oneC != 0) {
pm.setTotal(oneC);
} else {
pm.setTotal(0);
}
return pm;
}
public Object findForMap(String str, Object obj, String key, String value) throws Exception {
return sqlSessionTemplate.selectMap(str, obj, key);
}
/**
* 查询数量
*
* @param selectCount
* @param obj
* @return
* @throws Exception
*/
public int selectCount(String selectCount, Object obj) throws Exception {
Object oneC = sqlSessionTemplate.selectOne(selectCount, obj);
return Integer.parseInt(oneC.toString());
}
}
......@@ -6,8 +6,8 @@ import com.iloomo.util.Tools;
/**
* 分页类
* @author FH QQ 313596790[青苔]
* 创建时间:2014年6月28日
* 创建时间:
*/
public class Page {
......
package com.iloomo;
import com.iloomo.util.JsonUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.Map;
public class test {
public static void main(String[] args) {
String a = "[{interface_id':1274,'table_name':'id','table_column':'int','parameter_explain':''},{'interface_id':1274,'table_name':'user_id','table_column':'int','parameter_explain':''},{'interface_id':1274,'table_name':'sex','table_column':'int','parameter_explain':'性别1:男,2:女'},{'interface_id':1274,'table_name':'address','table_column':'varchar','parameter_explain':'所在地址'},{'interface_id':1274,'table_name':'qq','table_column':'int','parameter_explain':''},{'interface_id':1274,'table_name':'email','table_column':'varch…mark','table_column':'varchar','parameter_explain':'备注'},{'interface_id':1274,'table_name':'type','table_column':'int','parameter_explain':''},{'interface_id':1274,'table_name':'add_time','table_column':'int','parameter_explain':''},{'interface_id':1274,'table_name':'update_time','table_column':'int','parameter_explain':''},{'interface_id':1274,'table_name':'business_id','table_column':'int','parameter_explain':''},{'interface_id':1274,'table_name':'is_deleted','table_column':'int','parameter_explain':''}]";
// JSONObject json = JSONObject.fromObject(a);
JsonUtil jsonUtil = new JsonUtil();
JSONArray jay = JSONArray.fromObject(a);
for(int i =0;i<jay.size();i++){
Map<String, String> parameterMaps =jsonUtil.jsonObjToMap((JSONObject) jay.get(i));
}
System.out.println(a);
}
}
package com.iloomo.util;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.iloomo.constant.SysConstant;
import org.codehaus.jackson.map.util.JSONPObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** 接口参数校验
* @author: email yanghailong@iloomo.com
* 修改日期:2015/11/2
*/
public class AppUtil {
protected static Logger logger = Logger.getLogger(AppUtil.class);
/**检查参数是否完整
* @param method
* @param pd
* @return
*/
public static boolean checkParam(String method, PageData pd){
boolean result = false;
int falseCount = 0;
String[] paramArray = new String[20];
String[] valueArray = new String[20];
String[] tempArray = new String[20]; //临时数组
if(method=="registered"){// 注册
paramArray = Const.APP_REGISTERED_PARAM_ARRAY; //参数
valueArray = Const.APP_REGISTERED_VALUE_ARRAY; //参数名称
}else if(method=="getAppuserByUsernmae"){//根据用户名获取会员信息
paramArray = Const.APP_GETAPPUSER_PARAM_ARRAY;
valueArray = Const.APP_GETAPPUSER_VALUE_ARRAY;
}
int size = paramArray.length;
for(int i=0;i<size;i++){
String param = paramArray[i];
if(!pd.containsKey(param)){
tempArray[falseCount] = valueArray[i]+"--"+param;
falseCount += 1;
}
}
if(falseCount>0){
logger.error(method+"接口,请求协议中缺少 "+falseCount+"个 参数");
for(int j=1;j<=falseCount;j++){
logger.error(" 第"+j+"个:"+ tempArray[j-1]);
}
} else {
result = true;
}
return result;
}
/**
* 设置分页的参数
* @param pd
* @return
*/
public static PageData setPageParam(PageData pd){
String page_now_str = pd.get("page_now").toString();
int pageNowInt = Integer.parseInt(page_now_str)-1;
String page_size_str = pd.get("page_size").toString(); //每页显示记录数
int pageSizeInt = Integer.parseInt(page_size_str);
String page_now = pageNowInt+"";
String page_start = (pageNowInt*pageSizeInt)+"";
pd.put("page_now", page_now);
pd.put("page_start", page_start);
return pd;
}
/**设置list中的distance
* @param list
* @param pd
* @return
*/
public static List<PageData> setListDistance(List<PageData> list, PageData pd){
List<PageData> listReturn = new ArrayList<PageData>();
String user_longitude = "";
String user_latitude = "";
try{
user_longitude = pd.get("user_longitude").toString(); //"117.11811";
user_latitude = pd.get("user_latitude").toString(); //"36.68484";
} catch(Exception e){
logger.error("缺失参数--user_longitude和user_longitude");
logger.error("lost param:user_longitude and user_longitude");
}
PageData pdTemp = new PageData();
int size = list.size();
for(int i=0;i<size;i++){
pdTemp = list.get(i);
String longitude = pdTemp.get("longitude").toString();
String latitude = pdTemp.get("latitude").toString();
String distance = MapDistance.getDistance(
user_longitude, user_latitude,
longitude, latitude
);
pdTemp.put("distance", distance);
pdTemp.put("size", distance.length());
listReturn.add(pdTemp);
}
return listReturn;
}
/**
* @param pd
* @param map
* @return
*/
public static Object returnObject(PageData pd, Map map){
if(pd.containsKey("callback")){
String callback = pd.get("callback").toString();
return new JSONPObject(callback, map);
}else{
return map;
}
}
public static String getJson(boolean success,Object msg, PageData pageData){
Map<String,Object> map = new HashMap<String,Object>();
map.put("success", success);
map.put("msg", msg);
String str = JSONObject.toJSONString(map,SerializerFeature.WriteMapNullValue);
str = str.replace("null", "\"\"");
//str = str.replaceAll("\"", "\\\"");
if(pageData == null ){
if(SysConstant.IS_JSONP){
str = SysConstant.CALL_BACK + "(" + str + ")";
}
}else{
str = getCallbackJson(pageData, str, true);
}
return str;
}
public static String getCallbackJson(PageData pd,String pOrigin, boolean pJsonp) {
String msg = "";
if (pJsonp) {
if (pd.containsKey("callback")) {
msg = pd.get("callback").toString() + "(" + pOrigin + ")";
} else {
msg = pOrigin;
}
} else {
msg = pOrigin;
}
return msg;
}
}
package com.iloomo.util;
import java.io.IOException;
import java.util.Properties;
/**
* 获取config.properties配置文件的值
* @author 张亚兵
*
*/
public class ConfigUtil {
private static Properties prop = new Properties();
static {
try {
prop.load(ConfigUtil.class.getClassLoader().getResourceAsStream(
"config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getEnv() {
return (String) prop.getProperty("env").trim()+".";
}
public static String getValue(String key) {
String envKey = getEnv() + key;
return (String) prop.getProperty(envKey).trim();
}
// 获取oss根路径配置
public static String getOssRootDirName() {
String envKey = getEnv() + "ossRootDirName";
return (String) prop.getProperty(envKey).trim();
}
// 获取oss目录配置,自动拼接根路径
public static String getOssDirValue(String key) {
String envKey = getEnv() + key;
return getOssRootDirName() + (String) prop.getProperty(envKey).trim();
}
// 获取接口域名名称
public static String getInterfaceDomainName() {
String envKey = getEnv() + "interfaceDomainName";
return (String) prop.getProperty(envKey).trim();
}
// 获取接口对应的URL全路径
public static String getInterfaceFullUrl(String key) {
String envKey = getEnv() + key;
return getInterfaceDomainName() + (String) prop.getProperty(envKey).trim();
}
// 获取H5域名名称
public static String getH5DomainName() {
String envKey = getEnv() + "h5DomainName";
return (String) prop.getProperty(envKey).trim();
}
// 获取H5对应的URL全路径
public static String getH5FullUrl(String key) {
String envKey = getEnv() + key;
return getH5DomainName() + (String) prop.getProperty(envKey).trim();
}
// 获取接口域名名称
public static String getInterfaceSslDomainName() {
String envKey = getEnv() + "interfaceSslDomainName";
return (String) prop.getProperty(envKey).trim();
}
// 获取接口对应的URL全路径
public static String getInterfaceSslFullUrl(String key) {
String envKey = getEnv() + key;
return getInterfaceSslDomainName() + (String) prop.getProperty(envKey).trim();
}
// 获取商户域名名称
public static String getShopDomainName() {
String envKey = getEnv() + "shopDomainName";
return (String) prop.getProperty(envKey).trim();
}
// 获取商户对应的URL全路径
public static String getShopFullUrl(String key) {
String envKey = getEnv() + key;
return getShopDomainName() + (String) prop.getProperty(envKey).trim();
}
}
package com.iloomo.util;
import org.springframework.context.ApplicationContext;
/**
* 项目名称:
* @author:email yanghailong@iloomo.com
* 修改日期:2015/11/2
*/
public class Const {
public static final String SESSION_SECURITY_CODE = "sessionSecCode";//验证码
public static final String MOBILE_CODE = "mobileCode"; //手机验证码
public static final String SESSION_USER = "sessionUser"; //session用的用户
public static final String SESSION_ROLE_RIGHTS = "sessionRoleRights";
public static final String sSESSION_ROLE_RIGHTS = "sessionRoleRights";
public static final String SESSION_menuList = "menuList"; //当前菜单
public static final String SESSION_allmenuList = "allmenuList"; //全部菜单
public static final String SESSION_QX = "QX";
public static final String SESSION_userpds = "userpds";
public static final String SESSION_USERROL = "USERROL"; //用户对象
public static final String SESSION_USERNAME = "username"; //用户名
public static final String TRUE = "T";
public static final String FALSE = "F";
public static final String LOGIN = "/login_toLogin.do"; //登录地址
public static final String SYSNAME = "admin/config/SYSNAME.txt"; //系统名称路径
public static final String PAGE = "admin/config/PAGE.txt"; //分页条数配置路径
public static final String EMAIL = "admin/config/EMAIL.txt"; //邮箱服务器配置路径
public static final String SMS1 = "admin/config/SMS1.txt"; //短信账户配置路径1
public static final String SMS2 = "admin/config/SMS2.txt"; //短信账户配置路径2
public static final String FWATERM = "admin/config/FWATERM.txt"; //文字水印配置路径
public static final String IWATERM = "admin/config/IWATERM.txt"; //图片水印配置路径
public static final String WEIXIN = "admin/config/WEIXIN.txt"; //微信配置路径
public static final String WEBSOCKET = "admin/config/WEBSOCKET.txt";//WEBSOCKET配置路径
public static final String FILEPATHIMG = "uploadFiles/uploadImgs/"; //图片上传路径
public static final String FILEPATHFILE = "uploadFiles/file/"; //文件上传路径
public static final String FILEPATHTWODIMENSIONCODE = "uploadFiles/twoDimensionCode/"; //二维码存放路径
//public static final String NO_INTERCEPTOR_PATH = ".*/((login_login)|(forgetPass)|(register)|(checkCode)|(sign)|(accountRecord)|(getAllSecondList)|(getshopSkuList)|(getInfoByid2)|(receiver)|(getshopSkuOne)|(getMainshopSkuList)|(getByShopId)|(linglingshenghuoInit)|(system)|(logout)|(code)|(app)|(weixin)|(static)|(main)|(websocket)).*"; //不对匹配该值的访问路径拦截(正则)
public static final String NO_INTERCEPTOR_PATH = ".*/((checkCode)|(resetPassword)|(sendCode)|(checkMobileCode)|(register)).*"; //不对匹配该值的访问路径拦截(正则)
public static ApplicationContext WEB_APP_CONTEXT = null; //该值会在web容器启动时由WebAppContextListener初始化
/**
* APP Constants
*/
//app注册接口_请求协议参数)
public static final String[] APP_REGISTERED_PARAM_ARRAY = new String[]{"countries","uname","passwd","title","full_name","company_name","countries_code","area_code","telephone","mobile"};
public static final String[] APP_REGISTERED_VALUE_ARRAY = new String[]{"国籍","邮箱帐号","密码","称谓","名称","公司名称","国家编号","区号","电话","手机号"};
//app根据用户名获取会员信息接口_请求协议中的参数
public static final String[] APP_GETAPPUSER_PARAM_ARRAY = new String[]{"USERNAME"};
public static final String[] APP_GETAPPUSER_VALUE_ARRAY = new String[]{"用户名"};
}
package com.iloomo.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 说明:日期处理
* 创建人:loomo
* 修改时间:2015年11月24日
* @version
*/
public class DateUtil {
private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");
private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final static SimpleDateFormat sdfTimeOrder = new SimpleDateFormat("yyyyMMddHHmmssSSS");
/**
* 获取YYYY格式
* @return
*/
public static String getYear() {
return sdfYear.format(new Date());
}
/**
* 获取YYYY-MM-DD格式
* @return
*/
public static String getDay() {
return sdfDay.format(new Date());
}
/**
* 获取YYYYMMDD格式
* @return
*/
public static String getDays(){
return sdfDays.format(new Date());
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
* @return
*/
public static String getTime() {
return sdfTime.format(new Date());
}
/**
* 获取YYYYMMDDHHmmssSSS格式
* @return
*/
public static String getTimeOrder() {
return sdfTimeOrder.format(new Date());
}
/**
* 获取YYMMDDHHmmssSSS格式
* @return
*/
public static String getTimeOrderCardNum() {
return sdfTimeOrder.format(new Date());
}
/**
* @Title: compareDate
* @Description: TODO(日期比较,如果s>=e 返回true 否则返回false)
* @param s
* @param e
* @return boolean
* @throws
*/
public static boolean compareDate(String s, String e) {
if(fomatDate(s)==null||fomatDate(e)==null){
return false;
}
return fomatDate(s).getTime() >=fomatDate(e).getTime();
}
/**
* 格式化日期
* @return
*/
public static Date fomatDate(String date) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 校验日期是否合法
* @return
*/
public static boolean isValidDate(String s) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
fmt.parse(s);
return true;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return false;
}
}
/**
* @param startTime
* @param endTime
* @return
*/
public static int getDiffYear(String startTime,String endTime) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
//long aa=0;
int years=(int) (((fmt.parse(endTime).getTime()-fmt.parse(startTime).getTime())/ (1000 * 60 * 60 * 24))/365);
return years;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return 0;
}
}
/**
* <li>功能描述:时间相减得到天数
* @param beginDateStr
* @param endDateStr
* @return
* long
* @author Administrator
*/
public static long getDaySub(String beginDateStr,String endDateStr){
long day=0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = null;
Date endDate = null;
try {
beginDate = format.parse(beginDateStr);
endDate= format.parse(endDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
//System.out.println("相隔的天数="+day);
return day;
}
/**
* 得到n天之后的日期
* @param days
* @return
*/
public static String getAfterDayDate(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 得到n天之后是周几
* @param days
* @return
*/
public static String getAfterDayWeek(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(date);
return dateStr;
}
/**
* @Title: diffSecend
* @Description: TODO(获得当前时间减去n秒的时间)
* @param
* @return boolean
* @throws
*/
public static String diffSecond(Integer second) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = new GregorianCalendar();
Date date = new Date();
c.setTime(date);//设置参数时间
c.add(Calendar.SECOND,-second);//把日期往后增加SECOND 秒.整数往后推,负数往前移动
String str = df.format(c.getTime());
return str;
}
public static void main(String[] args) {
System.out.println(getDays());
System.out.println(getAfterDayWeek("3"));
}
/**
* 得到指定日期n天之后的日期-日期格式到天
* @param days
* @return
*/
public static String getAfterDayDateForParamDay(String days,String dateParam) {
int daysInt = Integer.parseInt(days);
Date dateParamD = fomatDate(dateParam);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.setTime(dateParamD);
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdfd.format(date);
return dateStr;
}
}
package com.iloomo.util;
import org.springframework.util.ResourceUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 下载工具类
* @param
* @throws Exception
*/
public class DownloadUtil {
public static HttpServletResponse downLoadFiles(String zipName,String pathString, HttpServletResponse response) throws Exception{
//1、获取项目根路径
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
//2、创建临时.zip压缩包的位置及名称
String zipFilename = path+"/"+"codes/"+System.currentTimeMillis()+"/"+zipName+".zip";
File newFile = new File(zipFilename);
if (!newFile.getParentFile().exists()) {
boolean result = newFile.getParentFile().mkdirs();
if (!result) {
System.out.println("创建失败");
throw new Exception();
}
}
if (!newFile.exists()) {
boolean result = newFile.createNewFile();
if (!result) {
System.out.println("创建失败");
throw new Exception();
}
}
//3、将pathString路径内的文件压缩为.zip文件
FileZip.zip(pathString,zipFilename);
response.reset();
//4、下载第3步压缩好的.zip文件
return downloadZip(newFile, response);
}
/**
* 把接受的全部文件打成压缩包
*
* @param
* @param
*/
public static void zipFile(List files, ZipOutputStream outputStream) {
int size = files.size();
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
}
/**
* 根据输入的文件与输出流对文件进行打包
*
* @param
* @param
*/
public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream IN = new FileInputStream(inputFile);
BufferedInputStream bins = new BufferedInputStream(IN, 512);
ZipEntry entry = new ZipEntry(inputFile.getName());
ouputStream.putNextEntry(entry);
// 向压缩文件中输出数据
int nNumber;
byte[] buffer = new byte[512];
while ((nNumber = bins.read(buffer)) != -1) {
ouputStream.write(buffer, 0, nNumber);
}
// 关闭创建的流对象
bins.close();
IN.close();
} else {
try {
File[] files = inputFile.listFiles();
for (int i = 0; i < files.length; i++) {
zipFile(files[i], ouputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
if (file.exists() == false) {
System.out.println("待压缩的文件目录:" + file + "不存在.");
} else {
try {
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
// 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
File f = new File(file.getPath());
f.delete();
f.getParentFile().delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return response;
}
}
package com.iloomo.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
/** 文件处理
* 创建人:loomo
* 创建时间:2014年12月23日
*/
public class FileUtil {
public static void main(String[] args) {
String dirName = "d:/FH/topic/";// 创建目录
FileUtil.createDir(dirName);
}
/**
* 创建目录
* @param destDirName
* 目标目录名
* @return 目录创建成功返回true,否则返回false
*/
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
// 创建单个目录
if (dir.mkdirs()) {
return true;
} else {
return false;
}
}
/**
* 删除文件
* @param filePathAndName
* String 文件路径及名称 如c:/fqf.txt
* @param
*
* @return boolean
*/
public static void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myDelFile = new File(filePath);
myDelFile.delete();
} catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
/**
* 读取到字节数组0
* @param filePath //路径
* @throws IOException
*/
public static byte[] getContent(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length
&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
throw new IOException("Could not completely read file " + file.getName());
}
fi.close();
return buffer;
}
/**
* 读取到字节数组1
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
/**
* 读取到字节数组2
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray2(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray3(String filePath) throws IOException {
FileChannel fc = null;
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(filePath, "r");
fc = rf.getChannel();
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
fc.size()).load();
//System.out.println(byteBuffer.isLoaded());
byte[] result = new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
// System.out.println("remain");
byteBuffer.get(result, 0, byteBuffer.remaining());
}
return result;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
rf.close();
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*工具类,将MultipartFile转换成 File 并且实现了平台无关性*/
public static File multipartToFile(MultipartFile multipart) throws IllegalStateException, IOException {
File convFile = new File(multipart.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(multipart.getBytes());
return convFile;
}
}
\ No newline at end of file
package com.iloomo.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**java压缩成zip
* @author loomo
* 创建时间:2015年1月14日
*/
public class FileZip {
/**
* @param inputFileName 你要压缩的文件夹(整个完整路径)
* @param zipFileName 压缩后的文件(整个完整路径)
* @throws Exception
*/
public static Boolean zip(String inputFileName, String zipFileName) throws Exception {
zip(zipFileName, new File(inputFileName));
return true;
}
private static void zip(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
zip(out, inputFile, "");
out.flush();
out.close();
}
private static void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
public static void main(String [] temp){
try {
zip("C:\\Users\\iloomo\\eclipse-workspace\\crm\\kernels-dev\\dev\\template","C:\\test\\test.zip");//你要压缩的文件夹 和 压缩后的文件
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
//=====================文件压缩=========================
/*//把文件压缩成zip
File zipFile = new File("E:/demo.zip");
//定义输入文件流
InputStream input = new FileInputStream(file);
//定义压缩输出流
ZipOutputStream zipOut = null;
//实例化压缩输出流,并制定压缩文件的输出路径 就是E盘下,名字叫 demo.zip
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
//设置注释
zipOut.setComment("www.demo.com");
int temp = 0;
while((temp = input.read()) != -1) {
zipOut.write(temp);
}
input.close();
zipOut.close();*/
//==============================================
package com.iloomo.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JavaBeanUtil {
private static Logger logger = LoggerFactory.getLogger(JavaBeanUtil.class);
/**
     * 实体类转map
     * @param obj
     * @return
     */
public static Map<String, Object> convertBeanToMap(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
if (null == value) {
map.put(key, "");
} else {
map.put(key, value);
}
}
}
} catch (Exception e) {
logger.error("convertBean2Map Error {}", e);
}
return map;
}
/**
     * map 转实体类
     * @param clazz
     * @param map
     * @param <T>
     * @return
     */
public static <T> T convertMapToBean(Class<T> clazz, Map<String,Object> map) {
T obj = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
obj = clazz.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
if ("".equals(value)) {
value = null;
}
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(obj, args);
}
}
} catch (IllegalAccessException e) {
logger.error("convertMapToBean 实例化JavaBean失败 Error{}" ,e);
} catch (IntrospectionException e) {
logger.error("convertMapToBean 分析类属性失败 Error{}" ,e);
} catch (IllegalArgumentException e) {
logger.error("convertMapToBean 映射错误 Error{}" ,e);
} catch (InstantiationException e) {
logger.error("convertMapToBean 实例化 JavaBean 失败 Error{}" ,e);
}catch (InvocationTargetException e){
logger.error("convertMapToBean字段映射失败 Error{}" ,e);
}catch (Exception e){
logger.error("convertMapToBean Error{}" ,e);
}
return (T) obj;
}
//将map通过反射转化为实体
public static Object MapToModel(Map<String,Object> map,Object o) throws Exception{
if (!map.isEmpty()) {
for (String k : map.keySet()) {
Object v =null;
if (!k.isEmpty()) {
v = map.get(k);
}
Field[] fields = null;
fields = o.getClass().getDeclaredFields();
String clzName = o.getClass().getSimpleName();
for (Field field : fields) {
int mod = field.getModifiers();
if (field.getName().toUpperCase().equals(k.toUpperCase())) {
field.setAccessible(true);
//region--进行类型判断
String type=field.getType().toString();
if (type.endsWith("String")){
if (v!=null){
v=v.toString();
}else {
v="";
}
}
if (type.endsWith("Date")){
v=new Date(v.toString());
}
if (type.endsWith("Boolean")){
v=Boolean.getBoolean(v.toString());
}
if (type.endsWith("int")){
v=new Integer(v.toString());
}
if (type.endsWith("Long")){
v=new Long(v.toString());
}
//endregion
field.set(o, v);
}
}
}
}
return o;
}
/**
   * 实体对象转成Map
   * @param obj 实体对象
   * @return
   */
public static Map<String, Object> object2Map(Object obj) {
Map<String, Object> map = new HashMap<>();
if (obj == null) {
return map;
}
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
     * Map转成实体对象
     * @param map map实体对象包含属性
     * @param clazz 实体对象类型
     * @return
     */
public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = clazz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
/*Student s = new Student();
      s.setUserName("ZHH");
      s.setAge("24");
      System.out.println(object2Map(s));
      Map<String, Object> map = new HashMap<>();
      map.put("userName", "zhh");
      map.put("age", "24");
      System.out.println(map2Object(map, Student.class));*/
}
}
package com.iloomo.util;
import net.sf.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class JsonUtil {
public Map<String,String> jsonToMap(String jsonString){
Map<String,String> map = new HashMap<String, String>();
JSONObject json = JSONObject.fromObject(jsonString);
Iterator iterator = json.keys();
while(iterator.hasNext()) {
String key = (String) iterator.next();
String value = json.getString(key);
map.put(key,value);
}
return map;
}
public Map<String,String> jsonObjToMap(JSONObject json){
Map<String,String> map = new HashMap<String, String>();
Iterator iterator = json.keys();
while(iterator.hasNext()) {
String key = (String) iterator.next();
String value = json.getString(key);
map.put(key,value);
}
return map;
}
}
package com.iloomo.util;
/**
* 说明:日志处理
* 创建人:loomo
* 修改时间:2014年9月20日
* @version
*/
public class Logger {
private org.apache.log4j.Logger logger;
/**
* 构造方法,初始化Log4j的日志对象
*/
private Logger(org.apache.log4j.Logger log4jLogger) {
logger = log4jLogger;
}
/**
* 获取构造器,根据类初始化Logger对象
*
* @param Class
* Class对象
* @return Logger对象
*/
public static Logger getLogger(Class classObject) {
return new Logger(org.apache.log4j.Logger.getLogger(classObject));
}
/**
* 获取构造器,根据类名初始化Logger对象
*
* @param String
* 类名字符串
* @return Logger对象
*/
public static Logger getLogger(String loggerName) {
return new Logger(org.apache.log4j.Logger.getLogger(loggerName));
}
public void debug(Object object) {
logger.debug(object);
}
public void debug(Object object, Throwable e) {
logger.debug(object, e);
}
public void info(Object object) {
logger.info(object);
}
public void info(Object object, Throwable e) {
logger.info(object, e);
}
public void warn(Object object) {
logger.warn(object);
}
public void warn(Object object, Throwable e) {
logger.warn(object, e);
}
public void error(Object object) {
logger.error(object);
}
public void error(Object object, Throwable e) {
logger.error(object, e);
}
public void fatal(Object object) {
logger.fatal(object);
}
public String getName() {
return logger.getName();
}
public org.apache.log4j.Logger getLog4jLogger() {
return logger;
}
public boolean equals(Logger newLogger) {
return logger.equals(newLogger.getLog4jLogger());
}
}
\ No newline at end of file
package com.iloomo.util;
import java.security.MessageDigest;
/**
* 说明:MD5处理
* 创建人:loomo
* 修改时间:2014年9月20日
* @version
*/
public class MD5 {
public static String md5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
str = buf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public final static String encode(String s) {
return encode(s.getBytes());
}
private static String encode(byte[] bytes){
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
return null;
}
md5.update(bytes);
byte[] md = md5.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
public static void main(String[] args) {
System.out.println(md5("31119@qq.com"+"123456"));
System.out.println(md5("mj1"));
}
}
package com.iloomo.util;
import java.util.HashMap;
import java.util.Map;
/**
* 说明:经纬度处理
* 创建人:loomo
* 修改时间:2014年9月20日
* @version
*/
public class MapDistance {
private static double EARTH_RADIUS = 6378.137;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
/**
* 根据两个位置的经纬度,来计算两地的距离(单位为KM)
* 参数为String类型
* @param lat1 用户经度
* @param lng1 用户纬度
* @param lat2 商家经度
* @param lng2 商家纬度
* @return
*/
public static String getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
Double lat1 = Double.parseDouble(lat1Str);
Double lng1 = Double.parseDouble(lng1Str);
Double lat2 = Double.parseDouble(lat2Str);
Double lng2 = Double.parseDouble(lng2Str);
double patm = 2;
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double difference = radLat1 - radLat2;
double mdifference = rad(lng1) - rad(lng2);
double distance = patm * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / patm), patm)
+ Math.cos(radLat1) * Math.cos(radLat2)
* Math.pow(Math.sin(mdifference / patm), patm)));
distance = distance * EARTH_RADIUS;
String distanceStr = String.valueOf(distance);
return distanceStr;
}
/**
* 获取当前用户一定距离以内的经纬度值
* 单位米 return minLat
* 最小经度 minLng
* 最小纬度 maxLat
* 最大经度 maxLng
* 最大纬度 minLat
*/
public static Map getAround(String latStr, String lngStr, String raidus) {
Map map = new HashMap();
Double latitude = Double.parseDouble(latStr);// 传值给经度
Double longitude = Double.parseDouble(lngStr);// 传值给纬度
Double degree = (24901 * 1609) / 360.0; // 获取每度
double raidusMile = Double.parseDouble(raidus);
Double mpdLng = Double.parseDouble((degree * Math.cos(latitude * (Math.PI / 180))+"").replace("-", ""));
Double dpmLng = 1 / mpdLng;
Double radiusLng = dpmLng * raidusMile;
//获取最小经度
Double minLat = longitude - radiusLng;
// 获取最大经度
Double maxLat = longitude + radiusLng;
Double dpmLat = 1 / degree;
Double radiusLat = dpmLat * raidusMile;
// 获取最小纬度
Double minLng = latitude - radiusLat;
// 获取最大纬度
Double maxLng = latitude + radiusLat;
map.put("minLat", minLat+"");
map.put("maxLat", maxLat+"");
map.put("minLng", minLng+"");
map.put("maxLng", maxLng+"");
return map;
}
public static void main(String[] args) {
//济南国际会展中心经纬度:117.11811 36.68484
//趵突泉:117.00999000000002 36.66123
System.out.println(getDistance("116.97265","36.694514","116.597805","36.738024"));
System.out.println(getAround("117.11811", "36.68484", "13000"));
//117.01028712333508(Double), 117.22593287666493(Double),
//36.44829619896034(Double), 36.92138380103966(Double)
}
}
package com.iloomo.util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
/**
* 说明:参数封装Map
* 创建人:loomo
* 修改时间:2014年9月20日
*/
public class PageData extends HashMap implements Map {
private static final long serialVersionUID = 1L;
public List<Map<String, String>> getBatchParam() {
return batchParam;
}
public void setBatchParam(List<Map<String, String>> batchParam) {
this.batchParam = batchParam;
}
public List<Map<String, String>> getChildParams() {
return childParams;
}
public void setChildParams(List<Map<String, String>> childParams) {
this.childParams = childParams;
}
List<Map<String, String>> childParams = null;
List<Map<String, String>> batchParam = null;
Map map = null;
HttpServletRequest request;
public PageData(HttpServletRequest request) {
this.request = request;
Map properties = request.getParameterMap();
Map returnMap = new HashMap();
Iterator entries = properties.entrySet().iterator();
Entry entry;
String name = "";
String value = "";
String business_id = request.getParameter("business_id");
while (entries.hasNext()) {
entry = (Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
value = values[i] + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
if (name.equals("offset") || name.equals("pageSize")) {
if (!value.equals("")) {
int num = Integer.valueOf(value);
returnMap.put(name, num);
}
} else if ("batch".equals(name)) {
batchParam = dealBathJsonParam(value,business_id);
} else if ("subParams".equals(name)) {
childParams = dealChildParams(value,business_id);
} else {
returnMap.put(name, value);
}
}
map = returnMap;
}
public List<Map<String, String>> dealBathJsonParam(String jsonString,String business_id) {
List<Map<String, String>> list = new ArrayList<>();
JsonUtil jsonUtil = new JsonUtil();
JSONArray jay = JSONArray.fromObject(jsonString);
for(int i =0;i<jay.size();i++){
Map<String, String> parameterMaps =jsonUtil.jsonObjToMap((JSONObject) jay.get(i));
parameterMaps.put("business_id",business_id);
list.add(parameterMaps);
}
return list;
}
public List<Map<String, String>> dealChildParams(String jsonString,String business_id) {
List<Map<String, String>> list = new ArrayList<>();
JsonUtil jsonUtil = new JsonUtil();
JSONArray jay = JSONArray.fromObject(jsonString);
for(int i =0;i<jay.size();i++){
Map<String, String> parameterMaps =jsonUtil.jsonObjToMap((JSONObject) jay.get(i));
parameterMaps.put("business_id",business_id);
list.add(parameterMaps);
}
return list;
}
public PageData() {
map = new HashMap();
}
@Override
public Object get(Object key) {
Object obj = null;
if (map.get(key) instanceof Object[]) {
Object[] arr = (Object[]) map.get(key);
obj = request == null ? arr : (request.getParameter((String) key) == null ? arr : arr[0]);
} else {
obj = map.get(key);
}
return obj;
}
public String getString(Object key) {
String string = null;
if (get(key) != null) {
string = get(key).toString();
}
return string;
}
@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
return map.put(key, value);
}
@Override
public Object remove(Object key) {
return map.remove(key);
}
public void clear() {
map.clear();
}
public boolean containsKey(Object key) {
// TODO Auto-generated method stub
return map.containsKey(key);
}
public boolean containsValue(Object value) {
// TODO Auto-generated method stub
return map.containsValue(value);
}
public Set entrySet() {
// TODO Auto-generated method stub
return map.entrySet();
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return map.isEmpty();
}
public Set keySet() {
// TODO Auto-generated method stub
return map.keySet();
}
@SuppressWarnings("unchecked")
public void putAll(Map t) {
// TODO Auto-generated method stub
map.putAll(t);
}
public int size() {
// TODO Auto-generated method stub
return map.size();
}
public Collection values() {
// TODO Auto-generated method stub
return map.values();
}
}
package com.iloomo.util;
import com.iloomo.constant.SysConstant;
import com.iloomo.entity.ClearBean;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* 分页模型,也是所有实体类的基类
*
* @author 陈龙波
*
*/
public class PagerModel implements ClearBean{
private int total; // 总数
private List list; // 分页集合列表
private int pageSize = SysConstant.PAGE_SIZE;// 每页显示记录数
private int offset; //偏移量
private int pagerSize;// 总页数
private int pageNo;//页码
protected String pagerUrl;//分页标签需要访问的ACTION地址
private String id;
public PagerModel(){
}
public PagerModel(PageData pd) {
int pageSize =pd.getString("rows")==null || pd.getString("rows")==""? this.getPageSize():Integer.parseInt(pd.getString("rows"));
int page = pd.getString("page")==null || pd.getString("page")==""? 1:Integer.parseInt(pd.getString("page"));
this.setPageNo(page);
this.setPageSize(pageSize);
if(this.getPageNo() > 1 ){
this.setOffset((this.getPageNo()-1)*this.getPageSize());
}
if (this.getOffset() < 0){
this.setOffset(0);
}
}
public String getPagerUrl() {
return pagerUrl;
}
public void setPagerUrl(String pagerUrl) {
this.pagerUrl = pagerUrl;
}
public int getPagerSize() {
return pagerSize;
}
public void setPagerSize(int pagerSize) {
this.pagerSize = pagerSize;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List getList() {
return list == null ? new LinkedList() : list;
}
public void setList(List list) {
this.list = list;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
/*
* (non-Javadoc)
*
* @see net.jeeshop.common.page.ClearBean#clear()
*/
public void clear() {
total = 0; // 总数
list = null; // 分页集合列表
offset = 0; // 偏移量
pagerSize = 0;// 总页数
// pagerUrl = null;//分页标签需要访问的ACTION地址
pageNo = 0;
id = null;
}
public String trim(String str){
if(str==null){
return null;
}
return str.trim();
}
public void clearList(List<String> list){
if(list==null || list.size()==0){
return;
}
list.clear();
list = null;
}
public void clearSet(Set<String> set){
if(set==null || set.size()==0){
return;
}
set.clear();
set = null;
}
public void clearListBean(List<PagerModel> list){
if(list==null || list.size()==0){
return;
}
for(int i=0;i<list.size();i++){
ClearBean item = list.get(i);
item.clear();
item = null;
}
list.clear();
list = null;
}
public void clearArray(String[] arr){
if(arr==null || arr.length==0){
return;
}
for(int i=0;i<arr.length;i++){
arr[i] = null;
}
arr = null;
}
@Override
public String toString() {
return "total:"+total+",list:"+list+",offset:"+offset;
}
}
package com.iloomo.util;
import java.io.File;
/**
* 说明:路径工具类
* 创建人:loomo
* 修改时间:2014年9月20日
* @version
*/
public class PathUtil {
private static String splitString(String str, String param) {
String result = str;
if (str.contains(param)) {
int start = str.indexOf(param);
result = str.substring(0, start);
}
return result;
}
/*
* 获取classpath1
*/
public static String getClasspath(){
String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../").replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(path.indexOf(":") != 1){
path = File.separator + path;
}
return path;
}
/*
* 获取classpath2
*/
public static String getClassResources(){
String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))).replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(path.indexOf(":") != 1){
path = File.separator + path;
}
return path;
}
}
package com.iloomo.util;
import java.lang.reflect.Field;
/**
* 说明:反射工具
* 创建人:loomo
* 修改时间:2014年9月20日
* @version
*/
public class ReflectHelper {
/**
* 获取obj对象fieldName的Field
* @param obj
* @param fieldName
* @return
*/
public static Field getFieldByFieldName(Object obj, String fieldName) {
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
return superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
}
}
return null;
}
/**
* 获取obj对象fieldName的属性值
* @param obj
* @param fieldName
* @return
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static Object getValueByFieldName(Object obj, String fieldName)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field field = getFieldByFieldName(obj, fieldName);
Object value = null;
if(field!=null){
if (field.isAccessible()) {
value = field.get(obj);
} else {
field.setAccessible(true);
value = field.get(obj);
field.setAccessible(false);
}
}
return value;
}
/**
* 设置obj对象fieldName的属性值
* @param obj
* @param fieldName
* @param value
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void setValueByFieldName(Object obj, String fieldName,
Object value) throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field field = obj.getClass().getDeclaredField(fieldName);
if (field.isAccessible()) {
field.set(obj, value);
} else {
field.setAccessible(true);
field.set(obj, value);
field.setAccessible(false);
}
}
}
package com.iloomo.util;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
public class RestTemplateUtil {
/**
* 创建指定字符集的RestTemplate
*
* @param charset
* @return
*/
public static RestTemplate getInstance(String charset) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName(charset)));
return restTemplate;
}
}
\ No newline at end of file
......@@ -4,7 +4,6 @@ import java.math.BigInteger;
/**
* 权限计算帮助类
* @author fh qq 3 1 3 5 96790[青苔]
* 修改日期:2015/11/2
*/
public class RightsHelper {
......
package com.iloomo.util;
/**
* 字符串相关方法
*
*/
public class StringUtil {
/**
* 将以逗号分隔的字符串转换成字符串数组
* @param valStr
* @return String[]
*/
public static String[] StrList(String valStr){
int i = 0;
String TempStr = valStr;
String[] returnStr = new String[valStr.length() + 1 - TempStr.replace(",", "").length()];
valStr = valStr + ",";
while (valStr.indexOf(',') > 0)
{
returnStr[i] = valStr.substring(0, valStr.indexOf(','));
valStr = valStr.substring(valStr.indexOf(',')+1 , valStr.length());
i++;
}
return returnStr;
}
/**获取字符串编码
* @param str
* @return
*/
public static String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s = encode;
return s;
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return "";
}
/**获取文件名(首字母大写)
* @param str
* @return
*/
public static String getfirstLetterUpperByTableName(String primaryTableName) {
String firstLetterUpperTableName = primaryTableName.substring(0, 1).toUpperCase() + primaryTableName.substring(1);
StringBuffer sbf2 = new StringBuffer();
if (firstLetterUpperTableName.contains("_")) {
String[] names = firstLetterUpperTableName.split("_");
for (String name : names) {
name = name.substring(0, 1).toUpperCase() + name.substring(1);
sbf2.append(name);
}
} else {
sbf2.append(firstLetterUpperTableName);
}
firstLetterUpperTableName = sbf2.toString();
return firstLetterUpperTableName;
}
/**获取驼峰式命名
* @param str
* @return
*/
public static String getHumpName(String tableName){
StringBuffer sbf = new StringBuffer();
if(tableName.contains("_")){
String[] names = tableName.split("_");
for(String name : names){
if(sbf.length() == 0){
sbf.append(name);
}else{
name = name.substring(0, 1).toUpperCase() + name.substring(1);
sbf.append(name);
}
}
}else{
sbf.append(tableName);
}
return sbf.toString();
}
}
package com.iloomo.util;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 说明:常用工具
* 创建人:loomo
* 修改时间:2015年11月24日
* @version
*/
public class Tools {
/**
* 随机生成六位数验证码
* @return
*/
public static int getRandomNum(){
Random r = new Random();
return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
}
/**
* 检测字符串是否不为空(null,"","null")
* @param s
* @return 不为空则返回true,否则返回false
*/
public static boolean notEmpty(String s){
return s!=null && !"".equals(s) && !"null".equals(s);
}
/**
* 检测字符串是否为空(null,"","null")
* @param s
* @return 为空则返回true,不否则返回false
*/
public static boolean isEmpty(String s){
return s==null || "".equals(s) || "null".equals(s);
}
/**
* 字符串转换为字符串数组
* @param str 字符串
* @param splitRegex 分隔符
* @return
*/
public static String[] str2StrArray(String str,String splitRegex){
if(isEmpty(str)){
return null;
}
return str.split(splitRegex);
}
/**
* 用默认的分隔符(,)将字符串转换为字符串数组
* @param str 字符串
* @return
*/
public static String[] str2StrArray(String str){
return str2StrArray(str,",\\s*");
}
/**
* 按照yyyy-MM-dd HH:mm:ss的格式,日期转字符串
* @param date
* @return yyyy-MM-dd HH:mm:ss
*/
public static String date2Str(Date date){
return date2Str(date,"yyyy-MM-dd HH:mm:ss");
}
/**
* 按照yyyy-MM-dd HH:mm:ss的格式,字符串转日期
* @param date
* @return
*/
public static Date str2Date(String date){
if(notEmpty(date)){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new Date();
}else{
return null;
}
}
/**
* 按照参数format的格式,日期转字符串
* @param date
* @param format
* @return
*/
public static String date2Str(Date date,String format){
if(date!=null){
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}else{
return "";
}
}
/**
* 把时间根据时、分、秒转换为时间段
* @param StrDate
*/
public static String getTimes(String StrDate){
String resultTimes = "";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now;
try {
now = new Date();
Date date=df.parse(StrDate);
long times = now.getTime()-date.getTime();
long day = times/(24*60*60*1000);
long hour = (times/(60*60*1000)-day*24);
long min = ((times/(60*1000))-day*24*60-hour*60);
long sec = (times/1000-day*24*60*60-hour*60*60-min*60);
StringBuffer sb = new StringBuffer();
//sb.append("发表于:");
if(hour>0 ){
sb.append(hour+"小时前");
} else if(min>0){
sb.append(min+"分钟前");
} else{
sb.append(sec+"秒前");
}
resultTimes = sb.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return resultTimes;
}
/**
* 写txt里的单行内容
* @param filePath 文件路径
* @param content 写入的内容
*/
public static void writeFile(String fileP,String content){
String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../"; //项目路径
filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
if(filePath.indexOf(":") != 1){
filePath = File.separator + filePath;
}
try {
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
BufferedWriter writer=new BufferedWriter(write);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 验证邮箱
* @param email
* @return
*/
public static boolean checkEmail(String email){
boolean flag = false;
try{
String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}
/**
* 验证手机号码
* @param mobiles
* @return
*/
public static boolean checkMobileNumber(String mobileNumber){
boolean flag = false;
try{
Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
Matcher matcher = regex.matcher(mobileNumber);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}
/**
* 检测KEY是否正确
* @param paraname 传入参数
* @param FKEY 接收的 KEY
* @return 为空则返回true,不否则返回false
*/
public static boolean checkKey(String paraname, String FKEY){
paraname = (null == paraname)? "":paraname;
return MD5.md5(paraname+DateUtil.getDays()+",fh,").equals(FKEY);
}
/**
* 读取txt里的单行内容
* @param filePath 文件路径
*/
public static String readTxtFile(String fileP) {
try {
String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../"; //项目路径
filePath = filePath.replaceAll("file:/", "");
filePath = filePath.replaceAll("%20", " ");
filePath = filePath.trim() + fileP.trim();
if(filePath.indexOf(":") != 1){
filePath = File.separator + filePath;
}
String encoding = "utf-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding); // 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
return lineTxt;
}
read.close();
}else{
System.out.println("找不到指定的文件,查看此路径是否正确:"+filePath);
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
}
return "";
}
public static void main(String[] args) {
System.out.println(getRandomNum());
}
}
package com.iloomo.util;
import java.util.UUID;
public class UuidUtil {
public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
"9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z" };
public static String generateShortUuid() {
StringBuffer shortBuffer = new StringBuffer();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 8; i++) {
String str = uuid.substring(i * 4, i * 4 + 4);
int x = Integer.parseInt(str, 16);
shortBuffer.append(chars[x % 0x3E]);
}
return shortBuffer.toString();
}
public static String get32UUID() {
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
public static String get16UUID() {
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
public static void main(String[] args) {
System.out.println(get32UUID());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment