DeviceGpsController.java 7.58 KB
package com.bsth.controller;

import com.bsth.data.gpsdata_v2.GpsRealData;
import com.bsth.data.gpsdata_v2.entity.GpsEntity;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("devicegps")
public class DeviceGpsController {

	@Autowired
	GpsRealData gpsRealData;

	@RequestMapping(value = "/real/line/{lineCode}")
	public List<GpsEntity> findByLineCode(@PathVariable("lineCode") String lineCode) {
		return gpsRealData.getByLine(lineCode);
	}

	@RequestMapping(value = "/real/all")
	public List<GpsEntity> findByLineCodes() {
		return new ArrayList<>(gpsRealData.all());
	}
	
	@RequestMapping(value = "/open", method = RequestMethod.POST)
	public Map<String, Object> open(@RequestParam(value = "_txt_", required = false) MultipartFile file, HttpServletRequest request) {
		Map<String, Object> res = new HashMap<>();
		File rf = new File(request.getServletContext().getRealPath("/temp"), System.currentTimeMillis() + "");
		File rd = rf.getParentFile();
		if (!rd.exists()) {
			rd.mkdirs();
		}
		
		BufferedReader reader = null;
		try {
			file.transferTo(rf);
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(rf), "GBK"));
			String line = null;
			List<Map<String, Object>> data = new ArrayList<>();
			while ((line = reader.readLine()) != null) {
				if (!StringUtils.isEmpty(line)) {
					String temp[] = line.split(",");
					if (temp.length != 4) {
						res.put("errCode", 1);
						res.put("msg", "txt文档格式错误,请检查");
						return res;
					}
					Map<String, Object> info = new HashMap<>();
					info.put("lineName", temp[0]);
					info.put("lineCode", temp[1]);
					info.put("inCode", temp[2]);
					info.put("deviceId", temp[3]);
					info.put("detail", gpsRealData.get(temp[3]));
					
					data.add(info);
				}
			}
			// 删除临时文件
			rf.delete();
			res.put("errCode", 0);
			res.put("data", data);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
				try {
					if (reader != null) reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
		return res;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/opened", method = RequestMethod.POST)
	public Map<String, Object> opened(@RequestParam(value = "json")String json) {
		json = StringEscapeUtils.unescapeHtml(json);
		Map<String, Object> res = new HashMap<>();
		List<Map<String, Object>> data = null;
		try {
			data = new ObjectMapper().readValue(json, List.class);
			for (Map<String, Object> info : data) {
				info.put("detail", gpsRealData.get((String)info.get("deviceId")));
			}
			
			res.put("errCode", 0);
			res.put("data", data);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return res;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/export", method = RequestMethod.POST)
	public void export(@RequestParam(value = "json")String json, HttpServletResponse response) {
		json = StringEscapeUtils.unescapeHtml(json);
		List<Map<String, Object>> data = null;
		OutputStream out = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			data = new ObjectMapper().readValue(json, List.class);
			for (Map<String, Object> info : data) {
				Map<String, Object> detail = (Map<String, Object>)info.get("detail");
				if (detail != null) {
					info.put("lineId", detail.get("lineId"));
					info.put("valid", (int)detail.get("valid") == 0 ? "$$$$$${txt-3829}" : "$$$$$${txt-4006}");
					info.put("timestamp", sdf.format(new Date((Long)detail.get("timestamp"))));
					info.put("version", detail.get("version"));
				} else {
					info.put("lineId", "");
					info.put("valid", "");
					info.put("timestamp", "");
					info.put("version", "");
				}
			}
			
			List<Header> head = new ArrayList<>();
			head.add(new Header("$$$$$${txt-3381}", "lineCode"));
			head.add(new Header("$$$$$${txt-3347}", "lineName"));
			head.add(new Header("$$$$$${txt-2576}", "inCode"));
			head.add(new Header("$$$$$${txt-3562}", "deviceId"));
			head.add(new Header("$$$$$${txt-3381}", "lineId"));
			head.add(new Header("GPS", "valid"));
			head.add(new Header("report", "timestamp"));
			head.add(new Header("版本", "version"));
			
			// 清空response  
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            out = new BufferedOutputStream(response.getOutputStream());
            excel(head, data, out);
            out.flush();
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (out != null) out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void excel(List<Header> head, List<Map<String, Object>> data, OutputStream out) throws IOException {
		// 声明一个工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = wb.createSheet("1");
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0;i < head.size();i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(head.get(i).getDescribe());
            cell.setCellValue(text);
        }
        
        int rownum = 1;
        for (Map<String, Object> map : data) {
        	HSSFRow r = sheet.createRow(rownum);
        	for (int i = 0;i < head.size();i++) {
                HSSFCell cell = r.createCell(i);
                HSSFRichTextString text = new HSSFRichTextString(String.valueOf(map.get(head.get(i).getField())));
                cell.setCellValue(text);
            }
        	rownum++;
        }
        
        wb.write(out);
        wb.close();
	}
	
	final class Header {
		private String describe;
		private String field;
		
		Header(){
			
		}
		
		Header(String describe, String field) {
			this.describe = describe;
			this.field = field;
		}

		public String getDescribe() {
			return describe;
		}

		public void setDescribe(String describe) {
			this.describe = describe;
		}

		public String getField() {
			return field;
		}

		public void setField(String field) {
			this.field = field;
		}
	}
}