裝置CSV檔案匯入,型別轉換加try...catch...

ZHOU_VIP發表於2018-10-19
cvStr = this.getCellValue(row, j++);
if (cvStr == null || cvStr.trim().equals("")) {
	// 7緯度
	osmDev.setGpslat(0D);
} else {
	try {
		osmDev.setGpslat(Double.valueOf(cvStr.trim()));
	} catch (Exception err) {
		logger.error("gpsln parse error: " + cvStr.trim());
	}
}

全程式碼:

/**
 * //18.10.11加裝置的批量匯入
 * 裝置批量(csv檔案)匯入
 * 
 * @param request
 * @param response
 * @return
 */
@RequestMapping("devbatchImport")
@ResponseBody
public ClaaAjaxResult devbatchImport(@RequestParam(value="dev_import_file", required=false) CommonsMultipartFile file, 
		HttpServletRequest request, HttpServletResponse response) throws Exception 
{
	if(!checkAccessRight(Constants.OPCODE_OSM_DEV_MOD)){
		this.addSmLog(MODULE_NAME, SmLogBean.OP_RET_FAIL, "許可權不足", "嘗試批量匯入裝置資訊", "");
		throw this.genNoRightException();
	}
	ClaaAjaxResult ret = new ClaaAjaxResult();
	String randomStr = Long.toUnsignedString(UUID.randomUUID().getLeastSignificantBits());
	try{		
		this.setProgress(randomStr, 1, true, "開始匯入裝置資訊...");
		List<OsmDev> devList = new ArrayList<OsmDev>();
		// 獲得原始檔名  
		String fileName = file.getOriginalFilename();  	        
		logger.info("devbatchImport(): file name=" + fileName);          
		// 新檔名.
		String filePath = this.getUploadPath(request)+randomStr+"_"+ fileName;
		filePath = filePath.replaceAll("\\\\", "/");
		logger.info("filePath: "+filePath);
		// 上傳
		File f = new File(filePath);
		file.transferTo(f);
		// 非同步解析檔案csv
		DevImportCSVFileParser gwEuiCsvParser = new DevImportCSVFileParser(f.getAbsolutePath());
		List<OsmDev> csvEuiList = gwEuiCsvParser.parseFile();
		devList.addAll(csvEuiList);			
		if(devList.size() == 0){
			this.setProgress(randomStr, 100, true, "沒有待匯入的裝置資訊!");
			ret.setRetCode(ClaaAjaxResult.RET_CODE_OK);
			ret.setRetRemark("沒有待匯入的裝置資訊!");
			return ret;
		}
		this.addOsmDevs(randomStr, devList);
		ret.setRetCode(ClaaAjaxResult.RET_CODE_OK);
		// 將隨機數返回,用於後續批量匯入進度查詢。
		ret.setRetRemark(randomStr);
	}catch(Exception ex){
		ret.setRetCode(ClaaAjaxResult.RET_CODE_ERR);
		ret.setRetRemark(ex.getMessage());
		this.setProgress(randomStr, 100, false, ex.getMessage());
	}
	this.addOpLog(ret, MODULE_NAME, "批量匯入裝置", "匯入請求提交", "請求批次編號:"+randomStr);
	return ret;
}	


/**
 * 以非同步方式進行匯入裝置
 * 
 * @param excelFile
 * @param randomStr
 * @param extParaMap
 * @throws Exception
 */
private void addOsmDevs(String randomStr, List<OsmDev> devList) throws Exception {
	logger.info("Begin process Dev: totalNum="+devList.size());
	final User u = this.getLoginUser();
	ExecutorService execSvr = Executors.newSingleThreadExecutor();
	execSvr.submit(new Runnable(){
		@Override
		public void run() {
			try {
				StringBuffer errBuf = new StringBuffer();
				int totalNum = devList.size();
				totalNum = (totalNum == 0) ? 1 : totalNum;					
				double stepVal = 100.0 / totalNum;
				int cc = 0;
				for(OsmDev osmDev : devList){
					cc++; 
					if(osmDev == null){
						continue;
					}
					try {
						String deveui = osmDev.getDeveui();
						if (deveui == null || deveui.trim().equals("")) {
							continue;
						}
						OsmDev curOsmdev = devService.queryOsmDev(deveui);
						if (curOsmdev == null) {
							devService.addOsmDevImport(osmDev);
						} else {
							//裝置型別
							String csvdevTp = osmDev.getDevType();
							if (csvdevTp != null && !csvdevTp.trim().equals("")) {
								curOsmdev.setDevType(csvdevTp);
							}
							//發貨單
							String csvordno = osmDev.getOrdNo();
							if (csvordno != null && !csvordno.trim().equals("") && !"NA".equals(csvordno)) {
								curOsmdev.setOrdNo(csvordno);
							}
							//裝置狀態
							Integer csvdevStatus = osmDev.getDevStatus();
							if (csvdevStatus != null) {
								curOsmdev.setDevStatus(csvdevStatus);
							}
							//地址
							String csvaddress = osmDev.getAddress();
							if (csvaddress != null && !csvaddress.trim().equals("")) {
								curOsmdev.setAddress(csvaddress);
							}
							//歸屬專案
							String csvprojectid = osmDev.getProjectid();
							if (csvprojectid != null && !csvprojectid.trim().equals("")) {
								curOsmdev.setProjectid(csvprojectid);
							}
							Double csvlat = osmDev.getGpslat();
							if (csvlat != null) {
								curOsmdev.setGpslat(csvlat);
							}
							Double csvlng = osmDev.getGpslng();
							if (csvlng != null) {
								curOsmdev.setGpslng(csvlng);
							}
							Float csvalt = osmDev.getGpsalt();
							if (csvalt != null) {
								curOsmdev.setGpsalt(csvalt);
							}
							String csvremark = osmDev.getRemark();
							if (csvremark != null && !csvremark.trim().equals("")) {
								curOsmdev.setRemark(csvremark);
							}
							devService.modifyDevImport(curOsmdev);
						}
						setProgress(randomStr, (int) (cc * stepVal), true, "匯入裝置資訊成功");
						logger.info("addOsmDev OK: " + osmDev.getDeveui());
					} catch(Exception e){
						errBuf.append(osmDev.getDeveui()).append("匯入裝置資訊失敗:"+e.getMessage()).append("; ");
						logger.error("addOsmContracts failed: "+osmDev.getDeveui()+", err="+e.getMessage(), e);
						setProgress(randomStr, 100, false, e.getMessage());
					}
				}
			}catch(Exception ex){
				logger.error(ex.getMessage(), ex);
				setProgress(randomStr, 100, false, ex.getMessage());
			}catch(Throwable err){
				logger.error(err.getMessage(), err);
				setProgress(randomStr, 100, false, err.getMessage());
			}finally {
				// 停掉執行緒池.
				execSvr.shutdown();
				checkProgressMap(); 
			}
		}
	});		
}
/**
 * 讀取csv中的資料
 * 
 * @return List<String>
 * @author
 */
