Browse Source

功能优化

张茂营 4 years ago
parent
commit
3d984eb5c0

+ 42 - 2
src/main/java/com/minpay/common/util/ArithUtils.java

@@ -1,6 +1,8 @@
 package com.minpay.common.util;
 
 import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * 计算
@@ -57,10 +59,20 @@ public class ArithUtils {
      */
     public static float mul(String v1,String v2){
         BigDecimal b1 = new BigDecimal(v1);
-
         BigDecimal b2 = new BigDecimal(v2);
-
         return b1.multiply(b2).floatValue();
+    }
+    /**
+     * 乘法
+     * @param v1
+     * @param v2
+     * @return
+     */
+    public static float mul2(String v1,String v2){
+        BigDecimal b1 = new BigDecimal(v1);
+        BigDecimal b2 = new BigDecimal(v2);
+        BigDecimal c =  b1.multiply(b2);
+        return  c.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
 
     }
     /**
@@ -81,4 +93,32 @@ public class ArithUtils {
         }
         return b1.divide(b2, DEF_DIV_SCALE, BigDecimal.ROUND_HALF_UP).floatValue();
     }
+
+    /**
+     * 获取0.9~1.1之间的随机数
+     * @return
+     */
+    public static float getRandom(){
+        List<Float> list = new ArrayList<Float>();
+        for (int i = 0; i < 200; i++) {
+            list.add(ArithUtils.add("0.9",(0.001*i) + ""));
+        }
+        int a = (int) Math.floor(Math.random() * list.size());
+        float f = list.get(a);
+        return f;
+    }
+    /**
+     * 获取0.9~1.1之间的随机数
+     * @return
+     */
+    public static float getRandom2(){
+        List<Float> list = new ArrayList<Float>();
+        for (int i = 0; i < 20; i++) {
+            list.add(ArithUtils.add("5.76",(0.001*i) + ""));
+        }
+        int a = (int) Math.floor(Math.random() * list.size());
+        float f = list.get(a);
+        return f;
+    }
+
 }

+ 7 - 9
src/main/java/com/minpay/common/util/FilesUtil.java

@@ -32,11 +32,7 @@ import org.apache.commons.fileupload.FileItem;
 import org.apache.poi.hssf.usermodel.HSSFCell;
 import org.apache.poi.hssf.usermodel.HSSFDateUtil;
 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.usermodel.WorkbookFactory;
+import org.apache.poi.ss.usermodel.*;
 
 import com.minpay.common.constant.Constant;
 import com.minpay.common.exception.BusinessCodeException;
