com.xxxxx.common.utils
ArrayUtils.java:
/**
*数组扩展类,可以动态增加数组的长度
*/
public final class ArrayUtils extends org.apache.commons.lang.ArrayUtils{
//扩展类型转换
public static <T extends Serializable> T add(Class<T> clazz,Object[] array,Object element)
{return clazz.cast( add(array,element) );}
//反序
public static <T> T[] reversez(T[] array)
{reverse(array);
return array;}
//数组求和
public static int sumNum(int[] array){
int sum = 0;
for(int i : array){
sum += i;
}
return sum;
}
public static float sumNum(int[] array){
float sum = 0;
for(float f : array){
sum +=f;
}
return sum;
}
//比较2个数组是否有相同部分
public static boolean hasIntersection(String[] arr1, String[] arr2){
for(String a1 : arr1){
for(String a2 : arr2){
if(a1.equals(a2)){ return true;}
}
}
}
}
明天继续补,剩下的.尤其是StringUtils.一共58个工具类.
PropertiesUtils
public class PropertiesUtil{
protected static final Map<String ,Properties> properties = new ConcurrentHashMap<>();
//1:加载配置文件
public static Properties loadRawProp(String path){
Properties props = new Properties();
InputStream in = ProperiesUtil.class.getResourceAsStream(path); //比如:path= "/config:properties"
try{ props.load(in)}catch(IOException e){ e.printStackTrace();}finally{
try{ if(in != null) in.close(); in = null; } catch(IOException e){e.printStackTrace();}
}
return props;
}
//2:加载配置文件
public static Properties loadProp(String path){
Properties p = properties.get(path);
if( p == null ){ p = loadRawProp(path); properties.put(path,p); }
return p;
}
//3:获取apllication文件的内容
public static String getAppContext(String key){
Properties prop = loadProp("/config.properties");
String value = prop.getProperty(key);
return (value == null)? "" ::value;
}
//4:获取apllication文件的内容,无内容,返回缺省值 (String)
public static String getAppContextString(String key, String defaultValue){
String value = getAppContext(key);
return StringUtils.isNotNullOrEmptyStr(value) ? value : defaultValue;
}
//获取apllication文件的内容,无内容,返回缺省值(int)--项目中设置连接池最大链接数用到。
public static Integer getAppContextInt(String key, int defaultValue){
try{ String value = getAppContext(key);
return Integer.parseInt(value);
}catch(Exception e){return defaultValue;}
}
//获取apllication文件的内容,无内容,返回缺省值(long)
public static Long getAppContextInt(String key, long defaultValue){
try{ String value = getAppContext(key);
return Long.parseLong(value);
}catch(Exception e){return defaultValue;}
}
//5:获取mailmodule文件的内容-----我没用过
public static String getMailContext(String key){
Properties prop = loadProp("/mailmodual.properties");
String value = prop.getProperty(key);
return (value == null)?"" : value;
}
//6:获取msgmodule文件的内容-----我依然没用过
public static String getMsgContext(String key){
Properties prop = loadProp("/sendmessages.properties");
String value = prop.getProperty(key);
return (value == null)?"" : value;
}
}
嗯,第二个完成。
BeanUtils
public class BeanUtils extends org.apache.commons.beanutils.BeanUtils{
//1:转换属性名--把首字母为大写(好匹配方法名)
private static final String converPropertyName(String propertyName) throws Exception{
if(propertyName == null || propertyName.length() == 0){ throw new Exception("属性名必须指定");}
String first = propertyName .substring(0,1).toUpperCase();//首字母
String str = propertyName.substring(1);//剩下的部分
String newpropertyName = String.format("%s%s",first,str);
return newpropertyName;
}
//2:复制属性名(1值设置给2)--干嘛用?、难道new对象,把现有的bean复制给他,这样就有值?项目中 编辑保存的时候用了一次,可以无视
public static final void copyNoBlank(Object bean1,Object bean2)throws Exception{
if( !bean1.getClass().equals(bean2.getClass()) ){throw new Exception("拷贝类型不一致");}
List<properties> properties = BeanUtils.getProperties(bean1,String.class);
for(String name : properties ){
Object value = BeanUtils.getValue(bean1,name);
if(value instanceof String){
String val = (String) value;
if(val != null) BeanUtils.setValue(bean2,name,val);
}
}
}
//3.获取Bean的属性名 -----这个常用,用到了反射。
public static final List<String> getProperties(Object bean ,Class<?> clazz) throws Exception{
Field[] fields = bean.getClass().getDeclaredFields();
List<String> retlist = new LinkedList<>();
//遍历得到的 属性数组
for(Field field :fields){
//获取属性的泛型,
if(field.getGenericType().toString.contains(clazz.getName())){
retlist.add( field.getName() );
}
}
return retlist;
}
//4:设置属性值 (value应该是set方法的入参)
public static final void setValue(Object bean ,String propertyName,Object value)throws Exception{
String methodName = String.format("set%s",converPropertyName(propertyName));
Method m = bean.getClass().getMethod(methodname,value.getClass());
m.invoke(bean,new Object[]{value});
}
//5:获取属性值
public static final Object getValue(Object bean,String propertyName)throws Exception{
String methodName = String.format("get%s",converPropertyName(propertyName));
Method m = bean.getClass().getMethod(methodName);
Object value = m.invoke(bean);
return value;
}
//6:获取树形列表
//TreeItf 是一个接口:getRowId(); getParentRowId();getChildren();setChildren(List<TreeItf children>);
public static final List<TreeItf> getTreeList(List<TreeItf> allList,String rootId){
List<TreeItf> retlist = new LinkedList<>();
if(allList == null || allList.isEmpty()){ return retlist;}
//遍历树形列表
for(TreeList item : allList){
if( (StringUtils.isBlank(rootId) && StringUtils.isBlank(item.getParentRowId()) ) ||
rootId.equals(item.getParentRowId()) )
item.setChildren( getTreeList(allList,item.getRowId()) );
retlist.add(item);
}
}
return retlist;
//7:main 方法 测试用
public static void main (String[] args)throws Exception{
UserModel user = new UserModel();
System.out.println(getProperties(user,String.class));
}
}
第三个完成,yeah.
CookieUtils工具类
public class CookieUtils{
public static final int COOKIE_MAX_AGE = 7*24*3600;//一周
public static final int COOKIE_HALF_HOUR= 30*60; //30min
//1:根据cookie名称得到cookie对象,若不存在返回null
public static Cookie getCookie(HttpServletRequest request,String name) {
Cookie[] cookies = request.getCookies();
if(isEmptyArray(cookies)){return null;}
Cookie cookie = null;
//遍历cookie数组
for(Cookie c :cookies){
if(name.equals(c.getName())){cookie = c; break; }
}
return cookie;
}
//2:根据cookie 名称直接得到cookie值
public static String getCookieValue(HttpServletRequest request,String name){
Cookie cookie = getCookie(request,name);
if(cookie != null ) return cookie.getValue();
return null;
}
//3:移除cookie (根据cookie名称)
public static void removeCookie(HttpServletRequest request,HttpServletResponse response ,String name){
if(name == null ) return ;
Cookie cookie = getCookie(request,name);
if(null != cookie ){
cookie.setPath("/");
cookie.setValue("");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
//4.添加一条新的cookie,可以指定过期时间(单位:秒)
public static void setCookie(HttpServletResponse response response,String name,String value ,int maxValue){
if(StringUtils.isBlank(name)) return ;
if(null == value) value = "";
Cookie cookie = new Cookie(name,value);
cookie.setPath("/");
if(maxValue != 0 ) {cookie.setValue(maxValue);} else{cookie.setMaxAge(COOKIE_HALF_HOUR);}
response.addCookie(cookie);
try{response.flushBuffer();}catch(IOException e){e.printStackTrace();}
}
//5.添加一条新的cookie,默认30分钟过期时间
public static void setCookie(HttpServletResponse response response,String name,String value){
setCookie(response,name,value,COOKIE_HALF_HOUR);
}
//6:把cookie 封装到map里
public static Map<String ,Cookie> getCookieMap(HttpServletRequest request){
Map<String,Cookie> cookieMap = new HashMap<>();
Cookie[] cookies = request.getCookies();
if ( ! isEmptyArray(cookies)){
for(Cookie c :cookies){
cookieMap.put(cookie.getName(),cookie);
}
}
return cookieMap;
}
//7:判断cookie数组是否为空
private static boolean isEmptyArray(Cookie[] cookies){
return cookies == null || cookies.length == 0;
}
}
SpringUtils 如下:
/*一组getBean方法*/
@Service
public class SpringUtils implements BeanFactoryAware{
static Logger log = LoggerFactory.getLogger(SpringUtils.class);
private static BeanFactory beanFactory;
//1:通过Bean的id从上下文中拿出该对象
public static Object getBean(String beanId){
return beanFactory == null ? null :beanFactory.getBean(beanId);
}
通过Bean的id从上下文中拿出该对象
public static <T> T getBean(Class<T> clazz, String beanId){
return beanFactory == null ? null :clazz.cast(beanFactory.getBean(beanId));
}
//2:通过bean的type从上下文中拿出该对象
public static <T> getBean(Class<T> clazz){
return beanFactory == null ? null :beanFactory.getBean(clazz);
}
通过bean的type从上下文中拿出该对象 -该方法整个项目没用到,啥用?
public void setBeanFactory(BeanFactory beanFactory)throws Exception{
SpringUtils.beanFactory = beanFactory;
log.info("Bean Factory has been saved in a static variable SpringUtils !");
}
//场景 SystemService service = springUtils.getBean("SystemService")//这个是不是类似 注入 啊。因为 @Service("SystemService") SystemServiceImpl上有这样的注解。
}
SystemUtils 系统相关(有点多)
public class SystemUtils{
//常量--就一个日志知道点.其他的干啥的?其他的也是放到 session中 缓存起来。
public static final Logger log = LoggerFactory.getLogger(SystemUtils.class.getName());
public static final String SESSION_USER = "SESSION_USER ";
public static final String SESSION_INDUSTRY/ORG/CONFIG = "SESSION_INDUSTRY/ORG/CONFIG";
public static final String CACHE_CONFIG_LIST="CACHE_CONFIG_LIST";
public static final String APPLICATION_PERMISSION="APPLICATION_PERMISSION";
public static final String SESSION_DATA_BEAN="SESSION_DATA_BEAN";
public static final String SESSION_POSITION_REF_LIST="SESSION_POSITION_REF_LIST";
//ThreadLocal相关 ,涉及线程安全. set,get 这里一样的我就只写一个
1:protected static final ThreadLocal<String > sessionId = new ThreadLocal<>();
public static final void setSessionId(String sessionId) throws Exception{ SystemUtils.sessionId.set(sessionId); }
public static final String getSessionId(){ return SystemUtils.sessionId.get(); }
2: protected static final ThreadLocal<HttpServletRequest> request= new ThreadLocal<>();
3:protected static final ThreadLocal<RequestContext> requestContext= new ThreadLocal<>();
public static final RequestContext getRequestContext(){
if(requestContext.get() == null) {
HttpServletRequest request = getHttpServletRequest();
requestContext.set(new RequestContext(request));
}
return requestContext.get();
}
4:protected static final ThreadLocal<CurrentConfigModel> currentConfigModel= new ThreadLocal<>();
//该get方法经常用 作用:获取当前配置信息
public static final CurrentConfigModel getCurrentConfigModel() throws Exception{
CurrentConfigModel obj = getHttpServletRequest().getSession.getAttribute(SESSION_CONFIG);
if(obj == null ){
obj= new CurrentConfigModel();
getHttpServletRequest().getSession().setAttribute(SESSION_CONFIG,obj);
}
return obj;
}
//该set方法 作用为 设置用户缓存 存在 session 中
public static void setCurrentConfigModel(CurrentConfigModel config) throws Exception{
getHttpServletRequest().getSession().setAttribute(SESSION_CONFIG.config);
}
5:protected static final ThreadLocal<UserModel> userModel= new ThreadLocal<>();
//该get方法经常用 作用:获取当前用户信息
public static UserModel getUserModel() throws Exception{
if(getHttpServletRequest() == null ) return userModel.get();
if(getHttpServletRequest().getSession() == null ) return null;
Obejct obj = getHttpServletRequest().getSession.getAttribute(SESSION_USER);
return (UserModel)obj;
}
//该set方法 作用为 设置用户缓存 存在 session 中
public static void setUserModel(UserModel user) throws Exception{
log.info( String.format("%s == %s"),user.getLoginName(),user.getLoginPwd()) );
if(getHttpServletRequest() == null){userModel.set(user) ;return ;}//说明不是第一次登陆。
getHttpServletRequest().getSession().setAttribute(SESSION_USER,user);
}
//该 clear方法是为了清除用户缓存
public static void clearUserModel() throws Exception{
getHttpServletRequest().getSession().removeAttribute(SESSION_USER);
}
//6:protected static final ThreadLocal<SiebelDataBean> siebelDataBean= new ThreadLocal<>(); //get set 我就不写了。
//11获取行业信息 --这个也缓存到session中,但 没有涉及线程安全。
//用户信息涉及 ,行业信息不涉及。那我怎么判断?/是因为用户信息经常修改吗?行业信息不经常变动,这个原因吗?/
public static List<IndustryModel> getIndustryList() throws Exception{
return (List<IndustryModel>)getHttpServletRequest().getSession().getAtrribute(SESSION_INDUSTRY);
}
//设置行业信息缓存
public static void setIndustryList(List<IndustryModel> list) throws Exception{
getHttpServletRequest().getSession().setAttribute(SESSION_INDUSTRY,list);
}
//12获取缓存列表 (ConfigModel:埋点信息 String value;值 String description ;描述,List<String> notKeys; extends BaseModel .说实话我第一次接触埋点。)
public static final Map<String ,Object> cacheList = new RedisMap<String,Object>(SystemUtils.class);
public static List<ConfigModel> getConfigList() throws Exception{
return (List<ConfigModel>)cacheList.get(CACHE_CONFIG_LIST);
}
public static String getConfig(String key){
try{
for( ConfigModel config : getConfigList() ){
if(key.equals(config.getRowId())){ return config.getValue();}
}
}catch(Exception e ){e.printStackTrace();}
return null;
}
//设置缓存列表
public static void List<ConfigModel> setConfigList(List<ConfigModel> list) throws Exception{
cacheList.put(CACHE_CONFIG_LIST,list);
}
//13 获取职位列表
public static List<String,String> getPositionRefList() throws Exception{
return (List<String,String>)getHttpServletRequest().getSession().getAttribute(SESSION_POSITION_REF_LIST);
}
public static List<String> getPositionRefStringList() throws Exception{
List<String> retlist = new LinkedList<>();
List<Map<String,String>> list = getPositionRefList();
if(list == null ) return retlist;
for( Map<String,String> map : list){ retlist.add(map.get("positionId"));}
return retlist;
}
//14:获取国际化信息--一般properties用于获取一般属性配置文件,ResourceBundle用于获取国际化属性信息
public static final String getMessage(String code){
try{
return getMessages().get( String.format("error.code.%s",code) );//其实就是 error.code.xxxxxx
}catch(Exception e ){
return code;
}
}
public static final Map<String,String> getMessages() throws Exception{
//读取国际化属性配置文件
ResourceBundle resourceBundle = ResourceBundle.getBundle("message,message",getRequestContext.getLocale()); //师父说 这个是随浏览器变化
//ResourceBundle resourceBundle = ResourceBundle.getBundle("message,message",Locale.getDefault()); //这个是 随操作系统变化
Enumeration<String> keys = resourceBundle.getKeys();//获取配置文件中所有key
Map<String ,String> retMap = new HashMap<>();//创建一个用来装返回数据的map集合
while( keys.hasMoreElements() ){
String key = keys.nextElement(); //得到每一个key
String value = resourceBundle.getString(key); //得到每一个value
retMap.put(key,value);
}
return retMap;
}
}
这里需要说明下那个 ResourceBundle resourceBundle = ResourceBundle.getBundle(“message.message”,getRequestContext.getLocale());
我先开始看不懂 message.message,项目下路径为:web层
src/main/resources /message/message_zh.properties message_ch.properties
我不明白为什么这样可以扫描到这个文件?、而且我做了测试,确实扫描的是这个文件。
后来上网查看,才知道答案在这里:
命名规则按照:资源名+语言国别.properties
ResourceBundle bundle = ResourceBundle.getBundle("res", new Locale("zh", "CN"));
1
**其中new Locale(“zh”, “CN”);这个对象就告诉了程序你的本地化信息,就拿这个来说吧:程序首先会去classpath下寻找res_zh_CN.properties;若不存在,那么会去找res_zh.properties,若还是不存在,则会去寻找res.properties,要还是找不到的话,那么就该抛异常了:MissingResourceException.**
参考:https://blog.youkuaiyun.com/haiyan0106/article/details/2257725