public List<OsmDev> parseFile() {
	List<OsmDev> ret = new ArrayList<OsmDev>();
	// 1.讀取有效資料行
	CsvReader reader = null;
	List<String[]> rawRowList = new ArrayList<String[]>();
	try {
		reader = new CsvReader(this.filePath, ',', Charset.forName("UTF-8"));
		// 跳過表頭 如果需要表頭的話,這句可以忽略
		reader.readHeaders();
		// 去掉空白行.
		reader.setSkipEmptyRecords(true);
		// trim
		reader.setTrimWhitespace(true);
		// 逐行讀入除表頭的資料
		while (reader.readRecord()) {
			// reader.getRawRecord() 讀取原始行字串.
			rawRowList.add(reader.getValues());
		}
		logger.info("Step.1>>Load file success: " + this.filePath + ", recordNum=" + rawRowList.size());
	} catch (Exception e) {
		logger.error("Step.1>>Load csv failed: " + this.filePath, e);
		return null;
	} finally {
		reader.close();
		reader = null;
	}

	// 2. 解析各行
	/**
	 * GWEUI
	 */
	for (String[] row : rawRowList) {
		// new contract 物件...
		OsmDev osmDev = new OsmDev();
		int j = 0;
		String cvStr = this.getCellValue(row, j++);
		if (cvStr == null) {
			cvStr = "";
		}
		// 1裝置編號
		osmDev.setDeveui(cvStr.trim());
		cvStr = this.getCellValue(row, j++);
		if (cvStr == null || cvStr.trim().equals("")) {
			// 2發貨單,如果發貨單沒填值,設個預設值NA
			osmDev.setOrdNo("NA");
		} else {
			osmDev.setOrdNo(cvStr);
		}
		cvStr = this.getCellValue(row, j++);
		if (cvStr == null) {
			cvStr = "";
		}
		// 3裝置型別
		osmDev.setDevType(cvStr.trim());
		cvStr = this.getCellValue(row, j++);
		if (cvStr != null && !cvStr.trim().equals("")) {
			try{
				// 4.裝置狀態
				osmDev.setDevStatus(Integer.parseInt(cvStr.trim()));
			} catch (Exception err) {
				logger.error("gpsln parse error: " + cvStr.trim());
		    }
		}
		cvStr = this.getCellValue(row, j++);
		if (cvStr == null) {
			cvStr = "";
		}
		// 5終端位置
		osmDev.setAddress(cvStr.trim());
		cvStr = this.getCellValue(row, j++);
		if (cvStr == null) {
			cvStr = "";
		}
		// 6歸屬專案
		osmDev.setProjectid(cvStr.trim());
		cvStr = this.getCellValue(row, j++);
		if (cvStr == null || cvStr.trim().equals("")) {
			// 7緯度
			osmDev.setGpslat(0D);
		} else {
			try {
				osmDev.setGpslat(Double.valueOf(cvStr.trim()));
			} catch (Exception err) {
				logger.error("gpsln parse error: " + cvStr.trim());
			}
		}
		cvStr = this.getCellValue(row, j++);
		if (cvStr == null || cvStr.trim().equals("")) {
			// 8經度
			osmDev.setGpslng(0D);
		} else {
			try {
				osmDev.setGpslng(Double.valueOf(cvStr.trim()));
			} catch (Exception err) {
				logger.error("gpsln parse error: " + cvStr.trim());
			}
		}
		cvStr = this.getCellValue(row, j++);
		if (cvStr == null || cvStr.trim().equals("")) {
			// 9海拔
			osmDev.setGpsalt(1F);
		} else {
			try {
				osmDev.setGpsalt(Float.valueOf(cvStr.trim()));
			} catch (Exception err) {
				logger.error("gpsln parse error: " + cvStr.trim());
			}
		}
		cvStr = this.getCellValue(row, j++);
		if (cvStr == null) {
			cvStr = "";
		}
		// 10備註
		osmDev.setRemark(cvStr.trim());

		ret.add(osmDev);
	}
	logger.info("Step.2>>Parse file success: " + this.filePath);
	return ret;
}

/**
 * 返回每一行各cell的值
 * 
 * @param row
 * @param cellId
 * @return
 */
private String getCellValue(String[] row, int cellId) {
	if (row == null || row.length <= cellId) {
		return "";
	}
	return row[cellId];
}

 

 

相關文章