@@ -358,6 +354,7 @@ public class FilesUtil {
 			Map<String,String> map = new HashMap<String,String>();
 			// 是否存在全为空的一行数据
 			boolean allIsNull = true;
+			int index = 0;
 			for(int j=0; j<titleKey.length; j++){
 				Cell cell = row.getCell(j);
 				String cellValue="";
@@ -367,7 +364,7 @@ public class FilesUtil {
 							if(HSSFDateUtil.isCellDateFormatted(cell)){
 								//用于转化为日期格式
 								Date d = cell.getDateCellValue();
-								DateFormat formater = new SimpleDateFormat("yyyyMMddHHmmss");
+								DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 								cellValue = formater.format(d);
 							}else{
 								// 用于格式化数字,只保留数字的整数部分
@@ -380,9 +377,10 @@ public class FilesUtil {
 		                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean  
 		                    cellValue = cell.getBooleanCellValue() + "";  
 		                    break;  
-		                case HSSFCell.CELL_TYPE_FORMULA: // 公式  
-		                    cellValue = cell.getCellFormula() + "";  
-		                    break;  
+		                case HSSFCell.CELL_TYPE_FORMULA: // 公式
+							cell.setCellType(Cell.CELL_TYPE_STRING);
+		                    cellValue = cell.getStringCellValue();
+		                    break;
 		                case HSSFCell.CELL_TYPE_BLANK: // 空值  
 		                    cellValue = "";  
 		                    break;  

+ 2 - 0
src/main/java/com/minpay/db/table/own/mapper/IEFileManageMapper.java

@@ -11,4 +11,6 @@ public interface IEFileManageMapper extends IMINMybatisMapper {
     void insertEFileData(List<Map<String, String>> tempList);
 
     List<Map<String, String>> selectTzInf(Map<String, String> param, MINRowBounds rows);
+
+    List<Map<String, String>> selectTzinfo(Map<String, String> param);
 }

+ 308 - 34
src/main/java/com/minpay/reportManage/action/EFileReportAction.java

@@ -1,12 +1,14 @@
 package com.minpay.reportManage.action;
 
 import com.minpay.common.constant.Constant;
+import com.minpay.common.util.ArithUtils;
 import com.minpay.common.util.ExportExcelUtil;
 import com.minpay.common.util.StringUtil;
 import com.minpay.db.table.mapper.*;
 import com.minpay.db.table.model.*;
 import com.minpay.db.table.own.mapper.IEFileManageMapper;
 import com.minpay.db.table.own.mapper.IQxgdUnitManageMapper;
+import com.minpay.db.table.own.mapper.SequenceMapper;
 import com.startup.minpay.frame.business.IMINAction;
 import com.startup.minpay.frame.business.res.MINActionResult;
 import com.startup.minpay.frame.constant.IMINBusinessConstant;
@@ -25,6 +27,10 @@ import java.io.*;
 import java.net.URLEncoder;
 import java.text.SimpleDateFormat;
 import java.util.*;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
 
 @MINComponent
 public class EFileReportAction implements IMINAction {
@@ -76,58 +82,326 @@ public class EFileReportAction implements IMINAction {
 	public HttpServletResponse fileInfDownload(
 			@MINParam(key = "fileId") String fileId,
 			HttpServletResponse response
-	) throws MINBusinessException, IOException {
+	)  {
 		db = Service.lookup(IMINDataBaseService.class);
 		try {
-			//获取昨天的时间
-			Calendar cal=Calendar.getInstance();
-			cal.add(Calendar.DATE,-1);
-			Date d=cal.getTime();
-			SimpleDateFormat sp=new SimpleDateFormat("yyyy-MM-dd");
-			String yesterday=sp.format(d);
-//			//获取数据
-//			String sql="select * from JDBHAPP.FAULT_RECORD  where FAULTTIME='"+yesterday+"'";
-//			DataTable resultRecord = dbDao.select(sql);
-			///写入数据
-			// 相对路径,如果没有则要建立一个新的output.txt文件
-			File writeName = new File("../temp/mumengxiang.txt");
+
+			for (int ii = 0; ii < 33; ii++) {
+				//设置起始日期
+				Calendar monthStart = Calendar.getInstance();
+				monthStart.set(2021,3,24,0,0,0);
+				Calendar monthStart2 = Calendar.getInstance();
+				monthStart2.set(2021,3,24,0,0,0);
+
+				monthStart.add(Calendar.DATE, ii);
+				monthStart2.add(Calendar.DATE,(ii+1));
+
+				Integer year = monthStart.get(Calendar.YEAR);
+				Integer month = monthStart.get(Calendar.MONTH)+1; //第一个月从0开始,所以得到月份+1
+				Integer day = monthStart.get(monthStart.DAY_OF_MONTH);
+
+				Integer year2 = monthStart2.get(Calendar.YEAR);
+				Integer month2 = monthStart2.get(Calendar.MONTH)+1; //第一个月从0开始,所以得到月份+1
+				Integer day2 = monthStart2.get(monthStart2.DAY_OF_MONTH);
+				String dataDate = year + "-" + (month > 10 ? month:("0"+month)) + "-" + (day>= 10 ? day:("0" + day));//数据日期
+				String dataDate1 = year2 + "-" + (month2 > 10 ? month2:("0"+month2)) + "-" + (day2 >= 10 ? day2:("0" + day2));//数据日期+1
+				System.out.println(dataDate);
+				//数据点 共49条
+				String[] dates = {
+						"00:00:00", "00:30:00",
+						"01:00:00", "01:30:00",
+						"02:00:00", "02:30:00",
+						"03:00:00", "03:30:00",
+						"04:00:00", "04:30:00",
+						"05:00:00", "05:30:00",
+						"06:00:00", "06:30:00",
+						"07:00:00", "07:30:00",
+						"08:00:00", "08:30:00",
+						"09:00:00", "09:30:00",
+						"10:00:00", "10:30:00",
+						"11:00:00", "11:30:00",
+						"12:00:00", "12:30:00",
+						"13:00:00", "13:30:00",
+						"14:00:00", "14:30:00",
+						"15:00:00", "15:30:00",
+						"16:00:00", "16:30:00",
+						"17:00:00", "17:30:00",
+						"18:00:00", "18:30:00",
+						"19:00:00", "19:30:00",
+						"20:00:00", "20:30:00",
+						"21:00:00", "21:30:00",
+						"22:00:00", "22:30:00",
+						"23:00:00", "23:30:00",
+						"00:00:00"
+				};
+				String str1 = "",str2="";
+				str2+=dataDate1 + " " + dates[0] + ",";
+				System.out.println("数组长度:"+dates.length);
+				for (int i = 0; i < dates.length; i++) {
+					if(i == dates.length - 1 ){
+						if(i%2 == 0){
+							str1 += dataDate1 +" " + dates[i]+",";
+						}else{
+							str2 += dataDate1 +" " + dates[i]+",";
+						}
+					}else{
+						if(i%2 == 0){
+							str1 += dataDate +" "+ dates[i]+",";
+						}else{
+							str2 += dataDate +" "+ dates[i]+",";
+						}
+					}
+				}
+				str1+= dataDate + " " + dates[dates.length-1];
+				if(!"".equals(str1)){
+					str1  = str1.substring(0,str1.lastIndexOf(","));
+				}
+				if(!"".equals(str2)){
+					str2  = str2.substring(0,str2.lastIndexOf(","));
+				}
+				String[] datesD = str2.split(",");
+				String[] datesS = str1.split(",");
+				String[] keys = {"NUM", "TRAN_ID", "TRAN_NAME", "DATA_DATE",
+						"COLL_DATE", "UA", "UB", "UC", "IA", "IB", "IC", "AP","RP" };
+				String[] values = {"序号","开关标识","开关名称","数据日期","采集时间","A相电压","B相电压","C相电压","A相电流",
+						"B相电流", "C相电流", "有功", "无功"};
+				Map<String,String> param = new HashMap<>();
+				int index1 = 6, index2 = 6;
+				//整点数据
+				for (int i = 1; i <= 24; i++) {
+					param.put("start",datesS[i-1]);
+					param.put("end",datesS[i]);
+					param.put("start2",datesS[i-1]);
+					param.put("end2",datesS[i]);
+					if( i!= 1 && (i -1 ) %6 == 0){
+						index1 += 6;
+					}
+					this.CreateFile(param,keys,values,"2",index1,dataDate);
+				}
+				//半点数据-取整点
+				for (int i = 1; i <= 24; i++) {
+					param.put("start",datesD[i-1]);
+					param.put("end",datesD[i]);
+					param.put("start2",datesS[i-1]);
+					param.put("end2",datesS[i]);
+					if( i!= 1 && (i -1 ) %6 == 0){
+						index2 += 6;
+					}
+					this.CreateFile(param,keys,values,"1",index2,dataDate);
+				}
+
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return response;
+	}
+
+	private void CreateFile(Map<String, String> param, String[] keys, String[] values,String type,int index,String dataDate) throws IOException, MINBusinessException {
+		{
+			String date = param.get("end");
+			String date2 = date.substring(0,10)+"_"+date.substring(11,date.length());
+			String title = "1".equals(type) ? "半点数据":"整点数据";
+			System.out.println("数据日期:"+dataDate);
+			dataDate = dataDate.replaceAll("-","").replaceAll(" ","");
+
+			String fileDir =  "C:\\Users\\zmy87\\Desktop\\111\\"+dataDate+"\\"+title+"\\BREAKER_taian_"+ dataDate  +(index > 10 ?index:"0"+index);
+			File dir = new File(fileDir);
+			if(!dir.exists() && !dir.isDirectory()){
+				dir.mkdirs();
+			}
+			String filePath = fileDir+"\\BREAKER_taian_"+date
+					.replaceAll("-","").replaceAll(" ","").replaceAll(":","")
+					+".e";
+			File writeName = new File(filePath);
 			// 创建新文件,有同名的文件的话直接覆盖
 			writeName.createNewFile();
 			try (FileWriter writer = new FileWriter(writeName);
 				 BufferedWriter out = new BufferedWriter(writer)
 			) {
 				// \r\n即为换行
-				//文件头
-				String headTime= StringUtil.replace(yesterday,"-","");
-				out.write("<!  system=继电保护系统  version=1.0  type=notype  code=GBK  data=1.0  datetime='"+headTime+"_00:00:00' !>\n" +
-						"<继电保护系统::"+headTime+"录播记录信息>\r\n");
+				out.write("<!Entity=37409\ttype=断面数据\tdatetime='"+date2+"'\ttime='" + date2 + "'!>\r\n" +
+						"<TranData::37409>\r\n");
 				// 字段名称
 				out.write("@");
-//				for(int i=0;i<resultRecord.getColumns().size();i++){
-//					out.write(resultRecord.getColumnName(i)+" ");
-//				}
+				for(int i=0;i<keys.length;i++){
+					if(i != keys.length - 1){
+						out.write(keys[i] + "\t");
+					}else{
+						out.write(keys[i]);
+					}
+				}
 				//结束
-				out.write("\r\n ");
+				out.write("\r\n");
+				out.write("//");
+				for(int i=0;i<values.length;i++){
+					if(i != values.length - 1){
+						out.write(values[i] + "\t");
+					}else{
+						out.write(values[i]);
+					}
+				}
 				//字段简介
-				out.write("//主键值 时间戳 录播记录编号 故障时间毫秒值 主站名 变电站名 录播器名 一次设备名 故障识别 故障测距 录波器类型 对策故障记录ID 录波器测距结果 最低故障电压 最大故障电压 A相最大故障电流一次值 B相最大故障电流一次值 C相最大故障电流一次值 零序最大故障电流一次值 故障信息 数据文件是否存在 电压等级 故障记录对应文件名 上传时间\r\n ");
-//				//数据记录
-//				DataRowCollection rows = resultRecord.getRows();
-//				for (DataRow row: rows){
-//					out.write("#");
-//					for (int i = 0;i< 25 ; i++) {
-//						out.write(row.getValue(i)+" ");
-//					}
-//					out.write("\r\n ");
-//				}
+				out.write("\r\n");
+				param.put("start",param.get("start2"));
+				param.put("end",param.get("end2"));
+				List<Map<String,String>> list =  db.getMybatisMapper(IEFileManageMapper.class).selectTzinfo(param);
+				int index2 = 1;
+				//数据记录
+				for (Map<String,String> row: list){
+					String str = "\t";
+					StringBuffer temp = new StringBuffer();
+					for (int j = 0; j < keys.length; j++) {
+						String val = "";
+						if("NUM".equals(keys[j])){
+							val = "#"+index2;
+						}else if("IB".equals(keys[j]) || "IC".equals(keys[j])){
+							val = StringUtil.ObjectToString(ArithUtils.mul2(row.get("IA"),ArithUtils.getRandom()+""));
+						}else if("UA".equals(keys[j])  || "UB".equals(keys[j]) || "UC".equals(keys[j])){
+							val = StringUtil.ObjectToString(ArithUtils.getRandom2()+"");
+						}else if("DATA_DATE".equals(keys[j]) || "COLL_DATE".equals(keys[j])){
+							val = date2;
+						}else{
+							val = row.get(keys[j]);
+						}
+						if(j != keys.length - 1){
+							temp.append(StringUtil.ObjectToString(val))
+									.append(str);
+						}else{
+							temp.append(StringUtil.ObjectToString(val));
+						}
+					}
+					out.write(temp.toString());
+					out.write("\r\n");
+					index2 ++;
+				}
 				//结束
-				out.write("</继电保护系统::"+headTime+"录播记录信息>");
+				out.write("</TranData::37409>");
 				// 把缓存区内容压入文件
 				out.flush();
 				out.close();
 			}
+		}
+	}
+
+	public static void main(String[] args) throws IOException {
+		/** 测试压缩方法 */
+		List<File> fileList = new ArrayList<>();
+		readfile( "C:\\Users\\zmy87\\Desktop\\11华科\\导入模板", fileList);//读文件
+		FileOutputStream fos2 = new FileOutputStream(new File("C:\\Users\\zmy87\\Desktop\\11华科\\导入模板\\111.zip"));
+		toZip(fileList, fos2);//打包
+	}
+
+	/**
+	 * 读取某个文件夹下的所有文件(支持多级文件夹)
+	 */
+	public static boolean readfile(String filepath, List<File> fileList) throws FileNotFoundException, IOException {
+		try {
+
+			File file = new File(filepath);
+			if (!file.isDirectory()) {
+				System.out.println("文件");
+				System.out.println("path=" + file.getPath());
+				System.out.println("absolutepath=" + file.getAbsolutePath());
+				System.out.println("name=" + file.getName());
+				fileList.add(file);
+
+			} else if (file.isDirectory()) {
+				System.out.println("文件夹");
+				String[] filelist = file.list();
+				for (int i = 0; i < filelist.length; i++) {
+					File readfile = new File(filepath + "\\" + filelist[i]);
+					if (!readfile.isDirectory()) {
+						fileList.add(readfile);
+						System.out.println("path=" + readfile.getPath());
+						System.out.println("absolutepath=" + readfile.getAbsolutePath());
+						System.out.println("name=" + readfile.getName());
+
+					} else if (readfile.isDirectory()) {
+						readfile(filepath + "\\" + filelist[i], fileList);
+					}
+				}
+
+			}
+
+		} catch (FileNotFoundException e) {
+			System.out.println("readfile()   Exception:" + e.getMessage());
+		}
+		return true;
+	}
+	private static final int BUFFER_SIZE = 2 * 1024;
+
+	/**
+	 * 压缩成ZIP 方法 * @param srcDir 压缩文件夹路径
+	 *
+	 * @param out
+	 *            压缩文件输出流
+	 * @param KeepDirStructure
+	 *            是否保留原来的目录结构,true:保留目录结构;
+	 *            false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
+	 * @throws RuntimeException
+	 *             压缩失败会抛出运行时异常
+	 */
+	public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
+		long start = System.currentTimeMillis();
+		ZipOutputStream zos = null;
+		try {
+			zos = new ZipOutputStream(out);
+			File sourceFile = new File(srcDir);
+//			compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
+			long end = System.currentTimeMillis();
+			System.out.println("压缩完成,耗时:" + (end - start) + " ms");
 		} catch (Exception e) {
-			e.printStackTrace();
+			throw new RuntimeException("zip error from ZipUtils", e);
+		} finally {
+			if (zos != null) {
+				try {
+					zos.close();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+			}
+		}
+
+	}
+
+	/**
+	 * 压缩成ZIP 方法 * @param srcFiles 需要压缩的文件列表
+	 *
+	 * @param out
+	 *            压缩文件输出流
+	 * @throws RuntimeException
+	 *             压缩失败会抛出运行时异常
+	 */
+	public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
+		long start = System.currentTimeMillis();
+		ZipOutputStream zos = null;
+		try {
+			zos = new ZipOutputStream(out);
+			for (File srcFile : srcFiles) {
+				byte[] buf = new byte[BUFFER_SIZE];
+				zos.putNextEntry(new ZipEntry(srcFile.getName()));
+				int len;
+				FileInputStream in = new FileInputStream(srcFile);
+				while ((len = in.read(buf)) != -1) {
+					zos.write(buf, 0, len);
+				}
+				zos.closeEntry();
+				in.close();
+			}
+			long end = System.currentTimeMillis();
+			System.out.println("压缩完成,耗时:" + (end - start) + " ms");
+		} catch (Exception e) {
+			throw new RuntimeException("zip error from ZipUtils", e);
+		} finally {
+			if (zos != null) {
+				try {
+					zos.close();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+			}
 		}
-		return response;
 	}
+
 }

+ 1 - 1
src/main/resources/com/minpay/db/table/own/mapper/DataWareManageMapper.xml

@@ -44,7 +44,7 @@
 				</foreach>
 		   	</if>
 			AND A.DFI_STATE = '0'
-			AND DFI_TYPE IS NOT NULL
+			AND DFI_TYPE  in (select DBFT_ID from dw_branch_file_type)
 		   	ORDER BY DFI_UPLOAD_DATE DESC
 	</select>
 </mapper>

+ 27 - 0
src/main/resources/com/minpay/db/table/own/mapper/IEFileReportMapper.xml

@@ -60,5 +60,32 @@
 		EF_STATE        state
  			from
  			dw_file_detail_22
+
+	</select>
+
+	<select id="selectTzinfo" resultType="hashmap" parameterType="java.util.Map">
+		SELECT
+		EF_NUM          NUM        	,
+		EF_TRAN_ID      TRAN_ID     ,
+		EF_TRAN_NAME    TRAN_NAME   ,
+		EF_DATA_DATE    DATA_DATE   ,
+		EF_COLL_DATE    COLL_DATE   ,
+		EF_UA           UA          ,
+		EF_UB           UB          ,
+		EF_UC           UC          ,
+		EF_IA           IA          ,
+		EF_IB           IB          ,
+		EF_IC           IC          ,
+		EF_AP           AP          ,
+		EF_RP           RP
+		FROM
+		DW_FILE_DETAIL_22
+		WHERE 1=1
+<!--
+		<if test="start != null  AND start != '' AND end != null  AND end != ''">
+-->
+			AND EF_DATA_DATE BETWEEN #{start} AND #{end}
+		<!--</if>-->
+
 	</select>
 </mapper>