我鍾愛的Utils-Array,Properties,Bean,Cookie,Spring,System

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.csdn.net/haiyan0106/article/details/2257725
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章