Commit ad6c7d439476c62028f45a721ac1b50d9cbe9285

Authored by 徐烜
2 parents 20d5d7ff 1171b75a

Update

Too many changes to show.

To preserve performance only 17 of 25 files are displayed.

src/main/java/com/bsth/controller/oil/YlbController.java
@@ -106,24 +106,24 @@ public class YlbController extends BaseController<Ylb, Integer>{ @@ -106,24 +106,24 @@ public class YlbController extends BaseController<Ylb, Integer>{
106 @RequestParam(defaultValue = "DESC") String direction){ 106 @RequestParam(defaultValue = "DESC") String direction){
107 107
108 Direction d; 108 Direction d;
109 - try { 109 +// try {
110 String rq=map.get("rq").toString(); 110 String rq=map.get("rq").toString();
111 if(!(rq=="")){ 111 if(!(rq=="")){
112 -  
113 - SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
114 - Calendar calendar = new GregorianCalendar();  
115 - calendar.setTime(sdf.parse(rq));  
116 - calendar.add(calendar.DATE,1);  
117 - Date date=calendar.getTime();  
118 - map.put("rq_ge", rq);  
119 - map.put("rq_le", sdf.format(date));  
120 - System.out.println(rq);  
121 - System.out.println(sdf.format(date));  
122 - }  
123 - } catch (ParseException e) {  
124 - // TODO Auto-generated catch block  
125 - e.printStackTrace(); 112 +//
  113 +// SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  114 +// Calendar calendar = new GregorianCalendar();
  115 +// calendar.setTime(sdf.parse(rq));
  116 +// calendar.add(calendar.DATE,1);
  117 +// Date date=calendar.getTime();
  118 + map.put("rq_eq", rq);
  119 +// map.put("rq_lt", sdf.format(date));
  120 +// System.out.println(rq);
  121 +// System.out.println(sdf.format(date));
126 } 122 }
  123 +// } catch (ParseException e) {
  124 +// // TODO Auto-generated catch block
  125 +// e.printStackTrace();
  126 +// }
127 if(null != direction && direction.equals("ASC")) 127 if(null != direction && direction.equals("ASC"))
128 d = Direction.ASC; 128 d = Direction.ASC;
129 else 129 else
src/main/java/com/bsth/controller/schedule/core/TTInfoDetailController.java
1 -package com.bsth.controller.schedule.core;  
2 -  
3 -import com.bsth.common.ResponseCode;  
4 -import com.bsth.controller.schedule.BController;  
5 -import com.bsth.entity.schedule.TTInfoDetail;  
6 -import com.bsth.service.schedule.TTInfoDetailService;  
7 -import org.springframework.beans.factory.annotation.Autowired;  
8 -import org.springframework.web.bind.annotation.PathVariable;  
9 -import org.springframework.web.bind.annotation.RequestMapping;  
10 -import org.springframework.web.bind.annotation.RequestMethod;  
11 -import org.springframework.web.bind.annotation.RestController;  
12 -  
13 -import java.util.HashMap;  
14 -import java.util.List;  
15 -import java.util.Map;  
16 -  
17 -/**  
18 - * Created by xu on 17/1/4.  
19 - */  
20 -@RestController  
21 -@RequestMapping("tidc")  
22 -public class TTInfoDetailController extends BController<TTInfoDetail, Long> {  
23 - @Autowired  
24 - private TTInfoDetailService ttInfoDetailService;  
25 -  
26 - @RequestMapping(value = "/bcdetail", method = RequestMethod.GET)  
27 - public List<TTInfoDetail> findBcdetails(Integer xlId, Long ttinfoId, Long lpId) {  
28 - return ttInfoDetailService.findBcdetails(xlId, ttinfoId, lpId);  
29 - }  
30 -  
31 - /**  
32 - * 验证sheet(以后放到规则引擎里去做)。  
33 - * @param filename excel文件全路径名  
34 - * @param sheetname sheet名字  
35 - * @param lineid 线路id  
36 - * @param linename 线路名称  
37 - * @return  
38 - */  
39 - @RequestMapping(value = "/validate/sheet", method = RequestMethod.POST)  
40 - public Map<String, Object> validate_sheet(String filename, String sheetname, Integer lineid, String linename) {  
41 - Map<String, Object> rtn = new HashMap<>();  
42 - try {  
43 - ttInfoDetailService.validateExcelSheet(filename, sheetname, lineid, linename);  
44 - rtn.put("status", ResponseCode.SUCCESS);  
45 - } catch (Exception exp) {  
46 - rtn.put("status", ResponseCode.ERROR);  
47 - rtn.put("msg", exp.getMessage());  
48 - }  
49 - return rtn;  
50 - }  
51 -  
52 - /**  
53 - * 验证关联的线路标准信息(以后放到规则引擎里去做)。  
54 - * @param lineinfoid  
55 - * @return  
56 - */  
57 - @RequestMapping(value = "/validate/lineinfo", method = RequestMethod.GET)  
58 - public Map<String, Object> validate_lineInfo(Integer lineinfoid) {  
59 - Map<String, Object> rtn = new HashMap<>();  
60 - try {  
61 - ttInfoDetailService.validateAssoLineInfo(lineinfoid);  
62 - rtn.put("status", ResponseCode.SUCCESS);  
63 - } catch (Exception exp) {  
64 - rtn.put("status", ResponseCode.ERROR);  
65 - rtn.put("msg", exp.getMessage());  
66 - }  
67 - return rtn;  
68 - }  
69 -  
70 - /**  
71 - * 获取时刻表明细编辑信息。  
72 - * @param xlid 线路id  
73 - * @param ttid 时刻表id  
74 - * @return  
75 - */  
76 - @RequestMapping(value = "/edit/{xlid}/{ttid}", method = RequestMethod.GET)  
77 - public Map<String, Object> getEditInfo(@PathVariable("xlid") Integer xlid,  
78 - @PathVariable("ttid") Long ttid) {  
79 - Map<String, Object> rtn = new HashMap<>();  
80 - try {  
81 - TTInfoDetailService.EditInfo editInfo = ttInfoDetailService.getEditInfo(xlid, ttid);  
82 - rtn.put("status", ResponseCode.SUCCESS);  
83 - rtn.put("data", editInfo);  
84 - } catch (Exception exp) {  
85 - rtn.put("status", ResponseCode.ERROR);  
86 - rtn.put("msg", exp.getMessage());  
87 - }  
88 - return rtn;  
89 - }  
90 -  
91 -} 1 +package com.bsth.controller.schedule.core;
  2 +
  3 +import com.bsth.common.ResponseCode;
  4 +import com.bsth.controller.schedule.BController;
  5 +import com.bsth.entity.schedule.TTInfoDetail;
  6 +import com.bsth.service.schedule.TTInfoDetailService;
  7 +import org.springframework.beans.factory.annotation.Autowired;
  8 +import org.springframework.web.bind.annotation.PathVariable;
  9 +import org.springframework.web.bind.annotation.RequestMapping;
  10 +import org.springframework.web.bind.annotation.RequestMethod;
  11 +import org.springframework.web.bind.annotation.RestController;
  12 +
  13 +import java.util.HashMap;
  14 +import java.util.List;
  15 +import java.util.Map;
  16 +
  17 +/**
  18 + * Created by xu on 17/1/4.
  19 + */
  20 +@RestController
  21 +@RequestMapping("tidc")
  22 +public class TTInfoDetailController extends BController<TTInfoDetail, Long> {
  23 + @Autowired
  24 + private TTInfoDetailService ttInfoDetailService;
  25 +
  26 + @RequestMapping(value = "/bcdetail", method = RequestMethod.GET)
  27 + public List<TTInfoDetail> findBcdetails(Integer xlId, Long ttinfoId, Long lpId) {
  28 + return ttInfoDetailService.findBcdetails(xlId, ttinfoId, lpId);
  29 + }
  30 +
  31 + /**
  32 + * 验证sheet(以后放到规则引擎里去做)。
  33 + * @param filename excel文件全路径名
  34 + * @param sheetname sheet名字
  35 + * @param lineid 线路id
  36 + * @param linename 线路名称
  37 + * @return
  38 + */
  39 + @RequestMapping(value = "/validate/sheet", method = RequestMethod.POST)
  40 + public Map<String, Object> validate_sheet(String filename, String sheetname, Integer lineid, String linename) {
  41 + Map<String, Object> rtn = new HashMap<>();
  42 + try {
  43 + ttInfoDetailService.validateExcelSheet(filename, sheetname, lineid, linename);
  44 + rtn.put("status", ResponseCode.SUCCESS);
  45 + } catch (Exception exp) {
  46 + rtn.put("status", ResponseCode.ERROR);
  47 + rtn.put("msg", exp.getMessage());
  48 + }
  49 + return rtn;
  50 + }
  51 +
  52 + /**
  53 + * 验证关联的线路标准信息(以后放到规则引擎里去做)。
  54 + * @param lineinfoid
  55 + * @return
  56 + */
  57 + @RequestMapping(value = "/validate/lineinfo", method = RequestMethod.GET)
  58 + public Map<String, Object> validate_lineInfo(Integer lineinfoid) {
  59 + Map<String, Object> rtn = new HashMap<>();
  60 + try {
  61 + ttInfoDetailService.validateAssoLineInfo(lineinfoid);
  62 + rtn.put("status", ResponseCode.SUCCESS);
  63 + } catch (Exception exp) {
  64 + rtn.put("status", ResponseCode.ERROR);
  65 + rtn.put("msg", exp.getMessage());
  66 + }
  67 + return rtn;
  68 + }
  69 +
  70 + /**
  71 + * 获取时刻表明细编辑信息。
  72 + * @param xlid 线路id
  73 + * @param ttid 时刻表id
  74 + * @return
  75 + */
  76 + @RequestMapping(value = "/edit/{xlid}/{ttid}", method = RequestMethod.GET)
  77 + public Map<String, Object> getEditInfo(@PathVariable("xlid") Integer xlid,
  78 + @PathVariable("ttid") Long ttid) {
  79 + Map<String, Object> rtn = new HashMap<>();
  80 + try {
  81 + TTInfoDetailService.EditInfo editInfo = ttInfoDetailService.getEditInfo(xlid, ttid);
  82 + rtn.put("status", ResponseCode.SUCCESS);
  83 + rtn.put("data", editInfo);
  84 + } catch (Exception exp) {
  85 + rtn.put("status", ResponseCode.ERROR);
  86 + rtn.put("msg", exp.getMessage());
  87 + }
  88 + return rtn;
  89 + }
  90 +
  91 +}
src/main/java/com/bsth/controller/sys/DutyEmployeeController.java
1 -package com.bsth.controller.sys;  
2 -  
3 -import com.bsth.controller.BaseController;  
4 -import com.bsth.entity.sys.DutyEmployee;  
5 -import com.bsth.service.sys.DutyEmployeeService;  
6 -import org.springframework.beans.factory.annotation.Autowired;  
7 -import org.springframework.web.bind.annotation.RequestMapping;  
8 -import org.springframework.web.bind.annotation.RequestParam;  
9 -import org.springframework.web.bind.annotation.RestController;  
10 -  
11 -import java.util.List;  
12 -  
13 -/**  
14 - * Created by panzhao on 2017/1/5.  
15 - */  
16 -@RestController  
17 -@RequestMapping("dutyEmployee")  
18 -public class DutyEmployeeController extends BaseController<DutyEmployee, Long> {  
19 -  
20 - @Autowired  
21 - DutyEmployeeService dutyEmployeeService;  
22 -  
23 - @RequestMapping(value = "queryByLineAndTime")  
24 - public List<DutyEmployee> getDutyEmployee(@RequestParam String lineCode, @RequestParam String startTime, @RequestParam String endTime) {  
25 - return dutyEmployeeService.getDutyEmployee(lineCode, startTime, endTime);  
26 - }  
27 -} 1 +package com.bsth.controller.sys;
  2 +
  3 +import com.bsth.controller.BaseController;
  4 +import com.bsth.entity.sys.DutyEmployee;
  5 +import com.bsth.service.sys.DutyEmployeeService;
  6 +import org.springframework.beans.factory.annotation.Autowired;
  7 +import org.springframework.web.bind.annotation.RequestMapping;
  8 +import org.springframework.web.bind.annotation.RequestParam;
  9 +import org.springframework.web.bind.annotation.RestController;
  10 +
  11 +import java.util.List;
  12 +
  13 +/**
  14 + * Created by panzhao on 2017/1/5.
  15 + */
  16 +@RestController
  17 +@RequestMapping("dutyEmployee")
  18 +public class DutyEmployeeController extends BaseController<DutyEmployee, Long> {
  19 +
  20 + @Autowired
  21 + DutyEmployeeService dutyEmployeeService;
  22 +
  23 + @RequestMapping(value = "queryByLineAndTime")
  24 + public List<DutyEmployee> getDutyEmployee(@RequestParam String lineCode, @RequestParam String startTime, @RequestParam String endTime) {
  25 + return dutyEmployeeService.getDutyEmployee(lineCode, startTime, endTime);
  26 + }
  27 +}
src/main/java/com/bsth/data/BasicData.java
@@ -261,26 +261,26 @@ public class BasicData implements CommandLineRunner { @@ -261,26 +261,26 @@ public class BasicData implements CommandLineRunner {
261 /** 261 /**
262 * 加载运管处的站点及序号 262 * 加载运管处的站点及序号
263 * 上行从1开始,下行顺序续编 263 * 上行从1开始,下行顺序续编
264 -  
265 - List<Object[]> ygcLines = stationRouteRepository.findAllLineWithYgc();  
266 - if(ygcLines != null && ygcLines.size() > 0){  
267 - int size = ygcLines.size();  
268 - Object[] tempArray ;  
269 - int num = 1;  
270 - String key;  
271 - String lineCode = "";  
272 - for (int i = 0; i < size; i ++){  
273 - tempArray = ygcLines.get(i);  
274 - if(lineCode.equals("")){  
275 - lineCode = tempArray[0]+"";  
276 - }else if(!lineCode.equals(tempArray[0]+"")){  
277 - num = 1;  
278 - lineCode = tempArray[0]+"";  
279 - }  
280 - key = tempArray[0] + "_"+tempArray[1] + "_"+tempArray[2];  
281 - tempStationName2YgcNumber.put(key,num++);  
282 - }  
283 - }*/ 264 + */
  265 + List<Object[]> ygcLines = stationRouteRepository.findAllLineWithYgc();
  266 + if(ygcLines != null && ygcLines.size() > 0){
  267 + int size = ygcLines.size();
  268 + Object[] tempArray ;
  269 + int num = 1;
  270 + String key;
  271 + String lineCode = "";
  272 + for (int i = 0; i < size; i ++){
  273 + tempArray = ygcLines.get(i);
  274 + if(lineCode.equals("")){
  275 + lineCode = tempArray[0]+"";
  276 + }else if(!lineCode.equals(tempArray[0]+"")){
  277 + num = 1;
  278 + lineCode = tempArray[0]+"";
  279 + }
  280 + key = tempArray[0] + "_"+tempArray[1] + "_"+tempArray[2];
  281 + tempStationName2YgcNumber.put(key,num++);
  282 + }
  283 + }
284 } 284 }
285 285
286 lineId2CodeMap = biMap; 286 lineId2CodeMap = biMap;
src/main/java/com/bsth/data/gpsdata/arrival/handlers/InOutStationSignalHandle.java
1 -package com.bsth.data.gpsdata.arrival.handlers;  
2 -  
3 -import com.bsth.data.LineConfigData;  
4 -import com.bsth.data.gpsdata.GpsEntity;  
5 -import com.bsth.data.gpsdata.arrival.SignalHandle;  
6 -import com.bsth.data.gpsdata.arrival.utils.CircleQueue;  
7 -import com.bsth.data.gpsdata.arrival.utils.ScheduleSignalState;  
8 -import com.bsth.data.gpsdata.arrival.utils.SignalSchPlanMatcher;  
9 -import com.bsth.data.schedule.DayOfSchedule;  
10 -import com.bsth.entity.realcontrol.LineConfig;  
11 -import com.bsth.entity.realcontrol.ScheduleRealInfo;  
12 -import com.bsth.service.directive.DirectiveService;  
13 -import com.bsth.websocket.handler.SendUtils;  
14 -import org.apache.commons.lang3.StringUtils;  
15 -import org.slf4j.Logger;  
16 -import org.slf4j.LoggerFactory;  
17 -import org.springframework.beans.factory.annotation.Autowired;  
18 -import org.springframework.stereotype.Component;  
19 -  
20 -/**  
21 - * 进出站动作处理  
22 - * Created by panzhao on 2016/12/27.  
23 - */  
24 -@Component  
25 -public class InOutStationSignalHandle extends SignalHandle{  
26 -  
27 - Logger logger = LoggerFactory.getLogger(this.getClass());  
28 -  
29 - @Autowired  
30 - DayOfSchedule dayOfSchedule;  
31 -  
32 - @Autowired  
33 - LineConfigData lineConfigData;  
34 -  
35 - @Autowired  
36 - SendUtils sendUtils;  
37 -  
38 - @Autowired  
39 - DirectiveService directiveService;  
40 -  
41 - @Autowired  
42 - ScheduleSignalState scheduleSignalState;  
43 -  
44 - @Autowired  
45 - SignalSchPlanMatcher signalSchPlanMatcher;  
46 -  
47 - private final static int MAX_BEFORE_TIME = 1000 * 60 * 72;  
48 -  
49 - @Override  
50 - public boolean handle(GpsEntity gps, CircleQueue<GpsEntity> prevs) {  
51 - //忽略漂移信号  
52 - if(isDriftSignal(gps))  
53 - return false;  
54 -  
55 - //从异常状态恢复的第一个信号  
56 - if(abnormalRecovery(gps, prevs)){  
57 - //回溯一下之前的轨迹  
58 - scheduleSignalState.signalRetrospect(gps);  
59 - }  
60 -  
61 - if(isNotEmpty(prevs)){  
62 - GpsEntity prev = prevs.getTail();  
63 - if(isOutStation(gps, prev))  
64 - outStation(gps, prev);  
65 -  
66 -  
67 - if(isInStation(gps, prev))  
68 - inStation(gps, prev);  
69 - }  
70 -  
71 - return true;  
72 - }  
73 -  
74 - private boolean isOutStation(GpsEntity gps, GpsEntity prev){  
75 - //从站内到站外  
76 - if(prev.getInstation() > 0 && gps.getInstation() == 0)  
77 - return true;  
78 -  
79 - //从站内到另一个站内  
80 - if(prev.getInstation() > 0 && gps.getInstation() > 0  
81 - && !prev.getStopNo().equals(gps.getStopNo()))  
82 - return true;  
83 - return false;  
84 - }  
85 -  
86 - private boolean isInStation(GpsEntity gps, GpsEntity prev){  
87 - //从站外到站内  
88 - if(prev.getInstation() == 0 && gps.getInstation() > 0  
89 - /*&& !prev.getStopNo().equals(gps.getStopNo())*/){  
90 - return true;  
91 - }  
92 -  
93 - //从站内到另一个站内  
94 - if(prev.getInstation() > 0 && gps.getInstation() > 0  
95 - && !prev.getStopNo().equals(gps.getStopNo()))  
96 - return true;  
97 - return false;  
98 - }  
99 -  
100 - /**  
101 - * 出站  
102 - * @param gps 当前点  
103 - * @param prev 上一个点  
104 - */  
105 - private void outStation(GpsEntity gps, GpsEntity prev) {  
106 - ScheduleRealInfo sch = dayOfSchedule.executeCurr(gps.getNbbm());  
107 - String qdzCode = sch.getQdzCode();  
108 -  
109 - //首班出场最多提前1.2小时  
110 - if(dayOfSchedule.isFirstOut(sch) && sch.getDfsjT() - gps.getTimestamp() > MAX_BEFORE_TIME)  
111 - return;  
112 -  
113 - //起点发车  
114 - if(qdzCode != null && prev.getStopNo().equals(qdzCode)  
115 - && !willDepart(gps, prev, sch)){  
116 -  
117 - //发车班次匹配  
118 - signalSchPlanMatcher.outMatch(gps, sch);  
119 - sch = dayOfSchedule.executeCurr(gps.getNbbm());  
120 -  
121 - //实发时间不覆盖  
122 - if(StringUtils.isNotEmpty(sch.getFcsjActual()))  
123 - return;  
124 -  
125 - //实发时间  
126 - sch.setFcsjActualAll(gps.getTimestamp());  
127 - //通知客户端  
128 - sendUtils.sendFcsj(sch);  
129 - //持久化  
130 - dayOfSchedule.save(sch);  
131 -  
132 - //出站既出场  
133 - outStationAndOutPark(sch);  
134 - logger.info("班次:" + sch.getDfsj() + "发车, 时间:" + sch.getFcsjActual());  
135 - }  
136 - else if(sch.getBcType().equals("out")){  
137 - ScheduleRealInfo next = dayOfSchedule.nextSame(sch);  
138 - if(prev.getStopNo().equals(next.getQdzCode())){  
139 - //发下一个班次  
140 - dayOfSchedule.addExecPlan(next);  
141 - outStation(gps, prev);  
142 - }  
143 - }  
144 - }  
145 -  
146 -  
147 - private void outStationAndOutPark(ScheduleRealInfo sch){  
148 - LineConfig config = lineConfigData.get(sch.getXlBm());  
149 - if (config != null && config.getOutConfig() == 2) {  
150 - //出站既出场  
151 - ScheduleRealInfo schPrev = dayOfSchedule.prev(sch);  
152 - if (schPrev != null && schPrev.getBcType().equals("out")) {  
153 - schPrev.setFcsjActualAll(sch.getFcsjActualTime());  
154 - schPrev.setZdsjActualAll(sch.getFcsjActualTime());  
155 -  
156 - sendUtils.refreshSch(schPrev);  
157 - dayOfSchedule.save(schPrev);  
158 - }  
159 - }  
160 - }  
161 -  
162 - /**  
163 - * 进站  
164 - * @param gps 当前点  
165 - * @param prev 上一个点  
166 - */  
167 - private void inStation(GpsEntity gps, GpsEntity prev){  
168 - ScheduleRealInfo sch = dayOfSchedule.executeCurr(gps.getNbbm());  
169 -  
170 - if(gps.getStopNo().equals(sch.getZdzCode())){  
171 -  
172 - //实达时间不覆盖  
173 - if(StringUtils.isNotEmpty(sch.getZdsjActual()))  
174 - return;  
175 -  
176 - sch.setZdsjActualAll(gps.getTimestamp());  
177 - //已完成班次数  
178 - int doneSum = dayOfSchedule.doneSum(sch.getClZbh());  
179 - ScheduleRealInfo next = dayOfSchedule.next(sch);  
180 - //通知客户端  
181 - sendUtils.sendZdsj(sch, next, doneSum);  
182 - //持久化  
183 - dayOfSchedule.save(sch);  
184 - //下发调度指令  
185 - directiveService.send60Dispatch(next, doneSum, "到站@系统");  
186 -  
187 - //准备执行下一个班次  
188 - if (next != null) {  
189 - next.setQdzArrDatesj(sch.getZdsjActual());  
190 - dayOfSchedule.addExecPlan(next);  
191 - //进站既进场  
192 - inStationAndInPark(sch, next);  
193 - //将gps转换为下一个班次走向的站内信号  
194 - transformUpdown(gps, sch);  
195 - }  
196 - }  
197 - else if(sch.getFcsjActual() == null){  
198 - //有进站,但班次没有实发,向前追溯一下信号  
199 - scheduleSignalState.signalRetrospect(gps, sch);  
200 - }  
201 - }  
202 -  
203 - /**  
204 - * 进站既进场  
205 - * @param sch  
206 - */  
207 - private void inStationAndInPark(ScheduleRealInfo sch, ScheduleRealInfo next){  
208 - LineConfig config = lineConfigData.get(sch.getXlBm());  
209 - if (next.getBcType().equals("in") &&  
210 - config != null && config.getOutConfig() == 2) {  
211 - next.setFcsjActualAll(sch.getZdsjActualTime());  
212 - next.setZdsjActualAll(sch.getZdsjActualTime());  
213 -  
214 - sendUtils.refreshSch(next);  
215 - dayOfSchedule.save(next);  
216 - }  
217 - }  
218 -  
219 - /**  
220 - * 发车漂移判定(这里出现的误判,由车辆到达中途站的时候补偿)  
221 - * @param gps  
222 - * @param prev  
223 - * @param task  
224 - * @return  
225 - */  
226 - private boolean willDepart(GpsEntity gps, GpsEntity prev, Object task){  
227 -  
228 - /*ScheduleRealInfo sch = (ScheduleRealInfo) task;  
229 - ScheduleRealInfo prevTask = dayOfSchedule.prev(sch);  
230 - if(prevTask == null || prevTask.getBcType().equals("out"))  
231 - return false;  
232 -  
233 - //计划停站时间  
234 - int stopTimePlan = (int) (sch.getDfsjT() - prevTask.getZdsjT());  
235 -  
236 - if(stopTimePlan < 1000 * 60 * 10)  
237 - return false;  
238 -  
239 - //实际停站时间  
240 - if(prevTask.getZdsjActual() != null){  
241 - int actualTime = (int) (gps.getTimestamp() - prevTask.getZdsjActualTime());  
242 -  
243 - if(actualTime < stopTimePlan * 0.8){  
244 - logger.info("漂移判定");  
245 -  
246 - return true;  
247 - }  
248 - }*/  
249 - return false;  
250 - } 1 +package com.bsth.data.gpsdata.arrival.handlers;
  2 +
  3 +import com.bsth.data.LineConfigData;
  4 +import com.bsth.data.gpsdata.GpsEntity;
  5 +import com.bsth.data.gpsdata.arrival.SignalHandle;
  6 +import com.bsth.data.gpsdata.arrival.utils.CircleQueue;
  7 +import com.bsth.data.gpsdata.arrival.utils.ScheduleSignalState;
  8 +import com.bsth.data.gpsdata.arrival.utils.SignalSchPlanMatcher;
  9 +import com.bsth.data.schedule.DayOfSchedule;
  10 +import com.bsth.entity.realcontrol.LineConfig;
  11 +import com.bsth.entity.realcontrol.ScheduleRealInfo;
  12 +import com.bsth.service.directive.DirectiveService;
  13 +import com.bsth.websocket.handler.SendUtils;
  14 +import org.apache.commons.lang3.StringUtils;
  15 +import org.slf4j.Logger;
  16 +import org.slf4j.LoggerFactory;
  17 +import org.springframework.beans.factory.annotation.Autowired;
  18 +import org.springframework.stereotype.Component;
  19 +
  20 +/**
  21 + * 进出站动作处理
  22 + * Created by panzhao on 2016/12/27.
  23 + */
  24 +@Component
  25 +public class InOutStationSignalHandle extends SignalHandle{
  26 +
  27 + Logger logger = LoggerFactory.getLogger(this.getClass());
  28 +
  29 + @Autowired
  30 + DayOfSchedule dayOfSchedule;
  31 +
  32 + @Autowired
  33 + LineConfigData lineConfigData;
  34 +
  35 + @Autowired
  36 + SendUtils sendUtils;
  37 +
  38 + @Autowired
  39 + DirectiveService directiveService;
  40 +
  41 + @Autowired
  42 + ScheduleSignalState scheduleSignalState;
  43 +
  44 + @Autowired
  45 + SignalSchPlanMatcher signalSchPlanMatcher;
  46 +
  47 + private final static int MAX_BEFORE_TIME = 1000 * 60 * 72;
  48 +
  49 + @Override
  50 + public boolean handle(GpsEntity gps, CircleQueue<GpsEntity> prevs) {
  51 + //忽略漂移信号
  52 + if(isDriftSignal(gps))
  53 + return false;
  54 +
  55 + //从异常状态恢复的第一个信号
  56 + if(abnormalRecovery(gps, prevs)){
  57 + //回溯一下之前的轨迹
  58 + scheduleSignalState.signalRetrospect(gps);
  59 + }
  60 +
  61 + if(isNotEmpty(prevs)){
  62 + GpsEntity prev = prevs.getTail();
  63 + if(isOutStation(gps, prev))
  64 + outStation(gps, prev);
  65 +
  66 +
  67 + if(isInStation(gps, prev))
  68 + inStation(gps, prev);
  69 + }
  70 +
  71 + return true;
  72 + }
  73 +
  74 + private boolean isOutStation(GpsEntity gps, GpsEntity prev){
  75 + //从站内到站外
  76 + if(prev.getInstation() > 0 && gps.getInstation() == 0)
  77 + return true;
  78 +
  79 + //从站内到另一个站内
  80 + if(prev.getInstation() > 0 && gps.getInstation() > 0
  81 + && !prev.getStopNo().equals(gps.getStopNo()))
  82 + return true;
  83 + return false;
  84 + }
  85 +
  86 + private boolean isInStation(GpsEntity gps, GpsEntity prev){
  87 + //从站外到站内
  88 + if(prev.getInstation() == 0 && gps.getInstation() > 0
  89 + /*&& !prev.getStopNo().equals(gps.getStopNo())*/){
  90 + return true;
  91 + }
  92 +
  93 + //从站内到另一个站内
  94 + if(prev.getInstation() > 0 && gps.getInstation() > 0
  95 + && !prev.getStopNo().equals(gps.getStopNo()))
  96 + return true;
  97 + return false;
  98 + }
  99 +
  100 + /**
  101 + * 出站
  102 + * @param gps 当前点
  103 + * @param prev 上一个点
  104 + */
  105 + private void outStation(GpsEntity gps, GpsEntity prev) {
  106 + ScheduleRealInfo sch = dayOfSchedule.executeCurr(gps.getNbbm());
  107 + String qdzCode = sch.getQdzCode();
  108 +
  109 + //首班出场最多提前1.2小时
  110 + if(dayOfSchedule.isFirstOut(sch) && sch.getDfsjT() - gps.getTimestamp() > MAX_BEFORE_TIME)
  111 + return;
  112 +
  113 + //起点发车
  114 + if(qdzCode != null && prev.getStopNo().equals(qdzCode)
  115 + && !willDepart(gps, prev, sch)){
  116 +
  117 + //发车班次匹配
  118 + signalSchPlanMatcher.outMatch(gps, sch);
  119 + sch = dayOfSchedule.executeCurr(gps.getNbbm());
  120 +
  121 + //实发时间不覆盖
  122 + if(StringUtils.isNotEmpty(sch.getFcsjActual()))
  123 + return;
  124 +
  125 + //实发时间
  126 + sch.setFcsjActualAll(gps.getTimestamp());
  127 + //通知客户端
  128 + sendUtils.sendFcsj(sch);
  129 + //持久化
  130 + dayOfSchedule.save(sch);
  131 +
  132 + //出站既出场
  133 + outStationAndOutPark(sch);
  134 + logger.info("班次:" + sch.getDfsj() + "发车, 时间:" + sch.getFcsjActual());
  135 + }
  136 + else if(sch.getBcType().equals("out")){
  137 + ScheduleRealInfo next = dayOfSchedule.nextSame(sch);
  138 + if(prev.getStopNo().equals(next.getQdzCode())){
  139 + //发下一个班次
  140 + dayOfSchedule.addExecPlan(next);
  141 + outStation(gps, prev);
  142 + }
  143 + }
  144 + }
  145 +
  146 +
  147 + private void outStationAndOutPark(ScheduleRealInfo sch){
  148 + LineConfig config = lineConfigData.get(sch.getXlBm());
  149 + if (config != null && config.getOutConfig() == 2) {
  150 + //出站既出场
  151 + ScheduleRealInfo schPrev = dayOfSchedule.prev(sch);
  152 + if (schPrev != null && schPrev.getBcType().equals("out")) {
  153 + schPrev.setFcsjActualAll(sch.getFcsjActualTime());
  154 + schPrev.setZdsjActualAll(sch.getFcsjActualTime());
  155 +
  156 + sendUtils.refreshSch(schPrev);
  157 + dayOfSchedule.save(schPrev);
  158 + }
  159 + }
  160 + }
  161 +
  162 + /**
  163 + * 进站
  164 + * @param gps 当前点
  165 + * @param prev 上一个点
  166 + */
  167 + private void inStation(GpsEntity gps, GpsEntity prev){
  168 + ScheduleRealInfo sch = dayOfSchedule.executeCurr(gps.getNbbm());
  169 +
  170 + if(gps.getStopNo().equals(sch.getZdzCode())){
  171 +
  172 + //实达时间不覆盖
  173 + if(StringUtils.isNotEmpty(sch.getZdsjActual()))
  174 + return;
  175 +
  176 + sch.setZdsjActualAll(gps.getTimestamp());
  177 + //已完成班次数
  178 + int doneSum = dayOfSchedule.doneSum(sch.getClZbh());
  179 + ScheduleRealInfo next = dayOfSchedule.next(sch);
  180 + //通知客户端
  181 + sendUtils.sendZdsj(sch, next, doneSum);
  182 + //持久化
  183 + dayOfSchedule.save(sch);
  184 + //下发调度指令
  185 + directiveService.send60Dispatch(next, doneSum, "到站@系统");
  186 +
  187 + //准备执行下一个班次
  188 + if (next != null) {
  189 + next.setQdzArrDatesj(sch.getZdsjActual());
  190 + dayOfSchedule.addExecPlan(next);
  191 + //进站既进场
  192 + inStationAndInPark(sch, next);
  193 + //将gps转换为下一个班次走向的站内信号
  194 + transformUpdown(gps, sch);
  195 + }
  196 + }
  197 + else if(sch.getFcsjActual() == null){
  198 + //有进站,但班次没有实发,向前追溯一下信号
  199 + scheduleSignalState.signalRetrospect(gps, sch);
  200 + }
  201 + }
  202 +
  203 + /**
  204 + * 进站既进场
  205 + * @param sch
  206 + */
  207 + private void inStationAndInPark(ScheduleRealInfo sch, ScheduleRealInfo next){
  208 + LineConfig config = lineConfigData.get(sch.getXlBm());
  209 + if (next.getBcType().equals("in") &&
  210 + config != null && config.getOutConfig() == 2) {
  211 + next.setFcsjActualAll(sch.getZdsjActualTime());
  212 + next.setZdsjActualAll(sch.getZdsjActualTime());
  213 +
  214 + sendUtils.refreshSch(next);
  215 + dayOfSchedule.save(next);
  216 + }
  217 + }
  218 +
  219 + /**
  220 + * 发车漂移判定(这里出现的误判,由车辆到达中途站的时候补偿)
  221 + * @param gps
  222 + * @param prev
  223 + * @param task
  224 + * @return
  225 + */
  226 + private boolean willDepart(GpsEntity gps, GpsEntity prev, Object task){
  227 +
  228 + /*ScheduleRealInfo sch = (ScheduleRealInfo) task;
  229 + ScheduleRealInfo prevTask = dayOfSchedule.prev(sch);
  230 + if(prevTask == null || prevTask.getBcType().equals("out"))
  231 + return false;
  232 +
  233 + //计划停站时间
  234 + int stopTimePlan = (int) (sch.getDfsjT() - prevTask.getZdsjT());
  235 +
  236 + if(stopTimePlan < 1000 * 60 * 10)
  237 + return false;
  238 +
  239 + //实际停站时间
  240 + if(prevTask.getZdsjActual() != null){
  241 + int actualTime = (int) (gps.getTimestamp() - prevTask.getZdsjActualTime());
  242 +
  243 + if(actualTime < stopTimePlan * 0.8){
  244 + logger.info("漂移判定");
  245 +
  246 + return true;
  247 + }
  248 + }*/
  249 + return false;
  250 + }
251 } 251 }
252 \ No newline at end of file 252 \ No newline at end of file
src/main/java/com/bsth/data/gpsdata/arrival/utils/ScheduleSignalState.java
1 -package com.bsth.data.gpsdata.arrival.utils;  
2 -  
3 -import com.bsth.data.LineConfigData;  
4 -import com.bsth.data.gpsdata.GpsEntity;  
5 -import com.bsth.data.gpsdata.SignalStateData;  
6 -import com.bsth.data.gpsdata.arrival.GeoCacheData;  
7 -import com.bsth.data.gpsdata.arrival.entity.RouteReverse;  
8 -import com.bsth.data.gpsdata.arrival.entity.SignalAbnormal;  
9 -import com.bsth.data.gpsdata.arrival.entity.SignalState;  
10 -import com.bsth.data.schedule.DayOfSchedule;  
11 -import com.bsth.entity.realcontrol.LineConfig;  
12 -import com.bsth.entity.realcontrol.ScheduleRealInfo;  
13 -import org.slf4j.Logger;  
14 -import org.slf4j.LoggerFactory;  
15 -import org.springframework.beans.factory.annotation.Autowired;  
16 -import org.springframework.stereotype.Component;  
17 -  
18 -/**  
19 - * 班次信号状态分析  
20 - * Created by panzhao on 2016/12/29.  
21 - */  
22 -@Component  
23 -public class ScheduleSignalState {  
24 -  
25 - @Autowired  
26 - DayOfSchedule dayOfSchedule;  
27 -  
28 - Logger logger = LoggerFactory.getLogger(this.getClass());  
29 -  
30 - @Autowired  
31 - LineConfigData lineConfigData;  
32 -  
33 - @Autowired  
34 - SignalStateData signalStateData;  
35 -  
36 - /**  
37 - * 路由反向分析  
38 - */  
39 - public void reverseAnalyse(RouteReverse reverse) {  
40 - ScheduleRealInfo sch = dayOfSchedule.executeCurr(reverse.getNbbm());  
41 -  
42 - String bcType = sch.getBcType();  
43 -  
44 - switch (bcType) {  
45 - case "out":  
46 - outReverseAnalyse(sch, reverse);  
47 - break;  
48 - case "normal":  
49 - normalReverseAnalyse(sch, reverse);  
50 - break;  
51 - }  
52 - }  
53 -  
54 - /**  
55 - * 出场班次路由反向分析  
56 - *  
57 - * @param sch  
58 - */  
59 - private void outReverseAnalyse(ScheduleRealInfo sch, RouteReverse reverse) {  
60 - long t = reverse.getCt();  
61 - //出场班次终点时间前,允许反向轨迹  
62 - if (sch.getZdsjT() != null && sch.getZdsjT() > t) {  
63 - return;  
64 - }  
65 -  
66 - int rt;  
67 - //从实发 到 当前时间 < 计划运送时间 * 0.9  
68 - if (sch.getFcsjActual() != null && sch.getBcsj() != null) {  
69 - rt = (int) (t - sch.getFcsjActualTime());  
70 - if (rt < sch.getBcsj() * 0.9)  
71 - return;  
72 - }  
73 -  
74 - ScheduleRealInfo next = dayOfSchedule.next(sch);  
75 - if (next.getXlDir().equals(sch.getXlDir()))  
76 - return;  
77 -  
78 - //时间足够下一个班次待发时间运行到当前站  
79 - int runTime = reverse.getCount() * 1500 * 60;  
80 - if (next.getDfsjT() + runTime < t) {  
81 - //跳到下一个班次  
82 - dayOfSchedule.addExecPlan(next);  
83 - }  
84 - }  
85 -  
86 - /**  
87 - * 正常班次路由反向分析  
88 - *  
89 - * @param sch  
90 - * @param reverse  
91 - */  
92 - private void normalReverseAnalyse(ScheduleRealInfo sch, RouteReverse reverse) {  
93 - LineConfig conf = lineConfigData.get(sch.getXlBm());  
94 -  
95 - if (conf.isReadReverse()) {  
96 - //跳下一个班次  
97 - ScheduleRealInfo next = dayOfSchedule.next(sch);  
98 - if (next != null)  
99 - dayOfSchedule.addExecPlan(next);  
100 -  
101 - //记录信号状态  
102 - SignalState signalState = SignalState.reverseSignalSTate(sch, reverse);  
103 - if(signalState != null)  
104 - signalStateData.put(signalState);  
105 - }  
106 - }  
107 -  
108 - public void signalRetrospect(GpsEntity gps) {  
109 - signalRetrospect(gps, dayOfSchedule.executeCurr(gps.getNbbm()));  
110 - }  
111 -  
112 - /**  
113 - * 信号追溯  
114 - *  
115 - * @param gps  
116 - * @param sch  
117 - */  
118 - public void signalRetrospect(GpsEntity gps, ScheduleRealInfo sch) {  
119 - //回放数据,是否有掉线或者漂移  
120 - CircleQueue<GpsEntity> queue = GeoCacheData.getGps(gps.getNbbm());  
121 - if (queue == null || queue.size() == 0 /*|| gps.getInstation() == 0*/)  
122 - return;  
123 -  
124 - //起始时间点  
125 - long st = 0;  
126 - ScheduleRealInfo prev = dayOfSchedule.prev(sch);  
127 -  
128 - if (prev != null) {  
129 - if (prev.getZdsjActual() != null)  
130 - st = prev.getZdsjActualTime();  
131 - else  
132 - st = (GeoCacheData.midwayStation(gps.getLineId(), gps.getUpDown(), sch.getQdzCode(), gps.getStopNo()).size() + 1) * (1000 * 60 * 5);  
133 - }  
134 -  
135 - Object[] tempArray = queue.getQueue();  
136 - int len = tempArray.length;  
137 -  
138 - Object[] array = new Object[len + 1];  
139 - System.arraycopy(tempArray, 0, array, 0, len);  
140 - array[len] = gps;  
141 -  
142 - String gpsState = "";  
143 - GpsEntity tempGps, nearGps = null;  
144 - int i = len - 1;  
145 - for (; i >= 0; i--) {  
146 - tempGps = (GpsEntity) array[i];  
147 -  
148 - gpsState = tempGps.getSignalState();  
149 - if (gpsState.equals("truncation"))  
150 - break;  
151 - else if (gpsState.equals("drift")) {  
152 - nearGps = (GpsEntity) array[i + 1];  
153 - break;  
154 - } else if (gpsState.equals("reconnection")) {  
155 - nearGps = tempGps;  
156 - break;  
157 - }  
158 -  
159 - if (tempGps.getTimestamp() < st)  
160 - break;  
161 - }  
162 -  
163 - if (nearGps != null && i > 0) {  
164 - createSignalAbnormal(gpsState, nearGps, i, array, sch);  
165 - }  
166 - }  
167 -  
168 - private void createSignalAbnormal(String gpsState, GpsEntity nearGps, int i, Object[] array, ScheduleRealInfo sch) {  
169 - switch (gpsState) {  
170 - case "drift":  
171 - driftSignalAbnormal(nearGps, i, array, sch);  
172 - break;  
173 - case "reconnection":  
174 - offlineSignalAbnormal(nearGps, ((GpsEntity) array[i - 1]), sch);  
175 - break;  
176 - }  
177 - }  
178 -  
179 - /**  
180 - * 掉线异常状态记录  
181 - *  
182 - * @param e  
183 - * @param s  
184 - */  
185 - private void offlineSignalAbnormal(GpsEntity e, GpsEntity s, ScheduleRealInfo sch) {  
186 - long st = s.getTimestamp(), et = e.getTimestamp();  
187 -  
188 - //掉线超过10分钟才记录  
189 - if (et - st < (1000 * 60 * 10))  
190 - return;  
191 -  
192 - SignalAbnormal signalAbnormal = new SignalAbnormal();  
193 - signalAbnormal.setSt(st);  
194 - signalAbnormal.setEt(et);  
195 - signalAbnormal.setAbnormalType("reconnection");  
196 - signalAbnormal.setDestCode(sch.getQdzCode());  
197 - signalAbnormal.setOutOrIn(0);  
198 -  
199 - //截断GPS  
200 - e.setSignalState("truncation");  
201 -  
202 - //记录信号状态  
203 - SignalState signalState = SignalState.abnormalSignalSTate(sch, signalAbnormal);  
204 - signalStateData.put(signalState);  
205 - }  
206 -  
207 - /**  
208 - * 漂移异常状态记录  
209 - *  
210 - * @param nearGps  
211 - * @param i  
212 - * @param array  
213 - */  
214 - private void driftSignalAbnormal(GpsEntity nearGps, int i, Object[] array, ScheduleRealInfo sch) {  
215 - GpsEntity gps, s = null;  
216 - //找到漂移开始时间  
217 - for (; i >= 0; i--) {  
218 - gps = (GpsEntity) array[i];  
219 -  
220 - if (!gps.getSignalState().equals("drift") || i == 0  
221 - || gps.getSignalState().equals("truncation")) {  
222 - s = gps;  
223 - break;  
224 - }  
225 - }  
226 -  
227 - long st = s.getTimestamp(), et = nearGps.getTimestamp();  
228 - if (et - st < (1000 * 60 * 3))  
229 - return;  
230 - /*if (s != null){  
231 - st = s.getTimestamp();  
232 - //漂移小于3分钟  
233 - if(et - st < (1000 * 60 * 3))  
234 - return;  
235 - }*/  
236 -  
237 -  
238 - SignalAbnormal signalAbnormal = new SignalAbnormal();  
239 - signalAbnormal.setSt(st);  
240 - signalAbnormal.setEt(et);  
241 - signalAbnormal.setAbnormalType("drift");  
242 - signalAbnormal.setDestCode(sch.getQdzCode());  
243 - signalAbnormal.setOutOrIn(0);  
244 -  
245 - //截断GPS  
246 - nearGps.setSignalState("truncation");  
247 -  
248 - //记录信号状态  
249 - SignalState signalState = SignalState.abnormalSignalSTate(sch, signalAbnormal);  
250 - signalStateData.put(signalState);  
251 - } 1 +package com.bsth.data.gpsdata.arrival.utils;
  2 +
  3 +import com.bsth.data.LineConfigData;
  4 +import com.bsth.data.gpsdata.GpsEntity;
  5 +import com.bsth.data.gpsdata.SignalStateData;
  6 +import com.bsth.data.gpsdata.arrival.GeoCacheData;
  7 +import com.bsth.data.gpsdata.arrival.entity.RouteReverse;
  8 +import com.bsth.data.gpsdata.arrival.entity.SignalAbnormal;
  9 +import com.bsth.data.gpsdata.arrival.entity.SignalState;
  10 +import com.bsth.data.schedule.DayOfSchedule;
  11 +import com.bsth.entity.realcontrol.LineConfig;
  12 +import com.bsth.entity.realcontrol.ScheduleRealInfo;
  13 +import org.slf4j.Logger;
  14 +import org.slf4j.LoggerFactory;
  15 +import org.springframework.beans.factory.annotation.Autowired;
  16 +import org.springframework.stereotype.Component;
  17 +
  18 +/**
  19 + * 班次信号状态分析
  20 + * Created by panzhao on 2016/12/29.
  21 + */
  22 +@Component
  23 +public class ScheduleSignalState {
  24 +
  25 + @Autowired
  26 + DayOfSchedule dayOfSchedule;
  27 +
  28 + Logger logger = LoggerFactory.getLogger(this.getClass());
  29 +
  30 + @Autowired
  31 + LineConfigData lineConfigData;
  32 +
  33 + @Autowired
  34 + SignalStateData signalStateData;
  35 +
  36 + /**
  37 + * 路由反向分析
  38 + */
  39 + public void reverseAnalyse(RouteReverse reverse) {
  40 + ScheduleRealInfo sch = dayOfSchedule.executeCurr(reverse.getNbbm());
  41 +
  42 + String bcType = sch.getBcType();
  43 +
  44 + switch (bcType) {
  45 + case "out":
  46 + outReverseAnalyse(sch, reverse);
  47 + break;
  48 + case "normal":
  49 + normalReverseAnalyse(sch, reverse);
  50 + break;
  51 + }
  52 + }
  53 +
  54 + /**
  55 + * 出场班次路由反向分析
  56 + *
  57 + * @param sch
  58 + */
  59 + private void outReverseAnalyse(ScheduleRealInfo sch, RouteReverse reverse) {
  60 + long t = reverse.getCt();
  61 + //出场班次终点时间前,允许反向轨迹
  62 + if (sch.getZdsjT() != null && sch.getZdsjT() > t) {
  63 + return;
  64 + }
  65 +
  66 + int rt;
  67 + //从实发 到 当前时间 < 计划运送时间 * 0.9
  68 + if (sch.getFcsjActual() != null && sch.getBcsj() != null) {
  69 + rt = (int) (t - sch.getFcsjActualTime());
  70 + if (rt < sch.getBcsj() * 0.9)
  71 + return;
  72 + }
  73 +
  74 + ScheduleRealInfo next = dayOfSchedule.next(sch);
  75 + if (next.getXlDir().equals(sch.getXlDir()))
  76 + return;
  77 +
  78 + //时间足够下一个班次待发时间运行到当前站
  79 + int runTime = reverse.getCount() * 1500 * 60;
  80 + if (next.getDfsjT() + runTime < t) {
  81 + //跳到下一个班次
  82 + dayOfSchedule.addExecPlan(next);
  83 + }
  84 + }
  85 +
  86 + /**
  87 + * 正常班次路由反向分析
  88 + *
  89 + * @param sch
  90 + * @param reverse
  91 + */
  92 + private void normalReverseAnalyse(ScheduleRealInfo sch, RouteReverse reverse) {
  93 + LineConfig conf = lineConfigData.get(sch.getXlBm());
  94 +
  95 + if (conf.isReadReverse()) {
  96 + //跳下一个班次
  97 + ScheduleRealInfo next = dayOfSchedule.next(sch);
  98 + if (next != null)
  99 + dayOfSchedule.addExecPlan(next);
  100 +
  101 + //记录信号状态
  102 + SignalState signalState = SignalState.reverseSignalSTate(sch, reverse);
  103 + if(signalState != null)
  104 + signalStateData.put(signalState);
  105 + }
  106 + }
  107 +
  108 + public void signalRetrospect(GpsEntity gps) {
  109 + signalRetrospect(gps, dayOfSchedule.executeCurr(gps.getNbbm()));
  110 + }
  111 +
  112 + /**
  113 + * 信号追溯
  114 + *
  115 + * @param gps
  116 + * @param sch
  117 + */
  118 + public void signalRetrospect(GpsEntity gps, ScheduleRealInfo sch) {
  119 + //回放数据,是否有掉线或者漂移
  120 + CircleQueue<GpsEntity> queue = GeoCacheData.getGps(gps.getNbbm());
  121 + if (queue == null || queue.size() == 0 /*|| gps.getInstation() == 0*/)
  122 + return;
  123 +
  124 + //起始时间点
  125 + long st = 0;
  126 + ScheduleRealInfo prev = dayOfSchedule.prev(sch);
  127 +
  128 + if (prev != null) {
  129 + if (prev.getZdsjActual() != null)
  130 + st = prev.getZdsjActualTime();
  131 + else
  132 + st = (GeoCacheData.midwayStation(gps.getLineId(), gps.getUpDown(), sch.getQdzCode(), gps.getStopNo()).size() + 1) * (1000 * 60 * 5);
  133 + }
  134 +
  135 + Object[] tempArray = queue.getQueue();
  136 + int len = tempArray.length;
  137 +
  138 + Object[] array = new Object[len + 1];
  139 + System.arraycopy(tempArray, 0, array, 0, len);
  140 + array[len] = gps;
  141 +
  142 + String gpsState = "";
  143 + GpsEntity tempGps, nearGps = null;
  144 + int i = len - 1;
  145 + for (; i >= 0; i--) {
  146 + tempGps = (GpsEntity) array[i];
  147 +
  148 + gpsState = tempGps.getSignalState();
  149 + if (gpsState.equals("truncation"))
  150 + break;
  151 + else if (gpsState.equals("drift")) {
  152 + nearGps = (GpsEntity) array[i + 1];
  153 + break;
  154 + } else if (gpsState.equals("reconnection")) {
  155 + nearGps = tempGps;
  156 + break;
  157 + }
  158 +
  159 + if (tempGps.getTimestamp() < st)
  160 + break;
  161 + }
  162 +
  163 + if (nearGps != null && i > 0) {
  164 + createSignalAbnormal(gpsState, nearGps, i, array, sch);
  165 + }
  166 + }
  167 +
  168 + private void createSignalAbnormal(String gpsState, GpsEntity nearGps, int i, Object[] array, ScheduleRealInfo sch) {
  169 + switch (gpsState) {
  170 + case "drift":
  171 + driftSignalAbnormal(nearGps, i, array, sch);
  172 + break;
  173 + case "reconnection":
  174 + offlineSignalAbnormal(nearGps, ((GpsEntity) array[i - 1]), sch);
  175 + break;
  176 + }
  177 + }
  178 +
  179 + /**
  180 + * 掉线异常状态记录
  181 + *
  182 + * @param e
  183 + * @param s
  184 + */
  185 + private void offlineSignalAbnormal(GpsEntity e, GpsEntity s, ScheduleRealInfo sch) {
  186 + long st = s.getTimestamp(), et = e.getTimestamp();
  187 +
  188 + //掉线超过10分钟才记录
  189 + if (et - st < (1000 * 60 * 10))
  190 + return;
  191 +
  192 + SignalAbnormal signalAbnormal = new SignalAbnormal();
  193 + signalAbnormal.setSt(st);
  194 + signalAbnormal.setEt(et);
  195 + signalAbnormal.setAbnormalType("reconnection");
  196 + signalAbnormal.setDestCode(sch.getQdzCode());
  197 + signalAbnormal.setOutOrIn(0);
  198 +
  199 + //截断GPS
  200 + e.setSignalState("truncation");
  201 +
  202 + //记录信号状态
  203 + SignalState signalState = SignalState.abnormalSignalSTate(sch, signalAbnormal);
  204 + signalStateData.put(signalState);
  205 + }
  206 +
  207 + /**
  208 + * 漂移异常状态记录
  209 + *
  210 + * @param nearGps
  211 + * @param i
  212 + * @param array
  213 + */
  214 + private void driftSignalAbnormal(GpsEntity nearGps, int i, Object[] array, ScheduleRealInfo sch) {
  215 + GpsEntity gps, s = null;
  216 + //找到漂移开始时间
  217 + for (; i >= 0; i--) {
  218 + gps = (GpsEntity) array[i];
  219 +
  220 + if (!gps.getSignalState().equals("drift") || i == 0
  221 + || gps.getSignalState().equals("truncation")) {
  222 + s = gps;
  223 + break;
  224 + }
  225 + }
  226 +
  227 + long st = s.getTimestamp(), et = nearGps.getTimestamp();
  228 + if (et - st < (1000 * 60 * 3))
  229 + return;
  230 + /*if (s != null){
  231 + st = s.getTimestamp();
  232 + //漂移小于3分钟
  233 + if(et - st < (1000 * 60 * 3))
  234 + return;
  235 + }*/
  236 +
  237 +
  238 + SignalAbnormal signalAbnormal = new SignalAbnormal();
  239 + signalAbnormal.setSt(st);
  240 + signalAbnormal.setEt(et);
  241 + signalAbnormal.setAbnormalType("drift");
  242 + signalAbnormal.setDestCode(sch.getQdzCode());
  243 + signalAbnormal.setOutOrIn(0);
  244 +
  245 + //截断GPS
  246 + nearGps.setSignalState("truncation");
  247 +
  248 + //记录信号状态
  249 + SignalState signalState = SignalState.abnormalSignalSTate(sch, signalAbnormal);
  250 + signalStateData.put(signalState);
  251 + }
252 } 252 }
253 \ No newline at end of file 253 \ No newline at end of file
src/main/java/com/bsth/entity/sys/DutyEmployee.java
1 -package com.bsth.entity.sys;  
2 -  
3 -import javax.persistence.*;  
4 -  
5 -/**  
6 - * 当班调度员  
7 - * Created by panzhao on 2017/1/5.  
8 - */  
9 -@Entity  
10 -@Table(name = "bsth_c_sys_duty_employee")  
11 -public class DutyEmployee {  
12 -  
13 - @Id  
14 - @GeneratedValue  
15 - private Long id;  
16 -  
17 - /**  
18 - * 员工ID  
19 - */  
20 - private Integer uId;  
21 -  
22 - /**  
23 - * 员工姓名  
24 - */  
25 - private String uName;  
26 -  
27 - /**  
28 - * 线路编码 ,号分割多个  
29 - */  
30 - private String codeIdx;  
31 -  
32 - /**  
33 - * 登入线调时间  
34 - */  
35 - private Long ts;  
36 -  
37 - /**  
38 - * 是否主调模式进入  
39 - */  
40 - private boolean main;  
41 -  
42 - public Integer getuId() {  
43 - return uId;  
44 - }  
45 -  
46 - public void setuId(Integer uId) {  
47 - this.uId = uId;  
48 - }  
49 -  
50 - public String getuName() {  
51 - return uName;  
52 - }  
53 -  
54 - public void setuName(String uName) {  
55 - this.uName = uName;  
56 - }  
57 -  
58 - public String getCodeIdx() {  
59 - return codeIdx;  
60 - }  
61 -  
62 - public void setCodeIdx(String codeIdx) {  
63 - this.codeIdx = codeIdx;  
64 - }  
65 -  
66 - public Long getTs() {  
67 - return ts;  
68 - }  
69 -  
70 - public void setTs(Long ts) {  
71 - this.ts = ts;  
72 - }  
73 -  
74 - public boolean isMain() {  
75 - return main;  
76 - }  
77 -  
78 - public void setMain(boolean main) {  
79 - this.main = main;  
80 - }  
81 -  
82 - public Long getId() {  
83 - return id;  
84 - }  
85 -  
86 - public void setId(Long id) {  
87 - this.id = id;  
88 - }  
89 -} 1 +package com.bsth.entity.sys;
  2 +
  3 +import javax.persistence.*;
  4 +
  5 +/**
  6 + * 当班调度员
  7 + * Created by panzhao on 2017/1/5.
  8 + */
  9 +@Entity
  10 +@Table(name = "bsth_c_sys_duty_employee")
  11 +public class DutyEmployee {
  12 +
  13 + @Id
  14 + @GeneratedValue
  15 + private Long id;
  16 +
  17 + /**
  18 + * 员工ID
  19 + */
  20 + private Integer uId;
  21 +
  22 + /**
  23 + * 员工姓名
  24 + */
  25 + private String uName;
  26 +
  27 + /**
  28 + * 线路编码 ,号分割多个
  29 + */
  30 + private String codeIdx;
  31 +
  32 + /**
  33 + * 登入线调时间
  34 + */
  35 + private Long ts;
  36 +
  37 + /**
  38 + * 是否主调模式进入
  39 + */
  40 + private boolean main;
  41 +
  42 + public Integer getuId() {
  43 + return uId;
  44 + }
  45 +
  46 + public void setuId(Integer uId) {
  47 + this.uId = uId;
  48 + }
  49 +
  50 + public String getuName() {
  51 + return uName;
  52 + }
  53 +
  54 + public void setuName(String uName) {
  55 + this.uName = uName;
  56 + }
  57 +
  58 + public String getCodeIdx() {
  59 + return codeIdx;
  60 + }
  61 +
  62 + public void setCodeIdx(String codeIdx) {
  63 + this.codeIdx = codeIdx;
  64 + }
  65 +
  66 + public Long getTs() {
  67 + return ts;
  68 + }
  69 +
  70 + public void setTs(Long ts) {
  71 + this.ts = ts;
  72 + }
  73 +
  74 + public boolean isMain() {
  75 + return main;
  76 + }
  77 +
  78 + public void setMain(boolean main) {
  79 + this.main = main;
  80 + }
  81 +
  82 + public Long getId() {
  83 + return id;
  84 + }
  85 +
  86 + public void setId(Long id) {
  87 + this.id = id;
  88 + }
  89 +}
src/main/java/com/bsth/repository/realcontrol/ScheduleRealInfoRepository.java
@@ -110,7 +110,7 @@ public interface ScheduleRealInfoRepository extends BaseRepository&lt;ScheduleRealI @@ -110,7 +110,7 @@ public interface ScheduleRealInfoRepository extends BaseRepository&lt;ScheduleRealI
110 @Query(value="select s from ScheduleRealInfo s where s.xlBm like %?1% and DATE_FORMAT(s.scheduleDate,'%Y-%m-%d') = ?2") 110 @Query(value="select s from ScheduleRealInfo s where s.xlBm like %?1% and DATE_FORMAT(s.scheduleDate,'%Y-%m-%d') = ?2")
111 List<ScheduleRealInfo> scheduleByDateAndLine(String line,String date); 111 List<ScheduleRealInfo> scheduleByDateAndLine(String line,String date);
112 112
113 - @Query(value="select new map(s.scheduleDate as scheduleDate,s.xlBm as xlBm,s.clZbh as clZbh,s.jGh as jGh) from ScheduleRealInfo s where s.xlBm like %?1% and DATE_FORMAT(s.scheduleDate,'%Y-%m-%d') = ?2 GROUP BY xlBm,clZbh,jGh,scheduleDate,jGh ORDER BY xlBm,clZbh") 113 + @Query(value="select new map(s.scheduleDate as scheduleDate,s.xlBm as xlBm,s.clZbh as clZbh,s.jGh as jGh) from ScheduleRealInfo s where s.xlBm like %?1% and DATE_FORMAT(s.scheduleDate,'%Y-%m-%d') = ?2 GROUP BY xlBm,clZbh,jGh,scheduleDate,jGh ORDER BY realExecDate,fcsj,xlBm,clZbh")
114 List<Map<String,Object>> yesterdayDataList(String line,String date); 114 List<Map<String,Object>> yesterdayDataList(String line,String date);
115 115
116 @Query(value="select s from ScheduleRealInfo s where DATE_FORMAT(s.scheduleDate,'%Y-%m-%d') = ?1 ORDER BY xlBm,lpName,clZbh,xlDir") 116 @Query(value="select s from ScheduleRealInfo s where DATE_FORMAT(s.scheduleDate,'%Y-%m-%d') = ?1 ORDER BY xlBm,lpName,clZbh,xlDir")
src/main/java/com/bsth/repository/sys/DutyEmployeeRepository.java
1 -package com.bsth.repository.sys;  
2 -  
3 -import com.bsth.entity.sys.DutyEmployee;  
4 -import com.bsth.repository.BaseRepository;  
5 -import org.springframework.data.jpa.repository.Query;  
6 -import org.springframework.stereotype.Repository;  
7 -  
8 -import java.util.List;  
9 -  
10 -/**  
11 - * Created by panzhao on 2017/1/5.  
12 - */  
13 -@Repository  
14 -public interface DutyEmployeeRepository extends BaseRepository<DutyEmployee, Long>{  
15 -  
16 - @Query("select t from DutyEmployee t where t.codeIdx like %?1% and t.ts > ?2 and t.ts < ?3")  
17 - List<DutyEmployee> findByLineAndTime(String lineCode, long st, long et);  
18 -} 1 +package com.bsth.repository.sys;
  2 +
  3 +import com.bsth.entity.sys.DutyEmployee;
  4 +import com.bsth.repository.BaseRepository;
  5 +import org.springframework.data.jpa.repository.Query;
  6 +import org.springframework.stereotype.Repository;
  7 +
  8 +import java.util.List;
  9 +
  10 +/**
  11 + * Created by panzhao on 2017/1/5.
  12 + */
  13 +@Repository
  14 +public interface DutyEmployeeRepository extends BaseRepository<DutyEmployee, Long>{
  15 +
  16 + @Query("select t from DutyEmployee t where t.codeIdx like %?1% and t.ts > ?2 and t.ts < ?3")
  17 + List<DutyEmployee> findByLineAndTime(String lineCode, long st, long et);
  18 +}
src/main/java/com/bsth/service/impl/TrafficManageServiceImpl.java
@@ -390,36 +390,44 @@ public class TrafficManageServiceImpl implements TrafficManageService{ @@ -390,36 +390,44 @@ public class TrafficManageServiceImpl implements TrafficManageService{
390 Map<String,Object> map = new HashMap<String,Object>(); 390 Map<String,Object> map = new HashMap<String,Object>();
391 for(Map<String,Object> schRealInfo:listGroup){ 391 for(Map<String,Object> schRealInfo:listGroup){
392 if(schRealInfo != null){ 392 if(schRealInfo != null){
  393 + map.put("insideCode_eq", schRealInfo.get("clZbh")+"");
  394 + Cars car = carsRepository.findOne(new CustomerSpecs<Cars>(map));
  395 + /**
  396 + * 如果car==null,则说明该车辆是从线调中换车功能中加进去的,
  397 + * 在cars基础信息中查不到车辆的信息,所以忽略该车辆
  398 + */
  399 + if(car == null){
  400 + continue;
  401 + }
393 //计算总公里和空驶公里,营运公里=总公里-空驶公里 402 //计算总公里和空驶公里,营运公里=总公里-空驶公里
394 double totalKilometers = 0,emptyKilometers =0; 403 double totalKilometers = 0,emptyKilometers =0;
395 sf.append("<LCYH>"); 404 sf.append("<LCYH>");
396 - map.put("insideCode_eq", schRealInfo.get("clZbh")+"");  
397 - Cars car = carsRepository.findOne(new CustomerSpecs<Cars>(map));  
398 -// Cars car = carsRepository.findCarByClzbh(schRealInfo.getClZbh());  
399 sf.append("<RQ>"+date+"</RQ>"); 405 sf.append("<RQ>"+date+"</RQ>");
400 sf.append("<XLBM>"+BasicData.lineCode2ShangHaiCodeMap.get(schRealInfo.get("xlBm"))+"</XLBM>"); 406 sf.append("<XLBM>"+BasicData.lineCode2ShangHaiCodeMap.get(schRealInfo.get("xlBm"))+"</XLBM>");
401 sf.append("<CPH>"+car.getCarPlate()+"</CPH>"); 407 sf.append("<CPH>"+car.getCarPlate()+"</CPH>");
402 - for(ScheduleRealInfo scheduleRealInfo:list){  
403 - if((schRealInfo.get("xlBm")+"").equals(scheduleRealInfo.getXlBm()) && (schRealInfo.get("clZbh")+"")  
404 - .equals(scheduleRealInfo.getClZbh())){  
405 - Set<ChildTaskPlan> childTaskPlans = scheduleRealInfo.getcTasks();  
406 - //如果没有子任务,里程就是已执行(Status=2);有子任务的,忽略主任务,子任务的烂班  
407 - if(childTaskPlans.isEmpty()){  
408 - if(scheduleRealInfo.getStatus() == 2){  
409 - totalKilometers += scheduleRealInfo.getJhlc()==null?0.0:scheduleRealInfo.getJhlc();  
410 - if(scheduleRealInfo.getBcType().equals("in") || scheduleRealInfo.getBcType().equals("out")  
411 - || scheduleRealInfo.getBcType().equals("venting")){  
412 - emptyKilometers += scheduleRealInfo.getJhlc()==null?0.0:scheduleRealInfo.getJhlc(); 408 + if(list != null && list.size() > 0){
  409 + for(ScheduleRealInfo scheduleRealInfo:list){
  410 + if((schRealInfo.get("xlBm")+"").equals(scheduleRealInfo.getXlBm()) && (schRealInfo.get("clZbh")+"")
  411 + .equals(scheduleRealInfo.getClZbh())){
  412 + Set<ChildTaskPlan> childTaskPlans = scheduleRealInfo.getcTasks();
  413 + //如果没有子任务,里程就是已执行(Status=2);有子任务的,忽略主任务,子任务的烂班
  414 + if(childTaskPlans.isEmpty()){
  415 + if(scheduleRealInfo.getStatus() == 2){
  416 + totalKilometers += scheduleRealInfo.getJhlc()==null?0.0:scheduleRealInfo.getJhlc();
  417 + if(scheduleRealInfo.getBcType().equals("in") || scheduleRealInfo.getBcType().equals("out")
  418 + || scheduleRealInfo.getBcType().equals("venting")){
  419 + emptyKilometers += scheduleRealInfo.getJhlc()==null?0.0:scheduleRealInfo.getJhlc();
  420 + }
413 } 421 }
414 - }  
415 - }else{  
416 - Iterator<ChildTaskPlan> it = childTaskPlans.iterator();  
417 - while(it.hasNext()){  
418 - ChildTaskPlan childTaskPlan = it.next();  
419 - if(!childTaskPlan.isDestroy()){  
420 - totalKilometers += childTaskPlan.getMileage()==null?0.0:childTaskPlan.getMileage();  
421 - if(childTaskPlan.getMileageType().equals("empty")){  
422 - emptyKilometers += childTaskPlan.getMileage()==null?0.0:childTaskPlan.getMileage();; 422 + }else{
  423 + Iterator<ChildTaskPlan> it = childTaskPlans.iterator();
  424 + while(it.hasNext()){
  425 + ChildTaskPlan childTaskPlan = it.next();
  426 + if(!childTaskPlan.isDestroy()){
  427 + totalKilometers += childTaskPlan.getMileage()==null?0.0:childTaskPlan.getMileage();
  428 + if(childTaskPlan.getMileageType().equals("empty")){
  429 + emptyKilometers += childTaskPlan.getMileage()==null?0.0:childTaskPlan.getMileage();;
  430 + }
423 } 431 }
424 } 432 }
425 } 433 }
@@ -604,8 +612,8 @@ public class TrafficManageServiceImpl implements TrafficManageService{ @@ -604,8 +612,8 @@ public class TrafficManageServiceImpl implements TrafficManageService{
604 schedulePlanInfo.getXlBm(), schedulePlanInfo.getXlDir(), schedulePlanInfo.getQdzName())).append("</ZDXH>"); 612 schedulePlanInfo.getXlBm(), schedulePlanInfo.getXlDir(), schedulePlanInfo.getQdzName())).append("</ZDXH>");
605 sBuffer.append("<JHFCSJ>").append(schedulePlanInfo.getFcsj()).append("</JHFCSJ>"); 613 sBuffer.append("<JHFCSJ>").append(schedulePlanInfo.getFcsj()).append("</JHFCSJ>");
606 sBuffer.append("<DDZDMC>").append(schedulePlanInfo.getZdzName()).append("</DDZDMC>"); 614 sBuffer.append("<DDZDMC>").append(schedulePlanInfo.getZdzName()).append("</DDZDMC>");
607 - sBuffer.append("<ZDXH>").append(getYgcStationNumByLineCodeAndDirectionAndStationName(  
608 - schedulePlanInfo.getXlBm(), schedulePlanInfo.getXlDir(), schedulePlanInfo.getZdzName())).append("</ZDXH>"); 615 + sBuffer.append("<DDXH>").append(getYgcStationNumByLineCodeAndDirectionAndStationName(
  616 + schedulePlanInfo.getXlBm(), schedulePlanInfo.getXlDir(), schedulePlanInfo.getZdzName())).append("</DDXH>");
609 sBuffer.append("<JHDDSJ>").append(calcDdsj(schedulePlanInfo.getFcsj(),schedulePlanInfo.getBcsj())) 617 sBuffer.append("<JHDDSJ>").append(calcDdsj(schedulePlanInfo.getFcsj(),schedulePlanInfo.getBcsj()))
610 .append("</JHDDSJ>"); 618 .append("</JHDDSJ>");
611 sBuffer.append("</BC>"); 619 sBuffer.append("</BC>");
src/main/java/com/bsth/service/oil/impl/YlbServiceImpl.java
@@ -132,7 +132,7 @@ public class YlbServiceImpl extends BaseServiceImpl&lt;Ylb,Integer&gt; implements YlbS @@ -132,7 +132,7 @@ public class YlbServiceImpl extends BaseServiceImpl&lt;Ylb,Integer&gt; implements YlbS
132 t.setJcsx(Integer.parseInt(map.get("seqNumber").toString())); 132 t.setJcsx(Integer.parseInt(map.get("seqNumber").toString()));
133 t.setSsgsdm(map.get("company")==null?"":map.get("company").toString()); 133 t.setSsgsdm(map.get("company")==null?"":map.get("company").toString());
134 t.setFgsdm(map.get("bCompany")==null?"":map.get("bCompany").toString()); 134 t.setFgsdm(map.get("bCompany")==null?"":map.get("bCompany").toString());
135 - t.setRq(dBefore); 135 + t.setRq(sdf.parse(rq));
136 repository.save(t); 136 repository.save(t);
137 result = "success"; 137 result = "success";
138 } catch (Exception e) { 138 } catch (Exception e) {
src/main/java/com/bsth/service/realcontrol/impl/ScheduleRealInfoServiceImpl.java
@@ -1653,7 +1653,7 @@ public class ScheduleRealInfoServiceImpl extends BaseServiceImpl&lt;ScheduleRealInf @@ -1653,7 +1653,7 @@ public class ScheduleRealInfoServiceImpl extends BaseServiceImpl&lt;ScheduleRealInf
1653 1653
1654 @Override 1654 @Override
1655 public List<ScheduleRealInfo> realScheduleList(String line, String date) { 1655 public List<ScheduleRealInfo> realScheduleList(String line, String date) {
1656 - List<ScheduleRealInfo> listInfo = scheduleRealInfoRepository.queryUserInfo(line, date); 1656 + /*List<ScheduleRealInfo> listInfo = scheduleRealInfoRepository.queryUserInfo(line, date);
1657 List<ScheduleRealInfo> listTotal = scheduleRealInfoRepository.scheduleByDateAndLine(line, date); 1657 List<ScheduleRealInfo> listTotal = scheduleRealInfoRepository.scheduleByDateAndLine(line, date);
1658 for(ScheduleRealInfo info:listInfo){ 1658 for(ScheduleRealInfo info:listInfo){
1659 for(ScheduleRealInfo total:listTotal){ 1659 for(ScheduleRealInfo total:listTotal){
@@ -1661,7 +1661,7 @@ public class ScheduleRealInfoServiceImpl extends BaseServiceImpl&lt;ScheduleRealInf @@ -1661,7 +1661,7 @@ public class ScheduleRealInfoServiceImpl extends BaseServiceImpl&lt;ScheduleRealInf
1661 1661
1662 } 1662 }
1663 } 1663 }
1664 - } 1664 + }*/
1665 return scheduleRealInfoRepository.scheduleByDateAndLine(line, date); 1665 return scheduleRealInfoRepository.scheduleByDateAndLine(line, date);
1666 } 1666 }
1667 1667
@@ -1671,8 +1671,84 @@ public class ScheduleRealInfoServiceImpl extends BaseServiceImpl&lt;ScheduleRealInf @@ -1671,8 +1671,84 @@ public class ScheduleRealInfoServiceImpl extends BaseServiceImpl&lt;ScheduleRealInf
1671 // String date = sdfMonth.format(org.apache.commons.lang.time.DateUtils.addDays(new Date(), -1)); 1671 // String date = sdfMonth.format(org.apache.commons.lang.time.DateUtils.addDays(new Date(), -1));
1672 // String date = "2016-09-20"; 1672 // String date = "2016-09-20";
1673 List<Map<String,Object>> yesterdayDataList = scheduleRealInfoRepository.yesterdayDataList(line, date); 1673 List<Map<String,Object>> yesterdayDataList = scheduleRealInfoRepository.yesterdayDataList(line, date);
1674 - List<ScheduleRealInfo> list = scheduleRealInfoRepository.scheduleByDateAndLine(line, date);  
1675 - for(ScheduleRealInfo scheduleRealInfo:list){ 1674 +// List<ScheduleRealInfo> list = scheduleRealInfoRepository.scheduleByDateAndLine(line, date);
  1675 + for(int x=0;x<yesterdayDataList.size();x++){
  1676 + String jName=yesterdayDataList.get(x).get("jGh").toString();
  1677 + String clZbh=yesterdayDataList.get(x).get("clZbh").toString();
  1678 + List<ScheduleRealInfo> lists=scheduleRealInfoRepository.queryListWaybill3(jName, clZbh, date);
  1679 + double jhlc = 0, yygl = 0, ksgl = 0,tempJhlc = 0,jcclc=0;
  1680 + float addMileage = 0l,remMileage = 0l;
  1681 + Map<String,Object> map = new HashMap<String, Object>();
  1682 + boolean fage=true;
  1683 + for(ScheduleRealInfo scheduleRealInfo : lists){
  1684 + if(fage){
  1685 + //根据线路代码获取公司
  1686 + Line li = lineRepository.findByLineCode(scheduleRealInfo.getXlBm());
  1687 + yesterdayDataList.get(x).put("company", li.getCompany());
  1688 + yesterdayDataList.get(x).put("bCompany", li.getBrancheCompany());
  1689 + fage=false;
  1690 + }
  1691 + if(scheduleRealInfo != null){
  1692 + //计划里程(主任务过滤掉临加班次),
  1693 + //烂班里程(主任务烂班),
  1694 + //临加里程(主任务临加),
  1695 + //计划班次,烂班班次,增加班次
  1696 + tempJhlc = scheduleRealInfo.getJhlc()==null?0:scheduleRealInfo.getJhlc();
  1697 + if(scheduleRealInfo.isSflj()){
  1698 + addMileage += tempJhlc;
  1699 + }else{
  1700 + if( !(scheduleRealInfo.getBcType().equals("in")
  1701 + ||scheduleRealInfo.getBcType().equals("out")) ){
  1702 + jhlc += tempJhlc;
  1703 + }
  1704 +
  1705 + if(scheduleRealInfo.getStatus() == -1){
  1706 + remMileage += tempJhlc;
  1707 + }
  1708 + }
  1709 + Set<ChildTaskPlan> childTaskPlans = scheduleRealInfo.getcTasks();
  1710 + //计算营运里程,空驶里程
  1711 + if(childTaskPlans.isEmpty()){
  1712 + if(scheduleRealInfo.getBcType().equals("in") ||
  1713 + scheduleRealInfo.getBcType().equals("out")){
  1714 + jcclc +=tempJhlc;
  1715 + }
  1716 + //主任务 放空班次属于营运
  1717 +// else if(scheduleRealInfo.getBcType().equals("venting")){
  1718 +// ksgl += tempJhlc;
  1719 +// }
  1720 + else{
  1721 + if(scheduleRealInfo.getStatus() != -1){
  1722 + yygl += tempJhlc;
  1723 + }
  1724 + }
  1725 + }else{
  1726 + Iterator<ChildTaskPlan> it = childTaskPlans.iterator();
  1727 + while(it.hasNext()){
  1728 + ChildTaskPlan childTaskPlan = it.next();
  1729 + if(childTaskPlan.getMileageType().equals("empty")){
  1730 + if(childTaskPlan.isDestroy()){
  1731 + remMileage += childTaskPlan.getMileage()==null?0:childTaskPlan.getMileage();
  1732 + }else{
  1733 + ksgl += childTaskPlan.getMileage()==null?0:childTaskPlan.getMileage();
  1734 + }
  1735 + }else{
  1736 + if(childTaskPlan.isDestroy()){
  1737 + remMileage += childTaskPlan.getMileage()==null?0:childTaskPlan.getMileage();
  1738 + }else{
  1739 + yygl += childTaskPlan.getMileage()==null?0:childTaskPlan.getMileage();
  1740 + }
  1741 + }
  1742 + }
  1743 + }
  1744 + }
  1745 + }
  1746 +
  1747 + yesterdayDataList.get(x).put("totalKilometers", yygl+ksgl+jcclc);
  1748 +
  1749 + }
  1750 +
  1751 + /* for(ScheduleRealInfo scheduleRealInfo:list){
1676 if(scheduleRealInfo != null){ 1752 if(scheduleRealInfo != null){
1677 for(int i=0;i<yesterdayDataList.size();i++){ 1753 for(int i=0;i<yesterdayDataList.size();i++){
1678 if(scheduleRealInfo.getXlBm().equals(yesterdayDataList.get(i).get("xlBm")) && scheduleRealInfo.getClZbh().equals(yesterdayDataList.get(i).get("clZbh")) 1754 if(scheduleRealInfo.getXlBm().equals(yesterdayDataList.get(i).get("xlBm")) && scheduleRealInfo.getClZbh().equals(yesterdayDataList.get(i).get("clZbh"))
@@ -1700,7 +1776,7 @@ public class ScheduleRealInfoServiceImpl extends BaseServiceImpl&lt;ScheduleRealInf @@ -1700,7 +1776,7 @@ public class ScheduleRealInfoServiceImpl extends BaseServiceImpl&lt;ScheduleRealInf
1700 } 1776 }
1701 } 1777 }
1702 } 1778 }
1703 - } 1779 + }*/
1704 //增加顺序号 1780 //增加顺序号
1705 for(int i=0;i<yesterdayDataList.size();i++){ 1781 for(int i=0;i<yesterdayDataList.size();i++){
1706 if(i == 0){ 1782 if(i == 0){
src/main/java/com/bsth/service/schedule/impl/TTInfoDetailServiceImpl.java
1 -package com.bsth.service.schedule.impl;  
2 -  
3 -import com.bsth.entity.CarPark;  
4 -import com.bsth.entity.LineInformation;  
5 -import com.bsth.entity.StationRoute;  
6 -import com.bsth.entity.schedule.GuideboardInfo;  
7 -import com.bsth.entity.schedule.TTInfoDetail;  
8 -import com.bsth.repository.schedule.TTInfoDetailRepository;  
9 -import com.bsth.service.CarParkService;  
10 -import com.bsth.service.LineInformationService;  
11 -import com.bsth.service.StationRouteService;  
12 -import com.bsth.service.schedule.GuideboardInfoService;  
13 -import com.bsth.service.schedule.TTInfoDetailService;  
14 -import com.bsth.service.schedule.exception.ScheduleException;  
15 -import com.bsth.service.schedule.utils.DataToolsProperties;  
16 -import jxl.Cell;  
17 -import jxl.Sheet;  
18 -import jxl.Workbook;  
19 -import jxl.write.Label;  
20 -import jxl.write.WritableSheet;  
21 -import jxl.write.WritableWorkbook;  
22 -import org.apache.commons.lang3.StringUtils;  
23 -import org.joda.time.DateTime;  
24 -import org.slf4j.Logger;  
25 -import org.slf4j.LoggerFactory;  
26 -import org.springframework.beans.factory.annotation.Autowired;  
27 -import org.springframework.boot.context.properties.EnableConfigurationProperties;  
28 -import org.springframework.stereotype.Service;  
29 -import org.springframework.util.CollectionUtils;  
30 -  
31 -import java.io.File;  
32 -import java.io.PrintWriter;  
33 -import java.io.StringWriter;  
34 -import java.util.*;  
35 -import java.util.regex.Matcher;  
36 -import java.util.regex.Pattern;  
37 -  
38 -/**  
39 - * Created by xu on 17/1/3.  
40 - */  
41 -@Service  
42 -@EnableConfigurationProperties(DataToolsProperties.class)  
43 -public class TTInfoDetailServiceImpl extends BServiceImpl<TTInfoDetail, Long> implements TTInfoDetailService {  
44 - /** 日志记录器 */  
45 - private static final Logger LOGGER = LoggerFactory.getLogger(TTInfoDetailServiceImpl.class);  
46 -  
47 - @Autowired  
48 - private GuideboardInfoService guideboardInfoService;  
49 - @Autowired  
50 - private StationRouteService stationRouteService;  
51 - @Autowired  
52 - private LineInformationService lineInformationService;  
53 - @Autowired  
54 - private CarParkService carParkService;  
55 - @Autowired  
56 - private TTInfoDetailRepository ttInfoDetailRepository;  
57 - @Autowired  
58 - private DataToolsProperties dataToolsProperties;  
59 -  
60 - @Override  
61 - public TTInfoDetail findById(Long aLong) {  
62 - return ttInfoDetailRepository.findOneExtend(aLong);  
63 - }  
64 -  
65 - @Override  
66 - public void importData(  
67 - File file,  
68 - Map<String, Object> params) throws ScheduleException {  
69 -  
70 - try {  
71 - LOGGER.info("//---------------- 导入时刻表明细 start... ----------------//");  
72 -  
73 - String filename = file.getAbsolutePath(); // xls文件名  
74 - String sheetname = String.valueOf(params.get("sheetname")); // sheet名字  
75 - Long ttid = Long.valueOf(String.valueOf(params.get("ttid"))); // 时刻表id  
76 - Long xlid = Long.valueOf(String.valueOf(params.get("xlid"))); // 线路id  
77 - Integer lineid = Integer.valueOf(String.valueOf(params.get("lineinfo"))); // 线路标准id  
78 - String xlname = String.valueOf(params.get("xlname")); // 线路名字  
79 - String ttname = String.valueOf(params.get("ttname")); // 时刻表名字  
80 -  
81 - LOGGER.info("参数1, xls文件名={},sheet名字={}", filename, sheetname);  
82 - LOGGER.info("参数2, 线路id={},线路名字={}", xlid, xlname);  
83 - LOGGER.info("参数3, 时刻表id={},时刻表名字={}", ttid, ttname);  
84 -  
85 - LOGGER.info("转换xls文件格式成文本格式...");  
86 - // 1、修改已经上传的excel文件,在每个起点站后标示数字,表示第几个班次  
87 - // 2、由于格式问题,需要把内容都转换成字符串  
88 - List<String> colList = new ArrayList<>();  
89 - Workbook workbook = Workbook.getWorkbook(new File(filename));  
90 - Sheet sheet = workbook.getSheet(sheetname);  
91 - Cell[] cells = sheet.getRow(0);  
92 - for (int i = 0; i < cells.length; i++) {  
93 - if (i == 0) {  
94 - colList.add(cells[i].getContents().trim());  
95 - } else {  
96 - colList.add(cells[i].getContents() + i);  
97 - }  
98 - }  
99 -  
100 - File fileCal = new File(filename + "_stringType.xls");  
101 - WritableWorkbook writableWorkbook = Workbook.createWorkbook(fileCal, workbook);  
102 - WritableSheet sheet1 = writableWorkbook.getSheet(sheetname);  
103 - for (int i = 0; i < sheet1.getColumns(); i++) { // 第一行数据  
104 - sheet1.addCell(new Label(i, 0, colList.get(i)));  
105 - }  
106 - for (int i = 1; i < sheet1.getRows(); i++) { // 第二行开始  
107 - Cell[] cells1 = sheet.getRow(i);  
108 - for (int j = 0; j < cells1.length; j++) {  
109 - sheet1.addCell(new Label(j, i, cells1[j].getContents()));  
110 - }  
111 - }  
112 - writableWorkbook.write();  
113 - writableWorkbook.close();  
114 -  
115 - // 2、删除原有数据  
116 - // 操作在ktr内部执行  
117 -  
118 - // 3、导入时刻表  
119 - // 获取停车场名字  
120 - LOGGER.info("获取停车场名字...");  
121 - LineInformation lineInformation = lineInformationService.findById(lineid);  
122 - Map<String, Object> p1 = new HashMap<>();  
123 - p1.put("parkCode_eq", lineInformation.getCarPark());  
124 - List<CarPark> carParkList = (List<CarPark>) carParkService.list(p1);  
125 - String tccname = carParkList.get(0).getParkName();  
126 - LOGGER.info("停车场名字={}", tccname);  
127 -  
128 -  
129 - // 计算表头参数  
130 - Workbook book = Workbook.getWorkbook(fileCal);  
131 - Sheet sheet_exp = book.getSheet(sheetname);  
132 - List<String> columnames = new ArrayList<>();  
133 - for (int i = 0; i < sheet_exp.getColumns(); i++) { // 获取第一行,数据,作为列名  
134 - columnames.add(sheet_exp.getCell(i, 0).getContents());  
135 - }  
136 - LOGGER.info("表头={}", StringUtils.join(columnames.toArray(), ","));  
137 -  
138 - // 创建ktr转换所需参数  
139 - Map<String, Object> ktrParms = new HashMap<>();  
140 - File ktrFile = new File(this.getClass().getResource(  
141 - dataToolsProperties.getTtinfodetailMetadatainputktr()).toURI());  
142 - File ktrFile2 = new File(this.getClass().getResource(  
143 - dataToolsProperties.getTtinfodetailDatainputktr()).toURI());  
144 -  
145 - // 通用参数,转换文件路径,excel输入文件路径,错误输出文件路径  
146 - ktrParms.put("transpath", ktrFile.getAbsolutePath());  
147 - ktrParms.put("filepath", fileCal.getAbsolutePath());  
148 - ktrParms.put("erroroutputdir", dataToolsProperties.getTransErrordir());  
149 -  
150 - // 附加参数  
151 - ktrParms.put("injectktrfile", ktrFile2.getAbsolutePath()); // 注入元数据的ktr文件  
152 - ktrParms.put("sheetname", sheetname); // sheet工作区的名字  
153 - ktrParms.put("xlname", xlname); // 线路名称  
154 - ktrParms.put("ttinfoname", ttname); // 时刻表名称  
155 - ktrParms.put("ttid", ttid.intValue()); // 时刻表id  
156 - ktrParms.put("tccname", tccname); // 停车场名字  
157 - ktrParms.put("excelfieldnames", StringUtils.join(columnames.toArray(), ",")); // 时刻表excel输入字段名,以逗号连接  
158 - columnames.remove(0);  
159 - ktrParms.put("normalizefieldnames", StringUtils.join(columnames.toArray(), ",")); // 数据范式化字段名,以逗号连接  
160 -  
161 - super.importData(fileCal, ktrParms);  
162 -  
163 - LOGGER.info("//---------------- 导入时刻表明细 success... ----------------//");  
164 - } catch (Exception exp) {  
165 - LOGGER.info("//---------------- 导入时刻表明细 failed... ----------------//");  
166 -  
167 - StringWriter sw = new StringWriter();  
168 - exp.printStackTrace(new PrintWriter(sw));  
169 - LOGGER.info(sw.toString());  
170 -  
171 - throw new ScheduleException(exp.getMessage());  
172 - }  
173 - }  
174 -  
175 - @Override  
176 - public File exportData(Map<String, Object> params) throws ScheduleException {  
177 - try {  
178 - LOGGER.info("//---------------- 导出时刻表明细 start... ----------------//");  
179 -  
180 - // 创建ktr转换所需参数  
181 - Map<String, Object> ktrParms = new HashMap<>();  
182 - File ktrFile = new File(this.getClass().getResource(  
183 - dataToolsProperties.getTtinfodetailMetaoutput()).toURI());  
184 - File ktrFile2 = new File(this.getClass().getResource(  
185 - dataToolsProperties.getTtinfodetailOutput()).toURI());  
186 -  
187 - // 通用参数,转换文件路径,excel输出文件名  
188 - ktrParms.put("transpath", ktrFile.getAbsolutePath());  
189 - ktrParms.put("filename", String.format("时刻表_(id=%s)_download-", String.valueOf(params.get("ttinfoid"))));  
190 -  
191 - // 附加参数  
192 - ktrParms.put("injectktrfile", ktrFile2.getAbsolutePath()); // 注入元数据的ktr文件  
193 - ktrParms.put("ttinfoid", String.valueOf(params.get("ttinfoid")));  
194 -  
195 - File file = super.exportData(ktrParms);  
196 -  
197 - LOGGER.info("//---------------- 导出时刻表明细 success... ----------------//");  
198 -  
199 - return file;  
200 - } catch (Exception exp) {  
201 - LOGGER.info("//---------------- 导出时刻表明细 failed... ----------------//");  
202 -  
203 - StringWriter sw = new StringWriter();  
204 - exp.printStackTrace(new PrintWriter(sw));  
205 - LOGGER.info(sw.toString());  
206 -  
207 - throw new ScheduleException(exp.getMessage());  
208 - }  
209 - }  
210 -  
211 - @Override  
212 - public EditInfo getEditInfo(Integer xlid, Long ttid) throws ScheduleException {  
213 - try {  
214 - LOGGER.info("//---------------- 时刻表编辑用数据输出 start... ----------------//");  
215 -  
216 - // 创建ktr转换所需参数  
217 - Map<String, Object> ktrParms = new HashMap<>();  
218 - File ktrFile = new File(this.getClass().getResource(  
219 - dataToolsProperties.getTtinfodetailForeditktr()).toURI());  
220 -  
221 - // 通用参数,转换文件路径,excel输出文件名,错误输出文件路径  
222 - ktrParms.put("transpath", ktrFile.getAbsolutePath());  
223 - ktrParms.put("filename", "todo");  
224 -  
225 - // 附加参数  
226 - String outputFilePath = String.format("ttinfodetail_(id=%s)_foredit-%s",  
227 - String.valueOf(ttid), new DateTime().toString("yyyyMMddHHmmss"));  
228 -  
229 - ktrParms.put("tempfilepath", dataToolsProperties.getTransTempdir() + File.separator + outputFilePath); // 数据输出文件路径  
230 - ktrParms.put("xlid", String.valueOf(xlid));  
231 - ktrParms.put("ttid", String.valueOf(ttid));  
232 -  
233 - super.exportData(ktrParms);  
234 -  
235 - // 1.6、获取最大的发车数,用于输出数据的数量  
236 - Long maxfcno = ttInfoDetailRepository.findMaxFcno(xlid, ttid);  
237 - if (maxfcno == null)  
238 - return new EditInfo();  
239 -  
240 - // 2、读取ktr生成的excel数据,组织编辑用数据返回  
241 - // 2-1、读取Excel文件  
242 - Workbook book = Workbook.getWorkbook(new File(dataToolsProperties.getTransTempdir() +  
243 - File.separator + outputFilePath + ".xls"));  
244 - Sheet sheet = book.getSheet(0);  
245 - EditInfo editInfo = new EditInfo();  
246 - // 2-2、处理数据  
247 - int all_bc = 0; // 总班次  
248 - double all_lc_ks = 0; // 总空驶里程  
249 - double all_lc_yy = 0; // 总营运里程  
250 -  
251 - String[] headarrays = new String[maxfcno.intValue() + 3];  
252 - headarrays[0] = "路牌";  
253 - headarrays[maxfcno.intValue() + 1] = "空驶班次/空驶里程";  
254 - headarrays[maxfcno.intValue() + 2] = "运营班次/运营里程";  
255 -  
256 - for (int r = 1; r < sheet.getRows(); r++) {  
257 - List<FcInfo> fcInfos = new ArrayList<>();  
258 - // 每行第一列都是路牌  
259 - fcInfos.add(new FcInfo(null, null, sheet.getCell(0, r).getContents(), null, null)); // 用fcsj放置路牌显示  
260 -  
261 - int bc_ks = 0; // 空驶班次  
262 - int bc_yy = 0; // 营运班次  
263 - double lc_ks = 0; // 空驶里程  
264 - double lc_yy = 0; // 营运里程  
265 -  
266 - for (int c = 1; c <= maxfcno * 7; ) {  
267 - String ttdid_str = sheet.getCell(c, r).getContents(); // 时刻表明细id  
268 - String fcsj = sheet.getCell(c + 1, r).getContents(); // 发车时间  
269 - String jhlc = sheet.getCell(c + 2, r).getContents(); // 计划里程  
270 - String fzdname = sheet.getCell(c + 3, r).getContents(); // 发车站点名称  
271 - String bctype = sheet.getCell(c + 4, r).getContents(); // 班次类型  
272 - String xldir = sheet.getCell(c + 5, r).getContents(); // 线路上下行  
273 - String isfb = sheet.getCell(c + 6, r).getContents(); // 是否分班  
274 -  
275 - FcInfo fcInfo = new FcInfo(ttdid_str, bctype, fcsj, xldir, isfb);  
276 -  
277 - if (StringUtils.isNotEmpty(fzdname))  
278 - headarrays[(int)(c / 7) + 1] = fzdname;  
279 - fcInfos.add(fcInfo);  
280 -  
281 - c += 7;  
282 -  
283 - // 计算班次里程  
284 - if (StringUtils.isNotEmpty(jhlc)) {  
285 - if ("in".equals(bctype) || "out".equals(bctype)) {  
286 - bc_ks += 1;  
287 - lc_ks += Double.valueOf(jhlc);  
288 -  
289 - all_bc += 1;  
290 - all_lc_ks += Double.valueOf(jhlc);  
291 -  
292 - } else {  
293 - bc_yy += 1;  
294 - lc_yy += Double.valueOf(jhlc);  
295 -  
296 - all_bc += 1;  
297 - all_lc_yy += Double.valueOf(jhlc);  
298 - }  
299 - }  
300 -  
301 - }  
302 -  
303 - // 添加一列 空驶班次/空驶里程,fcsj放置数据  
304 - fcInfos.add(new FcInfo(null, null, String.format("%d/%.2f", bc_ks, lc_ks), null, null));  
305 -  
306 - // 添加一列 营运班次/营运里程,fcsj放置数据  
307 - fcInfos.add(new FcInfo(null, null, String.format("%d/%.2f", bc_yy, lc_yy), null, null));  
308 -  
309 - editInfo.getContents().add(fcInfos);  
310 - }  
311 - editInfo.getHeader().addAll(Arrays.asList(headarrays));  
312 -  
313 - editInfo.setYy_desc(String.format("班次=%d,空驶里程=%.2f,营运里程=%.2f", all_bc, all_lc_ks, all_lc_yy));  
314 -  
315 - LOGGER.info("//---------------- 时刻表编辑用数据输出 success... ----------------//");  
316 -  
317 - return editInfo;  
318 - } catch (Exception exp) {  
319 - LOGGER.info("//---------------- 时刻表编辑用数据输出 failed... ----------------//");  
320 -  
321 - StringWriter sw = new StringWriter();  
322 - exp.printStackTrace(new PrintWriter(sw));  
323 - LOGGER.info(sw.toString());  
324 -  
325 - throw new ScheduleException(exp.getMessage());  
326 - }  
327 - }  
328 -  
329 -  
330 -  
331 - @Override  
332 - public void validateExcelSheet(String filename, String sheetname, Integer lineid, String linename) throws ScheduleException {  
333 - try {  
334 - Workbook book = Workbook.getWorkbook(new File(filename));  
335 - Sheet sheet = book.getSheet(sheetname);  
336 - if (sheet.getRows() == 0 || sheet.getColumns() == 0) { // 工作区是否为空  
337 - throw new Exception(String.format("%s 工作区没有数据!", sheetname));  
338 - } else {  
339 - if (sheet.getRows() <= 1 || sheet.getColumns() <= 1) {  
340 - throw new Exception(String.format("工作区至少包含2行2列的数据"));  
341 - } else {  
342 - Cell[] cells = sheet.getRow(0); // 获取第一行数据列  
343 - for (int i = 0; i < cells.length; i++) {  
344 - String cell_con = cells[i].getContents();  
345 -  
346 - if (StringUtils.isEmpty(cell_con)) {  
347 - throw new Exception(String.format("第1行,第%d列数据不能为空", i + 1));  
348 - } else {  
349 - // 正则表达式去除数字  
350 - cell_con = cell_con.replaceAll("[\\d+]", "");  
351 -  
352 - if (i == 0) { // 第一列必须是路牌2个字  
353 - if (!"路牌".equals(cell_con.trim())) {  
354 - throw new Exception("第1行,第1列数据必须是路牌2个字");  
355 - }  
356 - } else { // 排除出场,进场,其余内容到站点路由里查询,以各个方向的起点站为查询依据  
357 - if ((!"出场".equals(cell_con.trim())) &&  
358 - (!"进场".equals(cell_con.trim()))) {  
359 - Map<String, Object> p1 = new HashMap<>();  
360 - p1.put("line.id_eq", lineid);  
361 - p1.put("stationName_eq", cell_con.trim());  
362 - p1.put("stationMark_eq", "B");  
363 -  
364 -  
365 - // TODO:这里要修改(起点站有启用撤销的标志的)  
366 -  
367 - List<StationRoute> stationRouteList = (List<StationRoute>) stationRouteService.list(p1);  
368 - if (CollectionUtils.isEmpty(stationRouteList)) {  
369 - throw new Exception(String.format("第1行,第%d列数据%s在%s站点路由中不是起点站", i + 1, cell_con.trim(), linename));  
370 - } else if (stationRouteList.size() > 1) {  
371 - throw new Exception(String.format("第1行,第%d列数据%s在%s站点路由中上下行都是起点站", i + 1, cell_con.trim(), linename));  
372 - }  
373 - }  
374 -  
375 - }  
376 - }  
377 - }  
378 -  
379 - // 验证路牌内容  
380 - Map<String, Integer> gbindexmap = new HashMap<>(); // 记录每个路牌在第几行  
381 - for (int i = 1; i < sheet.getRows(); i++) { // 从第2行开始验证数据  
382 - Cell bcell = sheet.getRow(i)[0]; // 获取第1列  
383 - String bcell_con = bcell.getContents();  
384 - if (StringUtils.isEmpty(bcell_con)) {  
385 - throw new Exception(String.format("第%d行,第1列路牌无数据", i + 1));  
386 - } else if (gbindexmap.get(bcell_con.trim()) != null) {  
387 - throw new Exception(String.format("第%d行,第1列的路牌数据与第%d行,第1列数据重复",  
388 - i + 1,  
389 - gbindexmap.get(bcell_con.trim())));  
390 - } else {  
391 - Map<String, Object> p2 = new HashMap<>();  
392 - p2.put("xl.id_eq", lineid);  
393 - p2.put("lpName_eq", bcell_con.trim());  
394 - List<GuideboardInfo> guideboardInfoList = (List<GuideboardInfo>) guideboardInfoService.list(p2);  
395 - if (CollectionUtils.isEmpty(guideboardInfoList)) {  
396 - throw new Exception(String.format("第%d行,第1列的路牌在%s中不存在", i + 1, linename));  
397 - } else if (guideboardInfoList.size() > 1) {  
398 - throw new Exception(String.format("第%d行,第1列的路牌在%s中重复", i + 1, linename));  
399 - } else {  
400 - gbindexmap.put(bcell_con.trim(), i + 1);  
401 - }  
402 - }  
403 - }  
404 -  
405 - // 班次时间验证,正则表达式,格式hh:mm或者hhmm  
406 - String el = "^(([0-1]\\d)|(2[0-4])):[0-5]\\d$"; // hh:mm格式  
407 - String el2 = "^(([0-1]\\d)|(2[0-4]))[0-5]\\d$"; // hhmm格式  
408 - Pattern p = Pattern.compile(el);  
409 - Pattern p2 = Pattern.compile(el2);  
410 -  
411 - for (int i = 1; i < sheet.getRows(); i++) { // 从第2行开始验证数据  
412 - Cell[] bcells = sheet.getRow(i);  
413 - for (int j = 1; j < bcells.length; j++) { // 从第2列开始  
414 - String bcell_con = bcells[j].getContents();  
415 - if (StringUtils.isNotEmpty(bcell_con)) {  
416 - Matcher m = p.matcher(bcell_con.trim());  
417 - Matcher m2 = p2.matcher(bcell_con.trim());  
418 - if ((!m.matches()) && (!m2.matches())) {  
419 - throw new Exception(String.format("第%d行,第%d列的发车时间格式不正确,格式应为hh:mm或hhmm", i + 1, j + 1));  
420 - }  
421 - }  
422 - }  
423 - }  
424 - }  
425 -  
426 - }  
427 - } catch (Exception exp) {  
428 - throw new ScheduleException(exp.getMessage());  
429 - }  
430 -  
431 - }  
432 -  
433 - @Override  
434 - public void validateAssoLineInfo(Integer lineinfoid) throws ScheduleException {  
435 - LineInformation lineInformation = lineInformationService.findById(lineinfoid);  
436 - if (lineInformation.getUpInMileage() == null) {  
437 - throw new ScheduleException("上行进场里程为空");  
438 - } else if (lineInformation.getUpInTimer() == null) {  
439 - throw new ScheduleException("上行进场时间为空");  
440 - } else if (lineInformation.getUpOutMileage() == null) {  
441 - throw new ScheduleException("上行出场里程为空");  
442 - } else if (lineInformation.getUpOutTimer() == null) {  
443 - throw new ScheduleException("上行出场时间为空");  
444 - } else if (lineInformation.getUpMileage() == null) {  
445 - throw new ScheduleException("上行班次里程为空");  
446 - } else if (lineInformation.getUpTravelTime() == null) {  
447 - throw new ScheduleException("上行班次时间为空");  
448 - } else if (lineInformation.getDownInMileage() == null) {  
449 - throw new ScheduleException("下行进场里程为空");  
450 - } else if (lineInformation.getDownInTimer() == null) {  
451 - throw new ScheduleException("下行进场时间为空");  
452 - } else if (lineInformation.getDownOutMileage() == null) {  
453 - throw new ScheduleException("下行出场里程为空");  
454 - } else if (lineInformation.getDownOutTimer() == null) {  
455 - throw new ScheduleException("下行出场时间为空");  
456 - } else if (lineInformation.getDownMileage() == null) {  
457 - throw new ScheduleException("下行班次里程为空");  
458 - } else if (lineInformation.getDownTravelTime() == null) {  
459 - throw new ScheduleException("下行班次时间为空");  
460 - } else if (StringUtils.isEmpty(lineInformation.getCarPark())) {  
461 - throw new ScheduleException("停车场必须选择");  
462 - }  
463 -  
464 - // 单独验证停车场信息  
465 - String tcccode = lineInformation.getCarPark();  
466 - Map<String, Object> p1 = new HashMap<>();  
467 - p1.put("parkCode_eq", tcccode);  
468 - List<CarPark> carParkList = (List<CarPark>) carParkService.list(p1);  
469 - if (CollectionUtils.isEmpty(carParkList)) {  
470 - throw new ScheduleException(String.format("线路标准里的停车场code=%s,在停车场信息中未找到", tcccode));  
471 - } else if (carParkList.size() > 1) {  
472 - throw new ScheduleException(String.format("线路标准里的停车场code=%s,在停车场信息中有重复数据", tcccode));  
473 - } else {  
474 - CarPark carPark = carParkList.get(0);  
475 - if (StringUtils.isEmpty(carPark.getParkName())) {  
476 - throw new ScheduleException(String.format("线路标准里的停车场code=%s,在停车场信息中没有停车场名字", tcccode));  
477 - }  
478 - }  
479 -  
480 - }  
481 -  
482 - @Override  
483 - public List<TTInfoDetail> findBcdetails(Integer xlId, Long ttinfoId, Long lpId) {  
484 - return ttInfoDetailRepository.findBcdetails(xlId, ttinfoId, lpId);  
485 - }  
486 -} 1 +package com.bsth.service.schedule.impl;
  2 +
  3 +import com.bsth.entity.CarPark;
  4 +import com.bsth.entity.LineInformation;
  5 +import com.bsth.entity.StationRoute;
  6 +import com.bsth.entity.schedule.GuideboardInfo;
  7 +import com.bsth.entity.schedule.TTInfoDetail;
  8 +import com.bsth.repository.schedule.TTInfoDetailRepository;
  9 +import com.bsth.service.CarParkService;
  10 +import com.bsth.service.LineInformationService;
  11 +import com.bsth.service.StationRouteService;
  12 +import com.bsth.service.schedule.GuideboardInfoService;
  13 +import com.bsth.service.schedule.TTInfoDetailService;
  14 +import com.bsth.service.schedule.exception.ScheduleException;
  15 +import com.bsth.service.schedule.utils.DataToolsProperties;
  16 +import jxl.Cell;
  17 +import jxl.Sheet;
  18 +import jxl.Workbook;
  19 +import jxl.write.Label;
  20 +import jxl.write.WritableSheet;
  21 +import jxl.write.WritableWorkbook;
  22 +import org.apache.commons.lang3.StringUtils;
  23 +import org.joda.time.DateTime;
  24 +import org.slf4j.Logger;
  25 +import org.slf4j.LoggerFactory;
  26 +import org.springframework.beans.factory.annotation.Autowired;
  27 +import org.springframework.boot.context.properties.EnableConfigurationProperties;
  28 +import org.springframework.stereotype.Service;
  29 +import org.springframework.util.CollectionUtils;
  30 +
  31 +import java.io.File;
  32 +import java.io.PrintWriter;
  33 +import java.io.StringWriter;
  34 +import java.util.*;
  35 +import java.util.regex.Matcher;
  36 +import java.util.regex.Pattern;
  37 +
  38 +/**
  39 + * Created by xu on 17/1/3.
  40 + */
  41 +@Service
  42 +@EnableConfigurationProperties(DataToolsProperties.class)
  43 +public class TTInfoDetailServiceImpl extends BServiceImpl<TTInfoDetail, Long> implements TTInfoDetailService {
  44 + /** 日志记录器 */
  45 + private static final Logger LOGGER = LoggerFactory.getLogger(TTInfoDetailServiceImpl.class);
  46 +
  47 + @Autowired
  48 + private GuideboardInfoService guideboardInfoService;
  49 + @Autowired
  50 + private StationRouteService stationRouteService;
  51 + @Autowired
  52 + private LineInformationService lineInformationService;
  53 + @Autowired
  54 + private CarParkService carParkService;
  55 + @Autowired
  56 + private TTInfoDetailRepository ttInfoDetailRepository;
  57 + @Autowired
  58 + private DataToolsProperties dataToolsProperties;
  59 +
  60 + @Override
  61 + public TTInfoDetail findById(Long aLong) {
  62 + return ttInfoDetailRepository.findOneExtend(aLong);
  63 + }
  64 +
  65 + @Override
  66 + public void importData(
  67 + File file,
  68 + Map<String, Object> params) throws ScheduleException {
  69 +
  70 + try {
  71 + LOGGER.info("//---------------- 导入时刻表明细 start... ----------------//");
  72 +
  73 + String filename = file.getAbsolutePath(); // xls文件名
  74 + String sheetname = String.valueOf(params.get("sheetname")); // sheet名字
  75 + Long ttid = Long.valueOf(String.valueOf(params.get("ttid"))); // 时刻表id
  76 + Long xlid = Long.valueOf(String.valueOf(params.get("xlid"))); // 线路id
  77 + Integer lineid = Integer.valueOf(String.valueOf(params.get("lineinfo"))); // 线路标准id
  78 + String xlname = String.valueOf(params.get("xlname")); // 线路名字
  79 + String ttname = String.valueOf(params.get("ttname")); // 时刻表名字
  80 +
  81 + LOGGER.info("参数1, xls文件名={},sheet名字={}", filename, sheetname);
  82 + LOGGER.info("参数2, 线路id={},线路名字={}", xlid, xlname);
  83 + LOGGER.info("参数3, 时刻表id={},时刻表名字={}", ttid, ttname);
  84 +
  85 + LOGGER.info("转换xls文件格式成文本格式...");
  86 + // 1、修改已经上传的excel文件,在每个起点站后标示数字,表示第几个班次
  87 + // 2、由于格式问题,需要把内容都转换成字符串
  88 + List<String> colList = new ArrayList<>();
  89 + Workbook workbook = Workbook.getWorkbook(new File(filename));
  90 + Sheet sheet = workbook.getSheet(sheetname);
  91 + Cell[] cells = sheet.getRow(0);
  92 + for (int i = 0; i < cells.length; i++) {
  93 + if (i == 0) {
  94 + colList.add(cells[i].getContents().trim());
  95 + } else {
  96 + colList.add(cells[i].getContents() + i);
  97 + }
  98 + }
  99 +
  100 + File fileCal = new File(filename + "_stringType.xls");
  101 + WritableWorkbook writableWorkbook = Workbook.createWorkbook(fileCal, workbook);
  102 + WritableSheet sheet1 = writableWorkbook.getSheet(sheetname);
  103 + for (int i = 0; i < sheet1.getColumns(); i++) { // 第一行数据
  104 + sheet1.addCell(new Label(i, 0, colList.get(i)));
  105 + }
  106 + for (int i = 1; i < sheet1.getRows(); i++) { // 第二行开始
  107 + Cell[] cells1 = sheet.getRow(i);
  108 + for (int j = 0; j < cells1.length; j++) {
  109 + sheet1.addCell(new Label(j, i, cells1[j].getContents()));
  110 + }
  111 + }
  112 + writableWorkbook.write();
  113 + writableWorkbook.close();
  114 +
  115 + // 2、删除原有数据
  116 + // 操作在ktr内部执行
  117 +
  118 + // 3、导入时刻表
  119 + // 获取停车场名字
  120 + LOGGER.info("获取停车场名字...");
  121 + LineInformation lineInformation = lineInformationService.findById(lineid);
  122 + Map<String, Object> p1 = new HashMap<>();
  123 + p1.put("parkCode_eq", lineInformation.getCarPark());
  124 + List<CarPark> carParkList = (List<CarPark>) carParkService.list(p1);
  125 + String tccname = carParkList.get(0).getParkName();
  126 + LOGGER.info("停车场名字={}", tccname);
  127 +
  128 +
  129 + // 计算表头参数
  130 + Workbook book = Workbook.getWorkbook(fileCal);
  131 + Sheet sheet_exp = book.getSheet(sheetname);
  132 + List<String> columnames = new ArrayList<>();
  133 + for (int i = 0; i < sheet_exp.getColumns(); i++) { // 获取第一行,数据,作为列名
  134 + columnames.add(sheet_exp.getCell(i, 0).getContents());
  135 + }
  136 + LOGGER.info("表头={}", StringUtils.join(columnames.toArray(), ","));
  137 +
  138 + // 创建ktr转换所需参数
  139 + Map<String, Object> ktrParms = new HashMap<>();
  140 + File ktrFile = new File(this.getClass().getResource(
  141 + dataToolsProperties.getTtinfodetailMetadatainputktr()).toURI());
  142 + File ktrFile2 = new File(this.getClass().getResource(
  143 + dataToolsProperties.getTtinfodetailDatainputktr()).toURI());
  144 +
  145 + // 通用参数,转换文件路径,excel输入文件路径,错误输出文件路径
  146 + ktrParms.put("transpath", ktrFile.getAbsolutePath());
  147 + ktrParms.put("filepath", fileCal.getAbsolutePath());
  148 + ktrParms.put("erroroutputdir", dataToolsProperties.getTransErrordir());
  149 +
  150 + // 附加参数
  151 + ktrParms.put("injectktrfile", ktrFile2.getAbsolutePath()); // 注入元数据的ktr文件
  152 + ktrParms.put("sheetname", sheetname); // sheet工作区的名字
  153 + ktrParms.put("xlname", xlname); // 线路名称
  154 + ktrParms.put("ttinfoname", ttname); // 时刻表名称
  155 + ktrParms.put("ttid", ttid.intValue()); // 时刻表id
  156 + ktrParms.put("tccname", tccname); // 停车场名字
  157 + ktrParms.put("excelfieldnames", StringUtils.join(columnames.toArray(), ",")); // 时刻表excel输入字段名,以逗号连接
  158 + columnames.remove(0);
  159 + ktrParms.put("normalizefieldnames", StringUtils.join(columnames.toArray(), ",")); // 数据范式化字段名,以逗号连接
  160 +
  161 + super.importData(fileCal, ktrParms);
  162 +
  163 + LOGGER.info("//---------------- 导入时刻表明细 success... ----------------//");
  164 + } catch (Exception exp) {
  165 + LOGGER.info("//---------------- 导入时刻表明细 failed... ----------------//");
  166 +
  167 + StringWriter sw = new StringWriter();
  168 + exp.printStackTrace(new PrintWriter(sw));
  169 + LOGGER.info(sw.toString());
  170 +
  171 + throw new ScheduleException(exp.getMessage());
  172 + }
  173 + }
  174 +
  175 + @Override
  176 + public File exportData(Map<String, Object> params) throws ScheduleException {
  177 + try {
  178 + LOGGER.info("//---------------- 导出时刻表明细 start... ----------------//");
  179 +
  180 + // 创建ktr转换所需参数
  181 + Map<String, Object> ktrParms = new HashMap<>();
  182 + File ktrFile = new File(this.getClass().getResource(
  183 + dataToolsProperties.getTtinfodetailMetaoutput()).toURI());
  184 + File ktrFile2 = new File(this.getClass().getResource(
  185 + dataToolsProperties.getTtinfodetailOutput()).toURI());
  186 +
  187 + // 通用参数,转换文件路径,excel输出文件名
  188 + ktrParms.put("transpath", ktrFile.getAbsolutePath());
  189 + ktrParms.put("filename", String.format("时刻表_(id=%s)_download-", String.valueOf(params.get("ttinfoid"))));
  190 +
  191 + // 附加参数
  192 + ktrParms.put("injectktrfile", ktrFile2.getAbsolutePath()); // 注入元数据的ktr文件
  193 + ktrParms.put("ttinfoid", String.valueOf(params.get("ttinfoid")));
  194 +
  195 + File file = super.exportData(ktrParms);
  196 +
  197 + LOGGER.info("//---------------- 导出时刻表明细 success... ----------------//");
  198 +
  199 + return file;
  200 + } catch (Exception exp) {
  201 + LOGGER.info("//---------------- 导出时刻表明细 failed... ----------------//");
  202 +
  203 + StringWriter sw = new StringWriter();
  204 + exp.printStackTrace(new PrintWriter(sw));
  205 + LOGGER.info(sw.toString());
  206 +
  207 + throw new ScheduleException(exp.getMessage());
  208 + }
  209 + }
  210 +
  211 + @Override
  212 + public EditInfo getEditInfo(Integer xlid, Long ttid) throws ScheduleException {
  213 + try {
  214 + LOGGER.info("//---------------- 时刻表编辑用数据输出 start... ----------------//");
  215 +
  216 + // 创建ktr转换所需参数
  217 + Map<String, Object> ktrParms = new HashMap<>();
  218 + File ktrFile = new File(this.getClass().getResource(
  219 + dataToolsProperties.getTtinfodetailForeditktr()).toURI());
  220 +
  221 + // 通用参数,转换文件路径,excel输出文件名,错误输出文件路径
  222 + ktrParms.put("transpath", ktrFile.getAbsolutePath());
  223 + ktrParms.put("filename", "todo");
  224 +
  225 + // 附加参数
  226 + String outputFilePath = String.format("ttinfodetail_(id=%s)_foredit-%s",
  227 + String.valueOf(ttid), new DateTime().toString("yyyyMMddHHmmss"));
  228 +
  229 + ktrParms.put("tempfilepath", dataToolsProperties.getTransTempdir() + File.separator + outputFilePath); // 数据输出文件路径
  230 + ktrParms.put("xlid", String.valueOf(xlid));
  231 + ktrParms.put("ttid", String.valueOf(ttid));
  232 +
  233 + super.exportData(ktrParms);
  234 +
  235 + // 1.6、获取最大的发车数,用于输出数据的数量
  236 + Long maxfcno = ttInfoDetailRepository.findMaxFcno(xlid, ttid);
  237 + if (maxfcno == null)
  238 + return new EditInfo();
  239 +
  240 + // 2、读取ktr生成的excel数据,组织编辑用数据返回
  241 + // 2-1、读取Excel文件
  242 + Workbook book = Workbook.getWorkbook(new File(dataToolsProperties.getTransTempdir() +
  243 + File.separator + outputFilePath + ".xls"));
  244 + Sheet sheet = book.getSheet(0);
  245 + EditInfo editInfo = new EditInfo();
  246 + // 2-2、处理数据
  247 + int all_bc = 0; // 总班次
  248 + double all_lc_ks = 0; // 总空驶里程
  249 + double all_lc_yy = 0; // 总营运里程
  250 +
  251 + String[] headarrays = new String[maxfcno.intValue() + 3];
  252 + headarrays[0] = "路牌";
  253 + headarrays[maxfcno.intValue() + 1] = "空驶班次/空驶里程";
  254 + headarrays[maxfcno.intValue() + 2] = "运营班次/运营里程";
  255 +
  256 + for (int r = 1; r < sheet.getRows(); r++) {
  257 + List<FcInfo> fcInfos = new ArrayList<>();
  258 + // 每行第一列都是路牌
  259 + fcInfos.add(new FcInfo(null, null, sheet.getCell(0, r).getContents(), null, null)); // 用fcsj放置路牌显示
  260 +
  261 + int bc_ks = 0; // 空驶班次
  262 + int bc_yy = 0; // 营运班次
  263 + double lc_ks = 0; // 空驶里程
  264 + double lc_yy = 0; // 营运里程
  265 +
  266 + for (int c = 1; c <= maxfcno * 7; ) {
  267 + String ttdid_str = sheet.getCell(c, r).getContents(); // 时刻表明细id
  268 + String fcsj = sheet.getCell(c + 1, r).getContents(); // 发车时间
  269 + String jhlc = sheet.getCell(c + 2, r).getContents(); // 计划里程
  270 + String fzdname = sheet.getCell(c + 3, r).getContents(); // 发车站点名称
  271 + String bctype = sheet.getCell(c + 4, r).getContents(); // 班次类型
  272 + String xldir = sheet.getCell(c + 5, r).getContents(); // 线路上下行
  273 + String isfb = sheet.getCell(c + 6, r).getContents(); // 是否分班
  274 +
  275 + FcInfo fcInfo = new FcInfo(ttdid_str, bctype, fcsj, xldir, isfb);
  276 +
  277 + if (StringUtils.isNotEmpty(fzdname))
  278 + headarrays[(int)(c / 7) + 1] = fzdname;
  279 + fcInfos.add(fcInfo);
  280 +
  281 + c += 7;
  282 +
  283 + // 计算班次里程
  284 + if (StringUtils.isNotEmpty(jhlc)) {
  285 + if ("in".equals(bctype) || "out".equals(bctype)) {
  286 + bc_ks += 1;
  287 + lc_ks += Double.valueOf(jhlc);
  288 +
  289 + all_bc += 1;
  290 + all_lc_ks += Double.valueOf(jhlc);
  291 +
  292 + } else {
  293 + bc_yy += 1;
  294 + lc_yy += Double.valueOf(jhlc);
  295 +
  296 + all_bc += 1;
  297 + all_lc_yy += Double.valueOf(jhlc);
  298 + }
  299 + }
  300 +
  301 + }
  302 +
  303 + // 添加一列 空驶班次/空驶里程,fcsj放置数据
  304 + fcInfos.add(new FcInfo(null, null, String.format("%d/%.2f", bc_ks, lc_ks), null, null));
  305 +
  306 + // 添加一列 营运班次/营运里程,fcsj放置数据
  307 + fcInfos.add(new FcInfo(null, null, String.format("%d/%.2f", bc_yy, lc_yy), null, null));
  308 +
  309 + editInfo.getContents().add(fcInfos);
  310 + }
  311 + editInfo.getHeader().addAll(Arrays.asList(headarrays));
  312 +
  313 + editInfo.setYy_desc(String.format("班次=%d,空驶里程=%.2f,营运里程=%.2f", all_bc, all_lc_ks, all_lc_yy));
  314 +
  315 + LOGGER.info("//---------------- 时刻表编辑用数据输出 success... ----------------//");
  316 +
  317 + return editInfo;
  318 + } catch (Exception exp) {
  319 + LOGGER.info("//---------------- 时刻表编辑用数据输出 failed... ----------------//");
  320 +
  321 + StringWriter sw = new StringWriter();
  322 + exp.printStackTrace(new PrintWriter(sw));
  323 + LOGGER.info(sw.toString());
  324 +
  325 + throw new ScheduleException(exp.getMessage());
  326 + }
  327 + }
  328 +
  329 +
  330 +
  331 + @Override
  332 + public void validateExcelSheet(String filename, String sheetname, Integer lineid, String linename) throws ScheduleException {
  333 + try {
  334 + Workbook book = Workbook.getWorkbook(new File(filename));
  335 + Sheet sheet = book.getSheet(sheetname);
  336 + if (sheet.getRows() == 0 || sheet.getColumns() == 0) { // 工作区是否为空
  337 + throw new Exception(String.format("%s 工作区没有数据!", sheetname));
  338 + } else {
  339 + if (sheet.getRows() <= 1 || sheet.getColumns() <= 1) {
  340 + throw new Exception(String.format("工作区至少包含2行2列的数据"));
  341 + } else {
  342 + Cell[] cells = sheet.getRow(0); // 获取第一行数据列
  343 + for (int i = 0; i < cells.length; i++) {
  344 + String cell_con = cells[i].getContents();
  345 +
  346 + if (StringUtils.isEmpty(cell_con)) {
  347 + throw new Exception(String.format("第1行,第%d列数据不能为空", i + 1));
  348 + } else {
  349 + // 正则表达式去除数字
  350 + cell_con = cell_con.replaceAll("[\\d+]", "");
  351 +
  352 + if (i == 0) { // 第一列必须是路牌2个字
  353 + if (!"路牌".equals(cell_con.trim())) {
  354 + throw new Exception("第1行,第1列数据必须是路牌2个字");
  355 + }
  356 + } else { // 排除出场,进场,其余内容到站点路由里查询,以各个方向的起点站为查询依据
  357 + if ((!"出场".equals(cell_con.trim())) &&
  358 + (!"进场".equals(cell_con.trim()))) {
  359 + Map<String, Object> p1 = new HashMap<>();
  360 + p1.put("line.id_eq", lineid);
  361 + p1.put("stationName_eq", cell_con.trim());
  362 + p1.put("stationMark_eq", "B");
  363 +
  364 +
  365 + // TODO:这里要修改(起点站有启用撤销的标志的)
  366 +
  367 + List<StationRoute> stationRouteList = (List<StationRoute>) stationRouteService.list(p1);
  368 + if (CollectionUtils.isEmpty(stationRouteList)) {
  369 + throw new Exception(String.format("第1行,第%d列数据%s在%s站点路由中不是起点站", i + 1, cell_con.trim(), linename));
  370 + } else if (stationRouteList.size() > 1) {
  371 + throw new Exception(String.format("第1行,第%d列数据%s在%s站点路由中上下行都是起点站", i + 1, cell_con.trim(), linename));
  372 + }
  373 + }
  374 +
  375 + }
  376 + }
  377 + }
  378 +
  379 + // 验证路牌内容
  380 + Map<String, Integer> gbindexmap = new HashMap<>(); // 记录每个路牌在第几行
  381 + for (int i = 1; i < sheet.getRows(); i++) { // 从第2行开始验证数据
  382 + Cell bcell = sheet.getRow(i)[0]; // 获取第1列
  383 + String bcell_con = bcell.getContents();
  384 + if (StringUtils.isEmpty(bcell_con)) {
  385 + throw new Exception(String.format("第%d行,第1列路牌无数据", i + 1));
  386 + } else if (gbindexmap.get(bcell_con.trim()) != null) {
  387 + throw new Exception(String.format("第%d行,第1列的路牌数据与第%d行,第1列数据重复",
  388 + i + 1,
  389 + gbindexmap.get(bcell_con.trim())));
  390 + } else {
  391 + Map<String, Object> p2 = new HashMap<>();
  392 + p2.put("xl.id_eq", lineid);
  393 + p2.put("lpName_eq", bcell_con.trim());
  394 + List<GuideboardInfo> guideboardInfoList = (List<GuideboardInfo>) guideboardInfoService.list(p2);
  395 + if (CollectionUtils.isEmpty(guideboardInfoList)) {
  396 + throw new Exception(String.format("第%d行,第1列的路牌在%s中不存在", i + 1, linename));
  397 + } else if (guideboardInfoList.size() > 1) {
  398 + throw new Exception(String.format("第%d行,第1列的路牌在%s中重复", i + 1, linename));
  399 + } else {
  400 + gbindexmap.put(bcell_con.trim(), i + 1);
  401 + }
  402 + }
  403 + }
  404 +
  405 + // 班次时间验证,正则表达式,格式hh:mm或者hhmm
  406 + String el = "^(([0-1]\\d)|(2[0-4])):[0-5]\\d$"; // hh:mm格式
  407 + String el2 = "^(([0-1]\\d)|(2[0-4]))[0-5]\\d$"; // hhmm格式
  408 + Pattern p = Pattern.compile(el);
  409 + Pattern p2 = Pattern.compile(el2);
  410 +
  411 + for (int i = 1; i < sheet.getRows(); i++) { // 从第2行开始验证数据
  412 + Cell[] bcells = sheet.getRow(i);
  413 + for (int j = 1; j < bcells.length; j++) { // 从第2列开始
  414 + String bcell_con = bcells[j].getContents();
  415 + if (StringUtils.isNotEmpty(bcell_con)) {
  416 + Matcher m = p.matcher(bcell_con.trim());
  417 + Matcher m2 = p2.matcher(bcell_con.trim());
  418 + if ((!m.matches()) && (!m2.matches())) {
  419 + throw new Exception(String.format("第%d行,第%d列的发车时间格式不正确,格式应为hh:mm或hhmm", i + 1, j + 1));
  420 + }
  421 + }
  422 + }
  423 + }
  424 + }
  425 +
  426 + }
  427 + } catch (Exception exp) {
  428 + throw new ScheduleException(exp.getMessage());
  429 + }
  430 +
  431 + }
  432 +
  433 + @Override
  434 + public void validateAssoLineInfo(Integer lineinfoid) throws ScheduleException {
  435 + LineInformation lineInformation = lineInformationService.findById(lineinfoid);
  436 + if (lineInformation.getUpInMileage() == null) {
  437 + throw new ScheduleException("上行进场里程为空");
  438 + } else if (lineInformation.getUpInTimer() == null) {
  439 + throw new ScheduleException("上行进场时间为空");
  440 + } else if (lineInformation.getUpOutMileage() == null) {
  441 + throw new ScheduleException("上行出场里程为空");
  442 + } else if (lineInformation.getUpOutTimer() == null) {
  443 + throw new ScheduleException("上行出场时间为空");
  444 + } else if (lineInformation.getUpMileage() == null) {
  445 + throw new ScheduleException("上行班次里程为空");
  446 + } else if (lineInformation.getUpTravelTime() == null) {
  447 + throw new ScheduleException("上行班次时间为空");
  448 + } else if (lineInformation.getDownInMileage() == null) {
  449 + throw new ScheduleException("下行进场里程为空");
  450 + } else if (lineInformation.getDownInTimer() == null) {
  451 + throw new ScheduleException("下行进场时间为空");
  452 + } else if (lineInformation.getDownOutMileage() == null) {
  453 + throw new ScheduleException("下行出场里程为空");
  454 + } else if (lineInformation.getDownOutTimer() == null) {
  455 + throw new ScheduleException("下行出场时间为空");
  456 + } else if (lineInformation.getDownMileage() == null) {
  457 + throw new ScheduleException("下行班次里程为空");
  458 + } else if (lineInformation.getDownTravelTime() == null) {
  459 + throw new ScheduleException("下行班次时间为空");
  460 + } else if (StringUtils.isEmpty(lineInformation.getCarPark())) {
  461 + throw new ScheduleException("停车场必须选择");
  462 + }
  463 +
  464 + // 单独验证停车场信息
  465 + String tcccode = lineInformation.getCarPark();
  466 + Map<String, Object> p1 = new HashMap<>();
  467 + p1.put("parkCode_eq", tcccode);
  468 + List<CarPark> carParkList = (List<CarPark>) carParkService.list(p1);
  469 + if (CollectionUtils.isEmpty(carParkList)) {
  470 + throw new ScheduleException(String.format("线路标准里的停车场code=%s,在停车场信息中未找到", tcccode));
  471 + } else if (carParkList.size() > 1) {
  472 + throw new ScheduleException(String.format("线路标准里的停车场code=%s,在停车场信息中有重复数据", tcccode));
  473 + } else {
  474 + CarPark carPark = carParkList.get(0);
  475 + if (StringUtils.isEmpty(carPark.getParkName())) {
  476 + throw new ScheduleException(String.format("线路标准里的停车场code=%s,在停车场信息中没有停车场名字", tcccode));
  477 + }
  478 + }
  479 +
  480 + }
  481 +
  482 + @Override
  483 + public List<TTInfoDetail> findBcdetails(Integer xlId, Long ttinfoId, Long lpId) {
  484 + return ttInfoDetailRepository.findBcdetails(xlId, ttinfoId, lpId);
  485 + }
  486 +}
src/main/java/com/bsth/service/schedule/utils/DataToolsService.java
1 -package com.bsth.service.schedule.utils;  
2 -  
3 -import com.bsth.service.schedule.exception.ScheduleException;  
4 -  
5 -import java.io.File;  
6 -import java.util.Map;  
7 -  
8 -/**  
9 - * 数据服务接口。  
10 - */  
11 -public interface DataToolsService {  
12 - //----------------- 数据服务操作 --------------//  
13 - // 上传文件  
14 - File uploadFile(String filename, byte[] filedata) throws ScheduleException;  
15 - // 导入数据  
16 - void importData(File file, Map<String, Object> params) throws ScheduleException;  
17 - // 导出数据  
18 - File exportData(Map<String, Object> params) throws ScheduleException;  
19 -} 1 +package com.bsth.service.schedule.utils;
  2 +
  3 +import com.bsth.service.schedule.exception.ScheduleException;
  4 +
  5 +import java.io.File;
  6 +import java.util.Map;
  7 +
  8 +/**
  9 + * 数据服务接口。
  10 + */
  11 +public interface DataToolsService {
  12 + //----------------- 数据服务操作 --------------//
  13 + // 上传文件
  14 + File uploadFile(String filename, byte[] filedata) throws ScheduleException;
  15 + // 导入数据
  16 + void importData(File file, Map<String, Object> params) throws ScheduleException;
  17 + // 导出数据
  18 + File exportData(Map<String, Object> params) throws ScheduleException;
  19 +}
src/main/java/com/bsth/service/schedule/utils/DataToolsServiceImpl.java
1 -package com.bsth.service.schedule.utils;  
2 -  
3 -import com.bsth.service.schedule.exception.ScheduleException;  
4 -import com.google.common.io.Files;  
5 -import org.apache.tika.Tika;  
6 -import org.joda.time.DateTime;  
7 -import org.pentaho.di.core.KettleEnvironment;  
8 -import org.pentaho.di.core.logging.KettleLogStore;  
9 -import org.pentaho.di.core.logging.LoggingBuffer;  
10 -import org.pentaho.di.core.logging.LoggingRegistry;  
11 -import org.pentaho.di.core.util.EnvUtil;  
12 -import org.pentaho.di.trans.Trans;  
13 -import org.pentaho.di.trans.TransMeta;  
14 -import org.slf4j.Logger;  
15 -import org.slf4j.LoggerFactory;  
16 -import org.springframework.beans.factory.InitializingBean;  
17 -import org.springframework.beans.factory.annotation.Autowired;  
18 -import org.springframework.boot.context.properties.EnableConfigurationProperties;  
19 -import org.springframework.stereotype.Service;  
20 -  
21 -import java.io.File;  
22 -import java.io.PrintWriter;  
23 -import java.io.StringWriter;  
24 -import java.util.HashMap;  
25 -import java.util.Map;  
26 -import java.util.Properties;  
27 -  
28 -/**  
29 - * Created by xu on 17/1/3.  
30 - */  
31 -@Service  
32 -@EnableConfigurationProperties(DataToolsProperties.class)  
33 -public class DataToolsServiceImpl implements DataToolsService, InitializingBean {  
34 - /** 日志记录器 */  
35 - private static final Logger LOGGER = LoggerFactory.getLogger(DataToolsServiceImpl.class);  
36 -  
37 - @Autowired  
38 - private DataToolsProperties dataToolsProperties;  
39 -  
40 - /**  
41 - * 自定义kettle环境初始化定义。  
42 - */  
43 - private void ktrEnvironmentInit() throws Exception {  
44 - // 由于kettle.properties可能没有(没有安装过kettle),  
45 - // 导致 EnvUtil.environmentInit() 报找不到kettle.properties文件  
46 - // 所以这里重写 EnvUtil.environmentInit() 方法  
47 -  
48 - if (Thread.currentThread().getContextClassLoader() == null) {  
49 - Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());  
50 - }  
51 -  
52 - // 获取配置文件  
53 - File file = new File(getClass().getResource(dataToolsProperties.getKettleProperties()).toURI());  
54 - Properties kettleProperties = EnvUtil.readProperties(file.getAbsolutePath());  
55 - EnvUtil.applyKettleProperties(kettleProperties);  
56 - System.getProperties().put("Internal.Cluster.Size", "1");  
57 - System.getProperties().put("Internal.Slave.Transformation.Number", "0");  
58 - System.getProperties().put("Internal.Slave.Server.Name", "slave-trans-name");  
59 - System.getProperties().put("Internal.Step.CopyNr", "0");  
60 - System.getProperties().put("Internal.Step.Name", "step-name");  
61 - System.getProperties().put("Internal.Step.Partition.ID", "partition-id");  
62 - System.getProperties().put("Internal.Step.Partition.Number", "0");  
63 - System.getProperties().put("Internal.Step.Unique.Count", "1");  
64 - System.getProperties().put("Internal.Step.Unique.Number", "0");  
65 - if (!kettleProperties.containsKey("vfs.sftp.org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder.USER_DIR_IS_ROOT")) {  
66 - System.getProperties().put("vfs.sftp.org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder.USER_DIR_IS_ROOT", "false");  
67 - }  
68 -  
69 - }  
70 -  
71 - @Override  
72 - public void afterPropertiesSet() throws Exception {  
73 - // 初始化kettle环境(自定义)  
74 - ktrEnvironmentInit();  
75 -  
76 - // 添加全局ktr变量,并覆盖原来的设置  
77 - Map<String, String> kvars = new HashMap<>();  
78 - kvars.put("v_db_ip", dataToolsProperties.getKvarsDbip());  
79 - kvars.put("v_db_uname", dataToolsProperties.getKvarsDbuname());  
80 - kvars.put("v_db_pwd", dataToolsProperties.getKvarsDbpwd());  
81 - kvars.put("v_db_dname", dataToolsProperties.getKvarsDbdname());  
82 - EnvUtil.applyKettleProperties(kvars, true);  
83 - KettleEnvironment.init();  
84 - }  
85 -  
86 - @Override  
87 - public File uploadFile(String filename, byte[] filedata) throws ScheduleException {  
88 - // 上传文件  
89 - try {  
90 - LOGGER.info("start uploadFile...originalFilename={}", filename);  
91 - File newFile = new File(dataToolsProperties.getFileuploadDir() + File.separator +  
92 - filename + "-upload-" + new DateTime().toString("yyyyMMddHHmmss") + ".xls");  
93 - // TODO:判定是否excel数据  
94 - Tika tika = new Tika();  
95 - String type = tika.detect(filedata);  
96 - // application/x-tika-msoffice  
97 - LOGGER.info("文件格式={}", type);  
98 - if ("application/vnd.ms-excel".equals(type) || "application/x-tika-msoffice".equals(type)) {  
99 - // .xls 2007的格式  
100 - Files.write(filedata, newFile);  
101 - } else if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(type)) {  
102 - // .xlsx 2007之后的格式  
103 - throw new Exception("暂时不支持.xlsx格式文件!");  
104 - } else {  
105 - // 非excel文件  
106 - throw new Exception("非.xls格式文件!");  
107 - }  
108 -  
109 - LOGGER.info("uploadFile success...newFilename={}", newFile.getAbsolutePath());  
110 -  
111 - return newFile;  
112 - } catch (Exception exp) {  
113 - LOGGER.info("uploadFile failed...stackTrace...");  
114 -  
115 - StringWriter sw = new StringWriter();  
116 - exp.printStackTrace(new PrintWriter(sw));  
117 - LOGGER.info(sw.toString());  
118 -  
119 - throw new ScheduleException("上传文件错误!");  
120 - }  
121 - }  
122 -  
123 - @Override  
124 - public void importData(File file, Map<String, Object> params) throws ScheduleException {  
125 - // 导入数据  
126 - String transLogId = "";  
127 - String transMetaLogId = "";  
128 - try {  
129 - LOGGER.info("start importData...originalFilename={}", file.getAbsolutePath());  
130 - // 检查参数  
131 - String transpath = String.valueOf(params.get("transpath"));  
132 - if ("null".equals(transpath)) {  
133 - throw new Exception(  
134 - "没有指定transpath参数值,无法确定ktr转换文件!");  
135 - }  
136 - File ktrFile = new File(transpath);  
137 - // 设置文件路径,错误输出文件路径参数  
138 - params.put("filepath", file.getAbsolutePath());  
139 - params.put("erroroutputdir", dataToolsProperties.getTransErrordir());  
140 -  
141 - // 2、使用kettle运行封装数据导入逻辑的ktr转换文件  
142 - // 2.1、初始化kettle(组件初始化已经做了)  
143 - // 2.2、创建转换元数据,转换  
144 - TransMeta transMeta = new TransMeta(ktrFile.getAbsolutePath());  
145 - Trans trans = new Trans(transMeta);  
146 - // 2.3、设定命名参数,用于指定数据文件,注意每个ktr必须都有以下指定的命名参数  
147 - for (String key : params.keySet()) {  
148 - trans.setParameterValue(key, String.valueOf(params.get(key)));  
149 - }  
150 - // 2.4、执行转换  
151 - trans.execute(null);  
152 - // 2.5、等待转换结束  
153 - trans.waitUntilFinished();  
154 -  
155 - // 获取日志  
156 - transLogId = trans.getLogChannelId();  
157 - transMetaLogId = transMeta.getLogChannelId();  
158 -  
159 - LoggingBuffer loggingBuffer = KettleLogStore.getAppender();  
160 - StringBuffer stringBuffer = loggingBuffer.getBuffer(  
161 - trans.getLogChannelId(), false  
162 - );  
163 - if (trans.getErrors() > 0) {  
164 - throw new Exception(stringBuffer.toString());  
165 - }  
166 - LOGGER.info(stringBuffer.toString());  
167 - LOGGER.info("importData success...");  
168 -  
169 - } catch (Exception exp) {  
170 - LOGGER.info("importData failed...statckTrace...");  
171 -  
172 - StringWriter sw = new StringWriter();  
173 - exp.printStackTrace(new PrintWriter(sw));  
174 - LOGGER.info(sw.toString());  
175 -  
176 - throw new ScheduleException("导入数据错误!");  
177 - } finally {  
178 - // 清除日志操作  
179 - KettleLogStore.discardLines(transLogId, true);  
180 - KettleLogStore.discardLines(transMetaLogId, true);  
181 - LoggingRegistry.getInstance().removeIncludingChildren(transLogId);  
182 - }  
183 - }  
184 -  
185 - @Override  
186 - public File exportData(Map<String, Object> params) throws ScheduleException {  
187 - // 导出数据  
188 - String transLogId = "";  
189 - String transMetaLogId = "";  
190 - try {  
191 - LOGGER.info("start exportData...");  
192 - // 检查参数  
193 - String filename = String.valueOf(params.get("filename"));  
194 - if ("null".equals(filename)) {  
195 - filename = "temp";  
196 - }  
197 - String transpath = String.valueOf(params.get("transpath"));  
198 - if ("null".equals(transpath)) {  
199 - throw new Exception(  
200 - "没有指定transpath参数值,无法确定ktr转换文件!");  
201 - }  
202 - File ktrFile = new File(transpath);  
203 - // 设置文件路径参数  
204 - String filepath = dataToolsProperties.getFileoutputDir() +  
205 - File.separator +  
206 - filename +  
207 - new DateTime().toString("yyyyMMddHHmmss") + ".xls";  
208 - params.put("filepath", filepath);  
209 -  
210 - // 2、使用kettle运行封装数据导入逻辑的ktr转换文件  
211 - // 2.1、初始化kettle(组件初始化已经做了)  
212 - // 2.2、创建转换元数据,转换  
213 - TransMeta transMeta = new TransMeta(ktrFile.getAbsolutePath());  
214 - Trans trans = new Trans(transMeta);  
215 - // 2.3、设定命名参数,用于指定数据文件,注意每个ktr必须都有以下指定的命名参数  
216 - for (String key : params.keySet()) {  
217 - trans.setParameterValue(key, String.valueOf(params.get(key)));  
218 - }  
219 - // 2.4、执行转换  
220 - trans.execute(null);  
221 - // 2.5、等待转换结束  
222 - trans.waitUntilFinished();  
223 -  
224 - // 获取日志  
225 - transLogId = trans.getLogChannelId();  
226 - transMetaLogId = transMeta.getLogChannelId();  
227 -  
228 - LoggingBuffer loggingBuffer = KettleLogStore.getAppender();  
229 - StringBuffer stringBuffer = loggingBuffer.getBuffer(  
230 - trans.getLogChannelId(), false  
231 - );  
232 - if (trans.getErrors() > 0) {  
233 - throw new Exception(stringBuffer.toString());  
234 - }  
235 - LOGGER.info(stringBuffer.toString());  
236 - LOGGER.info("exportData success...");  
237 -  
238 - return new File(filepath);  
239 - } catch (Exception exp) {  
240 - LOGGER.info("exportData failed...statckTrace...");  
241 -  
242 - StringWriter sw = new StringWriter();  
243 - exp.printStackTrace(new PrintWriter(sw));  
244 - LOGGER.info(sw.toString());  
245 -  
246 - throw new ScheduleException("导出数据错误!");  
247 - } finally {  
248 - // 清除日志操作  
249 - KettleLogStore.discardLines(transLogId, true);  
250 - KettleLogStore.discardLines(transMetaLogId, true);  
251 - LoggingRegistry.getInstance().removeIncludingChildren(transLogId);  
252 - }  
253 - }  
254 -} 1 +package com.bsth.service.schedule.utils;
  2 +
  3 +import com.bsth.service.schedule.exception.ScheduleException;
  4 +import com.google.common.io.Files;
  5 +import org.apache.tika.Tika;
  6 +import org.joda.time.DateTime;
  7 +import org.pentaho.di.core.KettleEnvironment;
  8 +import org.pentaho.di.core.logging.KettleLogStore;
  9 +import org.pentaho.di.core.logging.LoggingBuffer;
  10 +import org.pentaho.di.core.logging.LoggingRegistry;
  11 +import org.pentaho.di.core.util.EnvUtil;
  12 +import org.pentaho.di.trans.Trans;
  13 +import org.pentaho.di.trans.TransMeta;
  14 +import org.slf4j.Logger;
  15 +import org.slf4j.LoggerFactory;
  16 +import org.springframework.beans.factory.InitializingBean;
  17 +import org.springframework.beans.factory.annotation.Autowired;
  18 +import org.springframework.boot.context.properties.EnableConfigurationProperties;
  19 +import org.springframework.stereotype.Service;
  20 +
  21 +import java.io.File;
  22 +import java.io.PrintWriter;
  23 +import java.io.StringWriter;
  24 +import java.util.HashMap;
  25 +import java.util.Map;
  26 +import java.util.Properties;
  27 +
  28 +/**
  29 + * Created by xu on 17/1/3.
  30 + */
  31 +@Service
  32 +@EnableConfigurationProperties(DataToolsProperties.class)
  33 +public class DataToolsServiceImpl implements DataToolsService, InitializingBean {
  34 + /** 日志记录器 */
  35 + private static final Logger LOGGER = LoggerFactory.getLogger(DataToolsServiceImpl.class);
  36 +
  37 + @Autowired
  38 + private DataToolsProperties dataToolsProperties;
  39 +
  40 + /**
  41 + * 自定义kettle环境初始化定义。
  42 + */
  43 + private void ktrEnvironmentInit() throws Exception {
  44 + // 由于kettle.properties可能没有(没有安装过kettle),
  45 + // 导致 EnvUtil.environmentInit() 报找不到kettle.properties文件
  46 + // 所以这里重写 EnvUtil.environmentInit() 方法
  47 +
  48 + if (Thread.currentThread().getContextClassLoader() == null) {
  49 + Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
  50 + }
  51 +
  52 + // 获取配置文件
  53 + File file = new File(getClass().getResource(dataToolsProperties.getKettleProperties()).toURI());
  54 + Properties kettleProperties = EnvUtil.readProperties(file.getAbsolutePath());
  55 + EnvUtil.applyKettleProperties(kettleProperties);
  56 + System.getProperties().put("Internal.Cluster.Size", "1");
  57 + System.getProperties().put("Internal.Slave.Transformation.Number", "0");
  58 + System.getProperties().put("Internal.Slave.Server.Name", "slave-trans-name");
  59 + System.getProperties().put("Internal.Step.CopyNr", "0");
  60 + System.getProperties().put("Internal.Step.Name", "step-name");
  61 + System.getProperties().put("Internal.Step.Partition.ID", "partition-id");
  62 + System.getProperties().put("Internal.Step.Partition.Number", "0");
  63 + System.getProperties().put("Internal.Step.Unique.Count", "1");
  64 + System.getProperties().put("Internal.Step.Unique.Number", "0");
  65 + if (!kettleProperties.containsKey("vfs.sftp.org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder.USER_DIR_IS_ROOT")) {
  66 + System.getProperties().put("vfs.sftp.org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder.USER_DIR_IS_ROOT", "false");
  67 + }
  68 +
  69 + }
  70 +
  71 + @Override
  72 + public void afterPropertiesSet() throws Exception {
  73 + // 初始化kettle环境(自定义)
  74 + ktrEnvironmentInit();
  75 +
  76 + // 添加全局ktr变量,并覆盖原来的设置
  77 + Map<String, String> kvars = new HashMap<>();
  78 + kvars.put("v_db_ip", dataToolsProperties.getKvarsDbip());
  79 + kvars.put("v_db_uname", dataToolsProperties.getKvarsDbuname());
  80 + kvars.put("v_db_pwd", dataToolsProperties.getKvarsDbpwd());
  81 + kvars.put("v_db_dname", dataToolsProperties.getKvarsDbdname());
  82 + EnvUtil.applyKettleProperties(kvars, true);
  83 + KettleEnvironment.init();
  84 + }
  85 +
  86 + @Override
  87 + public File uploadFile(String filename, byte[] filedata) throws ScheduleException {
  88 + // 上传文件
  89 + try {
  90 + LOGGER.info("start uploadFile...originalFilename={}", filename);
  91 + File newFile = new File(dataToolsProperties.getFileuploadDir() + File.separator +
  92 + filename + "-upload-" + new DateTime().toString("yyyyMMddHHmmss") + ".xls");
  93 + // TODO:判定是否excel数据
  94 + Tika tika = new Tika();
  95 + String type = tika.detect(filedata);
  96 + // application/x-tika-msoffice
  97 + LOGGER.info("文件格式={}", type);
  98 + if ("application/vnd.ms-excel".equals(type) || "application/x-tika-msoffice".equals(type)) {
  99 + // .xls 2007的格式
  100 + Files.write(filedata, newFile);
  101 + } else if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(type)) {
  102 + // .xlsx 2007之后的格式
  103 + throw new Exception("暂时不支持.xlsx格式文件!");
  104 + } else {
  105 + // 非excel文件
  106 + throw new Exception("非.xls格式文件!");
  107 + }
  108 +
  109 + LOGGER.info("uploadFile success...newFilename={}", newFile.getAbsolutePath());
  110 +
  111 + return newFile;
  112 + } catch (Exception exp) {
  113 + LOGGER.info("uploadFile failed...stackTrace...");
  114 +
  115 + StringWriter sw = new StringWriter();
  116 + exp.printStackTrace(new PrintWriter(sw));
  117 + LOGGER.info(sw.toString());
  118 +
  119 + throw new ScheduleException("上传文件错误!");
  120 + }
  121 + }
  122 +
  123 + @Override
  124 + public void importData(File file, Map<String, Object> params) throws ScheduleException {
  125 + // 导入数据
  126 + String transLogId = "";
  127 + String transMetaLogId = "";
  128 + try {
  129 + LOGGER.info("start importData...originalFilename={}", file.getAbsolutePath());
  130 + // 检查参数
  131 + String transpath = String.valueOf(params.get("transpath"));
  132 + if ("null".equals(transpath)) {
  133 + throw new Exception(
  134 + "没有指定transpath参数值,无法确定ktr转换文件!");
  135 + }
  136 + File ktrFile = new File(transpath);
  137 + // 设置文件路径,错误输出文件路径参数
  138 + params.put("filepath", file.getAbsolutePath());
  139 + params.put("erroroutputdir", dataToolsProperties.getTransErrordir());
  140 +
  141 + // 2、使用kettle运行封装数据导入逻辑的ktr转换文件
  142 + // 2.1、初始化kettle(组件初始化已经做了)
  143 + // 2.2、创建转换元数据,转换
  144 + TransMeta transMeta = new TransMeta(ktrFile.getAbsolutePath());
  145 + Trans trans = new Trans(transMeta);
  146 + // 2.3、设定命名参数,用于指定数据文件,注意每个ktr必须都有以下指定的命名参数
  147 + for (String key : params.keySet()) {
  148 + trans.setParameterValue(key, String.valueOf(params.get(key)));
  149 + }
  150 + // 2.4、执行转换
  151 + trans.execute(null);
  152 + // 2.5、等待转换结束
  153 + trans.waitUntilFinished();
  154 +
  155 + // 获取日志
  156 + transLogId = trans.getLogChannelId();
  157 + transMetaLogId = transMeta.getLogChannelId();
  158 +
  159 + LoggingBuffer loggingBuffer = KettleLogStore.getAppender();
  160 + StringBuffer stringBuffer = loggingBuffer.getBuffer(
  161 + trans.getLogChannelId(), false
  162 + );
  163 + if (trans.getErrors() > 0) {
  164 + throw new Exception(stringBuffer.toString());
  165 + }
  166 + LOGGER.info(stringBuffer.toString());
  167 + LOGGER.info("importData success...");
  168 +
  169 + } catch (Exception exp) {
  170 + LOGGER.info("importData failed...statckTrace...");
  171 +
  172 + StringWriter sw = new StringWriter();
  173 + exp.printStackTrace(new PrintWriter(sw));
  174 + LOGGER.info(sw.toString());
  175 +
  176 + throw new ScheduleException("导入数据错误!");
  177 + } finally {
  178 + // 清除日志操作
  179 + KettleLogStore.discardLines(transLogId, true);
  180 + KettleLogStore.discardLines(transMetaLogId, true);
  181 + LoggingRegistry.getInstance().removeIncludingChildren(transLogId);
  182 + }
  183 + }
  184 +
  185 + @Override
  186 + public File exportData(Map<String, Object> params) throws ScheduleException {
  187 + // 导出数据
  188 + String transLogId = "";
  189 + String transMetaLogId = "";
  190 + try {
  191 + LOGGER.info("start exportData...");
  192 + // 检查参数
  193 + String filename = String.valueOf(params.get("filename"));
  194 + if ("null".equals(filename)) {
  195 + filename = "temp";
  196 + }
  197 + String transpath = String.valueOf(params.get("transpath"));
  198 + if ("null".equals(transpath)) {
  199 + throw new Exception(
  200 + "没有指定transpath参数值,无法确定ktr转换文件!");
  201 + }
  202 + File ktrFile = new File(transpath);
  203 + // 设置文件路径参数
  204 + String filepath = dataToolsProperties.getFileoutputDir() +
  205 + File.separator +
  206 + filename +
  207 + new DateTime().toString("yyyyMMddHHmmss") + ".xls";
  208 + params.put("filepath", filepath);
  209 +
  210 + // 2、使用kettle运行封装数据导入逻辑的ktr转换文件
  211 + // 2.1、初始化kettle(组件初始化已经做了)
  212 + // 2.2、创建转换元数据,转换
  213 + TransMeta transMeta = new TransMeta(ktrFile.getAbsolutePath());
  214 + Trans trans = new Trans(transMeta);
  215 + // 2.3、设定命名参数,用于指定数据文件,注意每个ktr必须都有以下指定的命名参数
  216 + for (String key : params.keySet()) {
  217 + trans.setParameterValue(key, String.valueOf(params.get(key)));
  218 + }
  219 + // 2.4、执行转换
  220 + trans.execute(null);
  221 + // 2.5、等待转换结束
  222 + trans.waitUntilFinished();
  223 +
  224 + // 获取日志
  225 + transLogId = trans.getLogChannelId();
  226 + transMetaLogId = transMeta.getLogChannelId();
  227 +
  228 + LoggingBuffer loggingBuffer = KettleLogStore.getAppender();
  229 + StringBuffer stringBuffer = loggingBuffer.getBuffer(
  230 + trans.getLogChannelId(), false
  231 + );
  232 + if (trans.getErrors() > 0) {
  233 + throw new Exception(stringBuffer.toString());
  234 + }
  235 + LOGGER.info(stringBuffer.toString());
  236 + LOGGER.info("exportData success...");
  237 +
  238 + return new File(filepath);
  239 + } catch (Exception exp) {
  240 + LOGGER.info("exportData failed...statckTrace...");
  241 +
  242 + StringWriter sw = new StringWriter();
  243 + exp.printStackTrace(new PrintWriter(sw));
  244 + LOGGER.info(sw.toString());
  245 +
  246 + throw new ScheduleException("导出数据错误!");
  247 + } finally {
  248 + // 清除日志操作
  249 + KettleLogStore.discardLines(transLogId, true);
  250 + KettleLogStore.discardLines(transMetaLogId, true);
  251 + LoggingRegistry.getInstance().removeIncludingChildren(transLogId);
  252 + }
  253 + }
  254 +}
src/main/java/com/bsth/service/sys/DutyEmployeeService.java
1 -package com.bsth.service.sys;  
2 -  
3 -import com.bsth.entity.sys.DutyEmployee;  
4 -import com.bsth.service.BaseService;  
5 -  
6 -import java.util.List;  
7 -  
8 -/**  
9 - * Created by panzhao on 2017/1/5.  
10 - */  
11 -public interface DutyEmployeeService extends BaseService<DutyEmployee, Long> {  
12 -  
13 - List<DutyEmployee> getDutyEmployee(String lineCode, String startTime, String endTime);  
14 -} 1 +package com.bsth.service.sys;
  2 +
  3 +import com.bsth.entity.sys.DutyEmployee;
  4 +import com.bsth.service.BaseService;
  5 +
  6 +import java.util.List;
  7 +
  8 +/**
  9 + * Created by panzhao on 2017/1/5.
  10 + */
  11 +public interface DutyEmployeeService extends BaseService<DutyEmployee, Long> {
  12 +
  13 + List<DutyEmployee> getDutyEmployee(String lineCode, String startTime, String endTime);
  14 +}
src/main/java/com/bsth/service/sys/impl/DutyEmployeeServiceImpl.java
1 -package com.bsth.service.sys.impl;  
2 -  
3 -import com.bsth.entity.sys.DutyEmployee;  
4 -import com.bsth.repository.sys.DutyEmployeeRepository;  
5 -import com.bsth.service.impl.BaseServiceImpl;  
6 -import com.bsth.service.sys.DutyEmployeeService;  
7 -import org.joda.time.format.DateTimeFormat;  
8 -import org.joda.time.format.DateTimeFormatter;  
9 -import org.springframework.beans.factory.annotation.Autowired;  
10 -import org.springframework.stereotype.Service;  
11 -  
12 -import java.util.List;  
13 -import java.util.Map;  
14 -  
15 -/**  
16 - * Created by panzhao on 2017/1/5.  
17 - */  
18 -@Service  
19 -public class DutyEmployeeServiceImpl extends BaseServiceImpl<DutyEmployee, Long> implements DutyEmployeeService {  
20 -  
21 - @Autowired  
22 - DutyEmployeeRepository dutyEmployeeRepository;  
23 -  
24 - @Override  
25 - public Map<String, Object> save(DutyEmployee dutyEmployee) {  
26 - //登入时间,当前时间 - 10分钟  
27 - dutyEmployee.setTs(System.currentTimeMillis() - (1000 * 60 * 10));  
28 - return super.save(dutyEmployee);  
29 - }  
30 -  
31 -  
32 - /**  
33 - * 获取当班调度  
34 - *  
35 - * @param lineCode 线路编码  
36 - * @param startTime 开始时间 yyyy-MM-ddHH:mm  
37 - * @param endTime 结束时间 yyyy-MM-ddHH:mm  
38 - * @return  
39 - */  
40 - public List<DutyEmployee> getDutyEmployee(String lineCode, String startTime, String endTime) {  
41 - DateTimeFormatter fmtyyyyMMddHHmm = DateTimeFormat.forPattern("yyyy-MM-ddHH:mm");  
42 - return dutyEmployeeRepository.findByLineAndTime(lineCode + ",", fmtyyyyMMddHHmm.parseMillis(startTime), fmtyyyyMMddHHmm.parseMillis(endTime));  
43 - }  
44 -} 1 +package com.bsth.service.sys.impl;
  2 +
  3 +import com.bsth.entity.sys.DutyEmployee;
  4 +import com.bsth.repository.sys.DutyEmployeeRepository;
  5 +import com.bsth.service.impl.BaseServiceImpl;
  6 +import com.bsth.service.sys.DutyEmployeeService;
  7 +import org.joda.time.format.DateTimeFormat;
  8 +import org.joda.time.format.DateTimeFormatter;
  9 +import org.springframework.beans.factory.annotation.Autowired;
  10 +import org.springframework.stereotype.Service;
  11 +
  12 +import java.util.List;
  13 +import java.util.Map;
  14 +
  15 +/**
  16 + * Created by panzhao on 2017/1/5.
  17 + */
  18 +@Service
  19 +public class DutyEmployeeServiceImpl extends BaseServiceImpl<DutyEmployee, Long> implements DutyEmployeeService {
  20 +
  21 + @Autowired
  22 + DutyEmployeeRepository dutyEmployeeRepository;
  23 +
  24 + @Override
  25 + public Map<String, Object> save(DutyEmployee dutyEmployee) {
  26 + //登入时间,当前时间 - 10分钟
  27 + dutyEmployee.setTs(System.currentTimeMillis() - (1000 * 60 * 10));
  28 + return super.save(dutyEmployee);
  29 + }
  30 +
  31 +
  32 + /**
  33 + * 获取当班调度
  34 + *
  35 + * @param lineCode 线路编码
  36 + * @param startTime 开始时间 yyyy-MM-ddHH:mm
  37 + * @param endTime 结束时间 yyyy-MM-ddHH:mm
  38 + * @return
  39 + */
  40 + public List<DutyEmployee> getDutyEmployee(String lineCode, String startTime, String endTime) {
  41 + DateTimeFormatter fmtyyyyMMddHHmm = DateTimeFormat.forPattern("yyyy-MM-ddHH:mm");
  42 + return dutyEmployeeRepository.findByLineAndTime(lineCode + ",", fmtyyyyMMddHHmm.parseMillis(startTime), fmtyyyyMMddHHmm.parseMillis(endTime));
  43 + }
  44 +}