工厂、单例、模板 一次结合使用
生活随笔
收集整理的這篇文章主要介紹了
工厂、单例、模板 一次结合使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?工廠:
/*** 創建各個 單例csvReader的工廠* @author wj* @date 2017-1-7**/ public class CsvReaderAndPersistFactory {// 定義一個Map用于保存第一次創建對象時的實例private static final Map<String, Object> objectMap = Maps.newHashMap();private CsvReaderAndPersistFactory(){}@SuppressWarnings("rawtypes")public synchronized static <T extends CsvFileReaderAndPersist> T create(Class<T> c ,String type) throws Exception {CsvFileReaderAndPersist single = null;String className = null;className = c.getName();try {if (!objectMap.containsKey(className)) {Class class1 = Class.forName(className);// 獲得有參構造Constructor constructor = class1.getDeclaredConstructor(String.class);// 設置有參構造是可訪問的constructor.setAccessible(true);// 產生一個實例對象。single = (CsvFileReaderAndPersist) constructor.newInstance(type);objectMap.put(className, single);}} catch (Exception e) {e.printStackTrace();throw e;}return (T) objectMap.get(className);}}?
模板方法:
/*** 讀csv * @author wj* @date 2017-1-1**/ public abstract class CsvFileReaderAndPersist<T> {private static Logger logger = LoggerFactory.getLogger(CsvFileReaderAndPersist.class);protected String type;/*** @param fileName*/public void readCsvFileAndPersist(String fileName) {FileReader fileReader = null;CSVParser csvFileParser = null;//創建CSVFormat(header mapping) // CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER);CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(getHeader()).withSkipHeaderRecord(); //withSkipHeaderRecord 跳過第一行標題欄try {//初始化FileReader objectfileReader = new FileReader(fileName);//初始化 CSVParser objectcsvFileParser = new CSVParser(fileReader, csvFileFormat);//CSV文件recordsList<CSVRecord> csvRecords = csvFileParser.getRecords(); // CSVdataPersist(csvRecords);logger.info("---------------------成功導入【"+type+"】 "+csvRecords.size()+" 條數據------------");} catch (Exception e) {e.printStackTrace();logger.error("導入出錯:"+e.getMessage());return ;} finally {try {fileReader.close();csvFileParser.close();} catch (IOException e) {e.printStackTrace();}}}protected abstract String [] getHeader() ;// protected abstract List<T> dataSetter( List<CSVRecord> records);protected abstract void dataPersist(List<CSVRecord> records);public String getVal(Map<String, Object> map, String param) {return map.get(param) == null ? null : map.get(param).toString();} }?
單例 + 模板方法:
?
/*** 人員* @author wj**/ public class UserCsvFileReader extends CsvFileReaderAndPersist<Map<String,Object>> {public static final String pwd = "jsxfdj123456";private static Logger logger = LoggerFactory.getLogger(UserCsvFileReader.class);private List<String> nullOrgids = Lists.newArrayList();private List<String> dupids = Lists.newArrayList();//CSV文件頭//"ID","JGMC","JGJC","JGNBID","JGLB","JGDM","XZQHDM","JGDZ","YZBM","LXDH","CZHM","LXR","QTSJBM","SSXFJGDM","JGLX","JGXZDM","JGTREE","QZ","SSYM","GIS_X","GIS_Y","GIS_H","XQGLID","GLID","JGMS","JLZT","SJC","BZ","SJBB","CJSJ","BJSJ","YWXTBSID","YWQH","JGCXZT","JGCXSJ","BYZD1","BYZD2","BYZD3","BYZD4","BYZD5","BYZD6","BYZD7","BYZD8","BYZD9","BYZD10","ZP"protected static final String [] FILE_HEADER = {"ID","YHBH","XM","YHZH","BGXTZH","RYXH","YHLB","YHJBID","ZZMM","MZ","CSRQ","XB","JZID","JXID","ZWID","GWID","SSJG","SSDW","ZGDW","BMBM","YHZT","JZJDJG","JZJDDW","GWQY","SFZT","ZZDH","JTDH","SJHM","YXZH","XNH","YJFJDX","YHQZ","RZFS","JGZSMJ","YHZPSMJ","YHLCZT","SXRQ","SHXSJ","GZFW","JGZQFRQ","JGZID","JRSFZH","BBDJ","XBB","ADDACC","ADDACCNAME","ADDTIME","ADDIP","CHGACC","CHGACCNAME","CHGTIME","CHGIP","DELETED","LSJGID","YJXSBJ","TXLXSBJ","DXFSBJ","FLAG0","FLAG1","SFZW","QJID","QJLX","WJDX","RYZT","SJBB","CJSJ","BJSJ","YWXTBSID","ZHID","SIGNATUREFLAG","XZQH" };static JdbcTemplate jdbcTemplate = (JdbcTemplate) ContextUtil.getApplicationContext().getBean("jdbcTemplate");private UserCsvFileReader(String type){super.type = type;}@Overrideprotected String[] getHeader() {return FILE_HEADER;}@Overrideprotected void dataPersist( List<CSVRecord> csvRecords) {String sql = "select * from JSXF_ORG_JCJ t ";final List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);Map<String,String> lookup_nbid_orgid = Maps.newHashMapWithExpectedSize(list.size());Map<String,String> lookup_orgid_orgname = Maps.newHashMapWithExpectedSize(list.size());for (Map<String, Object> m : list) {String JGNBID = getVal(m, "JGNBID");String ORG_ID = getVal(m, "ORG_ID");String ORG_NAME = getVal(m, "ORG_NAME");lookup_nbid_orgid.put(JGNBID, ORG_ID);lookup_orgid_orgname.put(ORG_ID, ORG_NAME);}String SQL_CREAT_ALARM = Contants.sql_user; // String SQL_CREAT_ALARM = " INSERT INTO JSXF_ORG_JCJ2(ORG_ID,JGMC,ORG_NAME,JGNBID,JGDM,JGDZ,YZBM,LXDH,CZHM,LXR,JGXZDM,JGTREE,JGMS,ORG_LONGITUDE,ORG_DIMENSION,GIS_H,GLID,XQGLID,SSYM,ZP,BZ,JGCXZT,YWXTBSID,ORG_CREATE_TIME,SJBB,JGCXSJ) " // + " VALUES(?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?, ?,?,?,? )";if(!CollectionUtils.isEmpty(csvRecords)){int count = 0;for(CSVRecord record : csvRecords){/* T_BASE_USER 所需要的所有字段 */String USERID =record.get("YHZH"); // '用戶id';String USERNAME =record.get("XM");// '用戶名稱';if(StringUtils.isEmpty(USERNAME)){//可以記錄下個數continue;}String SEX =record.get("XB");// '性別';// String PWD =record.get("ID");// '密碼'; //沒有找到密碼字段String EMAIL =record.get("YXZH");// 'EMAIL';String PHONE =record.get("SJHM");// '聯系電話';String NATION =record.get("MZ");// '民族';String POLITICAL=record.get("ZZMM");// '整治面貌';String PHOTO =record.get("YHZPSMJ");// '照片';String BIRTHDAY = record.get("CSRQ");// '生日';Date BIRTHDAY_date = DateUtils.parseDate(BIRTHDAY);String JOINTIME=record.get("ADDTIME"); // '加入單位時間';Date JOINTIME_date = DateUtils.parseDate(JOINTIME);String COMPANYID =record.get("SSDW");// '所在單位ID';String DEPARTMENT =record.get("BMBM");// '所在部門';// String ADDRESS =record.get("ID");// '家庭住址'; //沒有對應字段// String LUTIME=record.get("ID"); // '最后登陸時間'; //沒有對應字段String LOCKED = record.get("SFZT");// '是否鎖定';String USER_TYPE =record.get("YHLB");// '用戶類型(社區人員、單位人員、消防分管人員、管理員)'; // 他們:用戶類別: ‘0’干部 ‘1’士官 ‘2’戰士 ‘3’民警// String ROLE_ID =record.get("ID");// '角色ID'; //沒有對應字段String SORTID=record.get("RYXH"); // '排序'; //數值太大,無法轉longString CARD_ID =StringUtils.trim(record.get("JRSFZH"));// '身份證號';String CREATETIME =record.get("CJSJ");// '創建時間';Date CREATETIME_date = DateUtils.parseDate(CREATETIME);String AREA_SELF=record.get("XZQH"); // '所屬區域';// String IMSI =record.get("ID");// '手機端登錄參數'; //沒有對應字段// String ORG_ID =record.get("ID");// '中隊id'; //沒有對應字段String ORG_ID =getOrgId(lookup_nbid_orgid, record.get("SSJG"));// '中隊id'; //可能為null,沒有找到對應ORG_IDString MENNU_ID =record.get("ZWID");// '職務'; String pwd = CryptoUtils.MD5().digestStr(UserCsvFileReader.pwd);String role_id = getRoleId(lookup_orgid_orgname, ORG_ID);try{jdbcTemplate.update(SQL_CREAT_ALARM, USERID, USERNAME,SEX,EMAIL,PHONE,NATION,POLITICAL,PHOTO,BIRTHDAY_date,JOINTIME_date,COMPANYID,DEPARTMENT,Integer.valueOf(LOCKED),USER_TYPE,0,CARD_ID,CREATETIME_date,AREA_SELF,ORG_ID,MENNU_ID,pwd,role_id);count++;}catch(org.springframework.dao.DuplicateKeyException e){ //如果沖突 繼續插下面的dupids.add(USERID);count--;}}logger.info("【用戶】 成功導入 "+count+" / "+csvRecords.size()+" 條數據,但是其中 SSJG為:["+StringUtils.join(nullOrgids, ",") +"] 在系統中沒有對應orgId,同時對應角色也為null。其中重復用戶ID: ["+ StringUtils.join(dupids, ",")+" ]");}}private String getOrgId(Map<String,String> map, String nbid){String orgId = map.get(nbid);if( orgId== null){nullOrgids.add(nbid);}return orgId;}//copy from SynTest.java line:631private String getRoleId(Map<String,String> map, String orgid){if(orgid ==null){return null;}String org_name = map.get(orgid);String role_id = "manage";// 默認給支隊權限if (org_name.contains("中隊")) {role_id = "comm";} else if (org_name.contains("大隊")) {role_id = "manageBrigade";} else if (org_name.contains("總隊")) {role_id = "manageCorps";}return role_id;}/*** @param args* @throws Exception */public static void main(String[] args) throws Exception{// new OrgCsvFileReader("機構信息").readCsvFileAndPersist(Contants.ORG_DATA_PATH); // new UserCsvFileReader("用戶信息").readCsvFileAndPersist(Contants.USER_DATA_PATH);CsvFileReaderAndPersist user = CsvReaderAndPersistFactory.create(UserCsvFileReader.class,"用戶信息");user.readCsvFileAndPersist(Contants.USER_DATA_PATH);}}?
?
結合起來,功能:不同類型數據的讀取CSV、以及持久化
?
總結
以上是生活随笔為你收集整理的工厂、单例、模板 一次结合使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1.网址推荐——专利下载
- 下一篇: OPS