Commit 775ecdbbf2f4225da1b90a80717d88c269d57958

Authored by 王通
1 parent 66200932

1.

src/main/java/com/bsth/data/gpsdata_v2/DataHandleProcess.java
@@ -127,16 +127,22 @@ public class DataHandleProcess { @@ -127,16 +127,22 @@ public class DataHandleProcess {
127 if (Math.abs(gps.getTimestamp() - gps.getServerTimestamp()) > 1000 * 60 * 20) 127 if (Math.abs(gps.getTimestamp() - gps.getServerTimestamp()) > 1000 * 60 * 20)
128 continue; 128 continue;
129 129
130 - gpsStateProcess.process(gps);//状态处理  
131 - stationInsideProcess.process(gps);//场站内外判定  
132 - reverseRouteProcess.process(gps);//反向路由处理  
133 - abnormalStateProcess.process(gps);//超速越界  
134 -  
135 - inStationProcess.process(gps);//进站  
136 - outStationProcess.process(gps);//出站  
137 -  
138 -  
139 - GpsCacheData.putGps(gps);//历史gps缓存 130 + if (gps.isRealtime()) {
  131 + // 状态处理
  132 + gpsStateProcess.process(gps);
  133 + }
  134 + // 场站内外判定
  135 + stationInsideProcess.process(gps);
  136 + // 反向路由处理
  137 + reverseRouteProcess.process(gps);
  138 + // 超速越界
  139 + abnormalStateProcess.process(gps);
  140 + // 进站
  141 + inStationProcess.process(gps);
  142 + // 出站
  143 + outStationProcess.process(gps);
  144 + // gps缓存
  145 + GpsCacheData.putGps(gps);
140 } catch (Throwable e) { 146 } catch (Throwable e) {
141 logger.error("", e); 147 logger.error("", e);
142 } 148 }
src/main/java/com/bsth/data/gpsdata_v2/cache/GpsCacheData.java
@@ -19,41 +19,62 @@ import java.util.concurrent.CopyOnWriteArrayList; @@ -19,41 +19,62 @@ import java.util.concurrent.CopyOnWriteArrayList;
19 */ 19 */
20 public class GpsCacheData { 20 public class GpsCacheData {
21 21
  22 + private static Logger logger = LoggerFactory.getLogger(GpsCacheData.class);
  23 +
22 /** 24 /**
23 * 每辆车缓存最后200条gps 25 * 每辆车缓存最后200条gps
24 */ 26 */
25 private static final int CACHE_SIZE = 200; 27 private static final int CACHE_SIZE = 200;
  28 +
  29 + /**
  30 + * 从网关实时过来的GPS数据缓存
  31 + */
26 private static ConcurrentMap<String, CircleQueue<GpsEntity>> gpsCacheMap = new ConcurrentHashMap<>(); 32 private static ConcurrentMap<String, CircleQueue<GpsEntity>> gpsCacheMap = new ConcurrentHashMap<>();
27 33
28 /** 34 /**
  35 + * 从数据库重算 GPS数据缓存
  36 + */
  37 + private static ConcurrentMap<String, CircleQueue<GpsEntity>> historyGpsCacheMap = new ConcurrentHashMap<>();
  38 +
  39 + /**
29 * 车辆执行班次的详细 进出站数据 40 * 车辆执行班次的详细 进出站数据
30 */ 41 */
31 - //private static ArrayListMultimap<String, GpsExecTrail> trailListMultimap = ArrayListMultimap.create();  
32 private static Map<String, List<GpsExecTrail>> trailListMultimap = new ConcurrentHashMap<>(); 42 private static Map<String, List<GpsExecTrail>> trailListMultimap = new ConcurrentHashMap<>();
33 43
34 - static Logger logger = LoggerFactory.getLogger(GpsCacheData.class); 44 + /**
  45 + * 数据库重算 进出站缓存
  46 + */
  47 + private static Map<String, List<GpsExecTrail>> historyTrailListMultimap = new ConcurrentHashMap<>();
35 48
36 - public static CircleQueue<GpsEntity> getGps(String device) {  
37 - return gpsCacheMap.get(device); 49 + /**
  50 + * 获取GPS缓存
  51 + * @param device
  52 + * @param realtime true实时/false历史
  53 + * @return
  54 + */
  55 + public static CircleQueue<GpsEntity> getGps(String device, boolean realtime) {
  56 + ConcurrentMap<String, CircleQueue<GpsEntity>> map = realtime ? gpsCacheMap : historyGpsCacheMap;
  57 + return map.get(device);
38 } 58 }
39 59
40 /** 60 /**
41 * 清除车辆的轨迹数据 61 * 清除车辆的轨迹数据
42 * @param nbbm 62 * @param nbbm
43 */ 63 */
44 - public static void remove(String nbbm){  
45 - //logger.info("清除车辆到离站轨迹, " + nbbm);  
46 - trailListMultimap.remove(nbbm); 64 + public static void remove(String nbbm, boolean realtime){
  65 + Map<String, List<GpsExecTrail>> map = realtime ? trailListMultimap : historyTrailListMultimap;
  66 + map.remove(nbbm);
47 } 67 }
48 68
49 - public static GpsExecTrail gpsExecTrail(String nbbm){  
50 - List<GpsExecTrail> list = trailListMultimap.get(nbbm); 69 + public static GpsExecTrail gpsExecTrail(String nbbm, boolean realtime){
  70 + Map<String, List<GpsExecTrail>> map = realtime ? trailListMultimap : historyTrailListMultimap;
  71 + List<GpsExecTrail> list = map.get(nbbm);
51 72
52 GpsExecTrail trail; 73 GpsExecTrail trail;
53 if (null == list || list.size() == 0 || list.get(list.size() - 1).isEnd()) { 74 if (null == list || list.size() == 0 || list.get(list.size() - 1).isEnd()) {
54 if (null == list) { 75 if (null == list) {
55 list = new CopyOnWriteArrayList<>(); 76 list = new CopyOnWriteArrayList<>();
56 - trailListMultimap.put(nbbm, list); 77 + map.put(nbbm, list);
57 } 78 }
58 trail = new GpsExecTrail(); 79 trail = new GpsExecTrail();
59 list.add(trail); 80 list.add(trail);
@@ -65,36 +86,39 @@ public class GpsCacheData { @@ -65,36 +86,39 @@ public class GpsCacheData {
65 } 86 }
66 87
67 public static void out(GpsEntity gps){ 88 public static void out(GpsEntity gps){
68 - GpsExecTrail trail = gpsExecTrail(gps.getNbbm()); 89 + GpsExecTrail trail = gpsExecTrail(gps.getNbbm(), gps.isRealtime());
69 trail.getSrs().add(gps); 90 trail.getSrs().add(gps);
70 91
71 } 92 }
72 93
73 public static void in(GpsEntity gps, boolean end){ 94 public static void in(GpsEntity gps, boolean end){
74 - GpsExecTrail trail = gpsExecTrail(gps.getNbbm()); 95 + GpsExecTrail trail = gpsExecTrail(gps.getNbbm(), gps.isRealtime());
75 trail.getSrs().add(gps); 96 trail.getSrs().add(gps);
76 trail.setEnd(end); 97 trail.setEnd(end);
77 } 98 }
78 99
79 public static GpsEntity getPrev(GpsEntity gps){ 100 public static GpsEntity getPrev(GpsEntity gps){
80 - CircleQueue<GpsEntity> queue = gpsCacheMap.get(gps.getDeviceId()); 101 + ConcurrentMap<String, CircleQueue<GpsEntity>> map = gps.isRealtime() ? gpsCacheMap : historyGpsCacheMap;
  102 + CircleQueue<GpsEntity> queue = map.get(gps.getDeviceId());
81 if(queue != null) 103 if(queue != null)
82 return queue.getTail(); 104 return queue.getTail();
83 return null; 105 return null;
84 } 106 }
85 107
86 public static void putGps(GpsEntity gps) { 108 public static void putGps(GpsEntity gps) {
87 - CircleQueue<GpsEntity> queue = gpsCacheMap.get(gps.getDeviceId()); 109 + ConcurrentMap<String, CircleQueue<GpsEntity>> map = gps.isRealtime() ? gpsCacheMap : historyGpsCacheMap;
  110 + CircleQueue<GpsEntity> queue = map.get(gps.getDeviceId());
88 if (queue == null) { 111 if (queue == null) {
89 queue = new CircleQueue<>(CACHE_SIZE); 112 queue = new CircleQueue<>(CACHE_SIZE);
90 - gpsCacheMap.put(gps.getDeviceId(), queue); 113 + map.put(gps.getDeviceId(), queue);
91 } 114 }
92 queue.add(gps); 115 queue.add(gps);
93 } 116 }
94 117
95 - public static void clear(String deviceId) { 118 + public static void clear(String deviceId, boolean realtime) {
  119 + ConcurrentMap<String, CircleQueue<GpsEntity>> map = realtime ? gpsCacheMap : historyGpsCacheMap;
96 try { 120 try {
97 - CircleQueue<GpsEntity> queue = gpsCacheMap.get(deviceId); 121 + CircleQueue<GpsEntity> queue = map.get(deviceId);
98 if (queue != null) 122 if (queue != null)
99 queue.clear(); 123 queue.clear();
100 } catch (Exception e) { 124 } catch (Exception e) {
@@ -103,7 +127,8 @@ public class GpsCacheData { @@ -103,7 +127,8 @@ public class GpsCacheData {
103 } 127 }
104 128
105 public static StationRoute prevStation(GpsEntity gps) { 129 public static StationRoute prevStation(GpsEntity gps) {
106 - List<GpsExecTrail> trails = trailListMultimap.get(gps.getNbbm()); 130 + Map<String, List<GpsExecTrail>> map = gps.isRealtime() ? trailListMultimap : historyTrailListMultimap;
  131 + List<GpsExecTrail> trails = map.get(gps.getNbbm());
107 if(null == trails || trails.size() == 0) 132 if(null == trails || trails.size() == 0)
108 return null; 133 return null;
109 134
@@ -124,8 +149,8 @@ public class GpsCacheData { @@ -124,8 +149,8 @@ public class GpsCacheData {
124 * @return 149 * @return
125 */ 150 */
126 public static int lastInTrailsSize(GpsEntity gps) { 151 public static int lastInTrailsSize(GpsEntity gps) {
127 - //int size = 0;  
128 - List<GpsExecTrail> trails = trailListMultimap.get(gps.getNbbm()); 152 + Map<String, List<GpsExecTrail>> map = gps.isRealtime() ? trailListMultimap : historyTrailListMultimap;
  153 + List<GpsExecTrail> trails = map.get(gps.getNbbm());
129 if(null == trails || trails.size() == 0) 154 if(null == trails || trails.size() == 0)
130 return 0; 155 return 0;
131 156
@@ -143,7 +168,8 @@ public class GpsCacheData { @@ -143,7 +168,8 @@ public class GpsCacheData {
143 168
144 public static List<StationRoute> prevMultiStation(GpsEntity gps) { 169 public static List<StationRoute> prevMultiStation(GpsEntity gps) {
145 List<StationRoute> rs = new ArrayList<>(); 170 List<StationRoute> rs = new ArrayList<>();
146 - List<GpsExecTrail> trails = trailListMultimap.get(gps.getNbbm()); 171 + Map<String, List<GpsExecTrail>> map = gps.isRealtime() ? trailListMultimap : historyTrailListMultimap;
  172 + List<GpsExecTrail> trails = map.get(gps.getNbbm());
147 if(null == trails || trails.size() == 0) 173 if(null == trails || trails.size() == 0)
148 return null; 174 return null;
149 175
src/main/java/com/bsth/data/gpsdata_v2/entity/GpsEntity.java
1 -package com.bsth.data.gpsdata_v2.entity;  
2 -  
3 -import com.fasterxml.jackson.annotation.JsonIgnore;  
4 -  
5 -/**  
6 - *  
7 - * @ClassName: GpsRealData  
8 - * @Description: TODO(HTTP接口的实时GPS数据)  
9 - * @author PanZhao  
10 - * @date 2016年5月11日 下午4:32:07  
11 - *  
12 - */  
13 -public class GpsEntity implements Cloneable{  
14 -  
15 - /** 公司代码 */  
16 - @JsonIgnore  
17 - private Short companyCode;  
18 -  
19 - /** 线路编码 */  
20 - private String lineId;  
21 -  
22 - /** 设备编码 */  
23 - private String deviceId;  
24 -  
25 - /** 停车场编码 */  
26 - private String carparkNo;  
27 -  
28 - /** 站点编码 */  
29 - private String stopNo;  
30 -  
31 - /** 站点名称 */  
32 - private String stationName;  
33 -  
34 - /** 到站时间 */  
35 - @JsonIgnore  
36 - private long arrTime;  
37 -  
38 - /** 经度 */  
39 - private Float lon;  
40 -  
41 - /** 纬度 */  
42 - private Float lat;  
43 -  
44 - /** GPS发送时间戳 */  
45 - private Long timestamp;  
46 -  
47 - /** 网关收到时间 */  
48 - private Long serverTimestamp;  
49 -  
50 - /** 速度 */  
51 - private Float speed;  
52 -  
53 - /** 方向(角度) */  
54 - private float direction;  
55 -  
56 - /** 营运状态( 0 营运 ,1 非营运, -1 无效) */  
57 - private Integer state;  
58 -  
59 - /** 上下行(0 上行 , 1 下行 , -1 无效) */  
60 - private Byte upDown;  
61 -  
62 - /**  
63 - * 设备原始走向_营运状态  
64 - * 当设备状态和系统不一致时,该字段有值  
65 - */  
66 - private String origStateStr;  
67 -  
68 - /** 车辆内部编码 */  
69 - private String nbbm;  
70 -  
71 - /** 预计到达终点时间 */  
72 - private Float expectStopTime;  
73 -  
74 - /** 当前执行班次ID */  
75 - private Long schId;  
76 -  
77 - private int version;  
78 -  
79 - /** 0: 站外 1:站内 2:场内 */  
80 - private int instation;  
81 -  
82 - /** 站点信息,站内时有值 */  
83 - @JsonIgnore  
84 - private StationRoute station;  
85 -  
86 - /**  
87 - * 前置约束 -站点编码  
88 - */  
89 - @JsonIgnore  
90 - private String premiseCode;  
91 -  
92 - /** 状态 */  
93 - private String signalState = "normal";  
94 -  
95 - /** 异常状态 */  
96 - private String abnormalStatus;  
97 -  
98 - /** 越界距离 */  
99 - private double outOfBoundDistance;  
100 -  
101 - /** gps是否有效 设备端发送的状态 */  
102 - private int valid;  
103 -  
104 - /**  
105 - * 数据来源  
106 - * 1:网关  
107 - * 0:转发  
108 - */  
109 - private int source = -1;  
110 -  
111 - private String remark;  
112 - private String planCode;  
113 -  
114 - public Object clone() {  
115 - try {  
116 - return super.clone();  
117 - } catch (CloneNotSupportedException e) {  
118 - return null;  
119 - }  
120 - }  
121 -  
122 - public String getDeviceId() {  
123 - return deviceId;  
124 - }  
125 -  
126 - public void setDeviceId(String deviceId) {  
127 - this.deviceId = deviceId;  
128 - }  
129 -  
130 - public String getCarparkNo() {  
131 - return carparkNo;  
132 - }  
133 -  
134 - public void setCarparkNo(String carparkNo) {  
135 - this.carparkNo = carparkNo;  
136 - }  
137 -  
138 - public String getStopNo() {  
139 - return stopNo;  
140 - }  
141 -  
142 - public void setStopNo(String stopNo) {  
143 - this.stopNo = stopNo;  
144 - }  
145 -  
146 - public Float getLon() {  
147 - return lon;  
148 - }  
149 -  
150 - public void setLon(Float lon) {  
151 - this.lon = lon;  
152 - }  
153 -  
154 - public Float getLat() {  
155 - return lat;  
156 - }  
157 -  
158 - public void setLat(Float lat) {  
159 - this.lat = lat;  
160 - }  
161 -  
162 - public Long getTimestamp() {  
163 - return timestamp;  
164 - }  
165 -  
166 - public void setTimestamp(Long timestamp) {  
167 - this.timestamp = timestamp;  
168 - }  
169 -  
170 -  
171 - public Integer getState() {  
172 - return state;  
173 - }  
174 -  
175 - public void setState(Integer state) {  
176 - this.state = state;  
177 - }  
178 -  
179 - public String getNbbm() {  
180 - return nbbm;  
181 - }  
182 -  
183 - public void setNbbm(String nbbm) {  
184 - this.nbbm = nbbm;  
185 - }  
186 -  
187 - public String getStationName() {  
188 - return stationName;  
189 - }  
190 -  
191 - public void setStationName(String stationName) {  
192 - this.stationName = stationName;  
193 - }  
194 -  
195 - public long getArrTime() {  
196 - return arrTime;  
197 - }  
198 -  
199 - public void setArrTime(long arrTime) {  
200 - this.arrTime = arrTime;  
201 - }  
202 -  
203 - public Float getExpectStopTime() {  
204 - return expectStopTime;  
205 - }  
206 -  
207 - public void setExpectStopTime(Float expectStopTime) {  
208 - this.expectStopTime = expectStopTime;  
209 - }  
210 -  
211 - public String getLineId() {  
212 - return lineId;  
213 - }  
214 -  
215 - public void setLineId(String lineId) {  
216 - this.lineId = lineId;  
217 - }  
218 -  
219 - public Long getSchId() {  
220 - return schId;  
221 - }  
222 -  
223 - public void setSchId(Long schId) {  
224 - this.schId = schId;  
225 - }  
226 -  
227 -  
228 - public int getVersion() {  
229 - return version;  
230 - }  
231 -  
232 - public void setVersion(int version) {  
233 - this.version = version;  
234 - }  
235 -  
236 - public StationRoute getStation() {  
237 - return station;  
238 - }  
239 -  
240 - public void setStation(StationRoute station) {  
241 - this.station = station;  
242 - }  
243 -  
244 - public String getSignalState() {  
245 - return signalState;  
246 - }  
247 -  
248 - public void setSignalState(String signalState) {  
249 - this.signalState = signalState;  
250 - }  
251 -  
252 - public int getInstation() {  
253 - return instation;  
254 - }  
255 -  
256 - public void setInstation(int instation) {  
257 - this.instation = instation;  
258 - }  
259 -  
260 - public String getAbnormalStatus() {  
261 - return abnormalStatus;  
262 - }  
263 -  
264 - public void setAbnormalStatus(String abnormalStatus) {  
265 - this.abnormalStatus = abnormalStatus;  
266 - }  
267 -  
268 - public double getOutOfBoundDistance() {  
269 - return outOfBoundDistance;  
270 - }  
271 -  
272 - public void setOutOfBoundDistance(double outOfBoundDistance) {  
273 - this.outOfBoundDistance = outOfBoundDistance;  
274 - }  
275 -  
276 - public int getValid() {  
277 - return valid;  
278 - }  
279 -  
280 - public void setValid(int valid) {  
281 - this.valid = valid;  
282 - }  
283 -  
284 -  
285 -  
286 - public short getCompanyCode() {  
287 - return companyCode;  
288 - }  
289 -  
290 - public void setCompanyCode(short companyCode) {  
291 - this.companyCode = companyCode;  
292 - }  
293 -  
294 - public Byte getUpDown() {  
295 - return upDown;  
296 - }  
297 -  
298 - public void setUpDown(Byte upDown) {  
299 - this.upDown = upDown;  
300 - }  
301 -  
302 -  
303 - public float getDirection() {  
304 - return direction;  
305 - }  
306 -  
307 - public void setDirection(float direction) {  
308 - this.direction = direction;  
309 - }  
310 -  
311 - public Float getSpeed() {  
312 - return speed;  
313 - }  
314 -  
315 - public void setSpeed(Float speed) {  
316 - this.speed = speed;  
317 - }  
318 -  
319 - public int getSource() {  
320 - return source;  
321 - }  
322 -  
323 - public void setSource(int source) {  
324 - this.source = source;  
325 - }  
326 -  
327 - public void offline(){  
328 - this.setAbnormalStatus("offline");  
329 - }  
330 -  
331 -/* public boolean isOnline(){  
332 - if(isOffline())  
333 - return false;  
334 -  
335 - long t = System.currentTimeMillis();  
336 -  
337 - if((t - this.getServerTimestamp()) > 1000 * 60 * 2){  
338 - return false;  
339 - }  
340 -  
341 - if((this.getServerTimestamp() - t) > 1000 * 60 * 3){  
342 - return false;  
343 - }  
344 - return true;  
345 - }*/  
346 -  
347 - /**  
348 - * 是否营运  
349 - * @return  
350 - */  
351 - public boolean isService(){  
352 - return state!=null && state==0;  
353 - }  
354 -  
355 - public boolean isOffline(){  
356 - return this.getAbnormalStatus() != null && this.getAbnormalStatus().equals("offline");  
357 - }  
358 -  
359 - public Long getServerTimestamp() {  
360 - return serverTimestamp;  
361 - }  
362 -  
363 - public void setServerTimestamp(Long serverTimestamp) {  
364 - this.serverTimestamp = serverTimestamp;  
365 - }  
366 -  
367 - public String getPremiseCode() {  
368 - return premiseCode;  
369 - }  
370 -  
371 - public void setPremiseCode(String premiseCode) {  
372 - this.premiseCode = premiseCode;  
373 - }  
374 -  
375 - public String getRemark() {  
376 - return remark;  
377 - }  
378 -  
379 - public void setRemark(String remark) {  
380 - this.remark = remark;  
381 - }  
382 -  
383 - public String getPlanCode() {  
384 - return planCode;  
385 - }  
386 -  
387 - public void setPlanCode(String planCode) {  
388 - this.planCode = planCode;  
389 - }  
390 -  
391 - public String getOrigStateStr() {  
392 - return origStateStr;  
393 - }  
394 -  
395 - public void setOrigStateStr(String origStateStr) {  
396 - this.origStateStr = origStateStr;  
397 - }  
398 -} 1 +package com.bsth.data.gpsdata_v2.entity;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonIgnore;
  4 +
  5 +/**
  6 + *
  7 + * @ClassName: GpsRealData
  8 + * @Description: TODO(HTTP接口的实时GPS数据)
  9 + * @author PanZhao
  10 + * @date 2016年5月11日 下午4:32:07
  11 + *
  12 + */
  13 +public class GpsEntity implements Cloneable{
  14 +
  15 + /** 公司代码 */
  16 + @JsonIgnore
  17 + private Short companyCode;
  18 +
  19 + /** 线路编码 */
  20 + private String lineId;
  21 +
  22 + /** 设备编码 */
  23 + private String deviceId;
  24 +
  25 + /** 停车场编码 */
  26 + private String carparkNo;
  27 +
  28 + /** 站点编码 */
  29 + private String stopNo;
  30 +
  31 + /** 站点名称 */
  32 + private String stationName;
  33 +
  34 + /** 到站时间 */
  35 + @JsonIgnore
  36 + private long arrTime;
  37 +
  38 + /** 经度 */
  39 + private Float lon;
  40 +
  41 + /** 纬度 */
  42 + private Float lat;
  43 +
  44 + /** GPS发送时间戳 */
  45 + private Long timestamp;
  46 +
  47 + /** 网关收到时间 */
  48 + private Long serverTimestamp;
  49 +
  50 + /** 速度 */
  51 + private Float speed;
  52 +
  53 + /** 方向(角度) */
  54 + private float direction;
  55 +
  56 + /** 营运状态( 0 营运 ,1 非营运, -1 无效) */
  57 + private Integer state;
  58 +
  59 + /** 上下行(0 上行 , 1 下行 , -1 无效) */
  60 + private Byte upDown;
  61 +
  62 + /**
  63 + * 设备原始走向_营运状态
  64 + * 当设备状态和系统不一致时,该字段有值
  65 + */
  66 + private String origStateStr;
  67 +
  68 + /** 车辆内部编码 */
  69 + private String nbbm;
  70 +
  71 + /** 预计到达终点时间 */
  72 + private Float expectStopTime;
  73 +
  74 + /** 当前执行班次ID */
  75 + private Long schId;
  76 +
  77 + private int version;
  78 +
  79 + /** 0: 站外 1:站内 2:场内 */
  80 + private int instation;
  81 +
  82 + /** 站点信息,站内时有值 */
  83 + @JsonIgnore
  84 + private StationRoute station;
  85 +
  86 + /**
  87 + * 前置约束 -站点编码
  88 + */
  89 + @JsonIgnore
  90 + private String premiseCode;
  91 +
  92 + /** 状态 */
  93 + private String signalState = "normal";
  94 +
  95 + /** 异常状态 */
  96 + private String abnormalStatus;
  97 +
  98 + /** 越界距离 */
  99 + private double outOfBoundDistance;
  100 +
  101 + /** gps是否有效 设备端发送的状态 */
  102 + private int valid;
  103 +
  104 + /**
  105 + * 数据来源
  106 + * 1:网关
  107 + * 0:转发
  108 + */
  109 + private int source = -1;
  110 +
  111 + private String remark;
  112 + private String planCode;
  113 +
  114 + private boolean realtime;
  115 +
  116 + public Object clone() {
  117 + try {
  118 + return super.clone();
  119 + } catch (CloneNotSupportedException e) {
  120 + return null;
  121 + }
  122 + }
  123 +
  124 + public String getDeviceId() {
  125 + return deviceId;
  126 + }
  127 +
  128 + public void setDeviceId(String deviceId) {
  129 + this.deviceId = deviceId;
  130 + }
  131 +
  132 + public String getCarparkNo() {
  133 + return carparkNo;
  134 + }
  135 +
  136 + public void setCarparkNo(String carparkNo) {
  137 + this.carparkNo = carparkNo;
  138 + }
  139 +
  140 + public String getStopNo() {
  141 + return stopNo;
  142 + }
  143 +
  144 + public void setStopNo(String stopNo) {
  145 + this.stopNo = stopNo;
  146 + }
  147 +
  148 + public Float getLon() {
  149 + return lon;
  150 + }
  151 +
  152 + public void setLon(Float lon) {
  153 + this.lon = lon;
  154 + }
  155 +
  156 + public Float getLat() {
  157 + return lat;
  158 + }
  159 +
  160 + public void setLat(Float lat) {
  161 + this.lat = lat;
  162 + }
  163 +
  164 + public Long getTimestamp() {
  165 + return timestamp;
  166 + }
  167 +
  168 + public void setTimestamp(Long timestamp) {
  169 + this.timestamp = timestamp;
  170 + }
  171 +
  172 +
  173 + public Integer getState() {
  174 + return state;
  175 + }
  176 +
  177 + public void setState(Integer state) {
  178 + this.state = state;
  179 + }
  180 +
  181 + public String getNbbm() {
  182 + return nbbm;
  183 + }
  184 +
  185 + public void setNbbm(String nbbm) {
  186 + this.nbbm = nbbm;
  187 + }
  188 +
  189 + public String getStationName() {
  190 + return stationName;
  191 + }
  192 +
  193 + public void setStationName(String stationName) {
  194 + this.stationName = stationName;
  195 + }
  196 +
  197 + public long getArrTime() {
  198 + return arrTime;
  199 + }
  200 +
  201 + public void setArrTime(long arrTime) {
  202 + this.arrTime = arrTime;
  203 + }
  204 +
  205 + public Float getExpectStopTime() {
  206 + return expectStopTime;
  207 + }
  208 +
  209 + public void setExpectStopTime(Float expectStopTime) {
  210 + this.expectStopTime = expectStopTime;
  211 + }
  212 +
  213 + public String getLineId() {
  214 + return lineId;
  215 + }
  216 +
  217 + public void setLineId(String lineId) {
  218 + this.lineId = lineId;
  219 + }
  220 +
  221 + public Long getSchId() {
  222 + return schId;
  223 + }
  224 +
  225 + public void setSchId(Long schId) {
  226 + this.schId = schId;
  227 + }
  228 +
  229 +
  230 + public int getVersion() {
  231 + return version;
  232 + }
  233 +
  234 + public void setVersion(int version) {
  235 + this.version = version;
  236 + }
  237 +
  238 + public StationRoute getStation() {
  239 + return station;
  240 + }
  241 +
  242 + public void setStation(StationRoute station) {
  243 + this.station = station;
  244 + }
  245 +
  246 + public String getSignalState() {
  247 + return signalState;
  248 + }
  249 +
  250 + public void setSignalState(String signalState) {
  251 + this.signalState = signalState;
  252 + }
  253 +
  254 + public int getInstation() {
  255 + return instation;
  256 + }
  257 +
  258 + public void setInstation(int instation) {
  259 + this.instation = instation;
  260 + }
  261 +
  262 + public String getAbnormalStatus() {
  263 + return abnormalStatus;
  264 + }
  265 +
  266 + public void setAbnormalStatus(String abnormalStatus) {
  267 + this.abnormalStatus = abnormalStatus;
  268 + }
  269 +
  270 + public double getOutOfBoundDistance() {
  271 + return outOfBoundDistance;
  272 + }
  273 +
  274 + public void setOutOfBoundDistance(double outOfBoundDistance) {
  275 + this.outOfBoundDistance = outOfBoundDistance;
  276 + }
  277 +
  278 + public int getValid() {
  279 + return valid;
  280 + }
  281 +
  282 + public void setValid(int valid) {
  283 + this.valid = valid;
  284 + }
  285 +
  286 +
  287 +
  288 + public short getCompanyCode() {
  289 + return companyCode;
  290 + }
  291 +
  292 + public void setCompanyCode(short companyCode) {
  293 + this.companyCode = companyCode;
  294 + }
  295 +
  296 + public Byte getUpDown() {
  297 + return upDown;
  298 + }
  299 +
  300 + public void setUpDown(Byte upDown) {
  301 + this.upDown = upDown;
  302 + }
  303 +
  304 +
  305 + public float getDirection() {
  306 + return direction;
  307 + }
  308 +
  309 + public void setDirection(float direction) {
  310 + this.direction = direction;
  311 + }
  312 +
  313 + public Float getSpeed() {
  314 + return speed;
  315 + }
  316 +
  317 + public void setSpeed(Float speed) {
  318 + this.speed = speed;
  319 + }
  320 +
  321 + public int getSource() {
  322 + return source;
  323 + }
  324 +
  325 + public void setSource(int source) {
  326 + this.source = source;
  327 + }
  328 +
  329 + public void offline(){
  330 + this.setAbnormalStatus("offline");
  331 + }
  332 +
  333 +/* public boolean isOnline(){
  334 + if(isOffline())
  335 + return false;
  336 +
  337 + long t = System.currentTimeMillis();
  338 +
  339 + if((t - this.getServerTimestamp()) > 1000 * 60 * 2){
  340 + return false;
  341 + }
  342 +
  343 + if((this.getServerTimestamp() - t) > 1000 * 60 * 3){
  344 + return false;
  345 + }
  346 + return true;
  347 + }*/
  348 +
  349 + /**
  350 + * 是否营运
  351 + * @return
  352 + */
  353 + public boolean isService(){
  354 + return state!=null && state==0;
  355 + }
  356 +
  357 + public boolean isOffline(){
  358 + return this.getAbnormalStatus() != null && this.getAbnormalStatus().equals("offline");
  359 + }
  360 +
  361 + public Long getServerTimestamp() {
  362 + return serverTimestamp;
  363 + }
  364 +
  365 + public void setServerTimestamp(Long serverTimestamp) {
  366 + this.serverTimestamp = serverTimestamp;
  367 + }
  368 +
  369 + public String getPremiseCode() {
  370 + return premiseCode;
  371 + }
  372 +
  373 + public void setPremiseCode(String premiseCode) {
  374 + this.premiseCode = premiseCode;
  375 + }
  376 +
  377 + public String getRemark() {
  378 + return remark;
  379 + }
  380 +
  381 + public void setRemark(String remark) {
  382 + this.remark = remark;
  383 + }
  384 +
  385 + public String getPlanCode() {
  386 + return planCode;
  387 + }
  388 +
  389 + public void setPlanCode(String planCode) {
  390 + this.planCode = planCode;
  391 + }
  392 +
  393 + public String getOrigStateStr() {
  394 + return origStateStr;
  395 + }
  396 +
  397 + public void setOrigStateStr(String origStateStr) {
  398 + this.origStateStr = origStateStr;
  399 + }
  400 +
  401 + public boolean isRealtime() {
  402 + return realtime;
  403 + }
  404 +
  405 + public void setRealtime(boolean realtime) {
  406 + this.realtime = realtime;
  407 + }
  408 +}
src/main/java/com/bsth/data/gpsdata_v2/load/GatewayHttpLoader.java
1 -package com.bsth.data.gpsdata_v2.load;  
2 -  
3 -import com.alibaba.fastjson.JSON;  
4 -import com.bsth.data.BasicData;  
5 -import com.bsth.data.gpsdata_v2.GpsRealData;  
6 -import com.bsth.data.gpsdata_v2.entity.GpsEntity;  
7 -import com.bsth.data.gpsdata_v2.utils.GpsDataUtils;  
8 -import com.bsth.util.ConfigUtil;  
9 -import org.apache.commons.lang3.StringUtils;  
10 -import org.apache.http.HttpEntity;  
11 -import org.apache.http.client.config.RequestConfig;  
12 -import org.apache.http.client.methods.CloseableHttpResponse;  
13 -import org.apache.http.client.methods.HttpGet;  
14 -import org.apache.http.impl.client.CloseableHttpClient;  
15 -import org.apache.http.impl.client.HttpClients;  
16 -import org.slf4j.Logger;  
17 -import org.slf4j.LoggerFactory;  
18 -import org.springframework.beans.BeansException;  
19 -import org.springframework.context.ApplicationContext;  
20 -import org.springframework.context.ApplicationContextAware;  
21 -import org.springframework.stereotype.Component;  
22 -  
23 -import java.io.BufferedReader;  
24 -import java.io.InputStreamReader;  
25 -import java.util.ArrayList;  
26 -import java.util.List;  
27 -  
28 -/**  
29 - * 从网关http 接口加载数据  
30 - * Created by panzhao on 2017/11/15.  
31 - */  
32 -@Component  
33 -public class GatewayHttpLoader implements ApplicationContextAware{  
34 -  
35 - static Logger logger = LoggerFactory.getLogger(GatewayHttpLoader.class);  
36 -  
37 - static String url;  
38 - static List<GpsEntity> list;  
39 - static CloseableHttpClient httpClient = null;  
40 - static HttpGet get;  
41 - static RequestConfig requestConfig;  
42 - static CloseableHttpResponse response;  
43 - static HttpEntity entity;  
44 - static BufferedReader br;  
45 -  
46 - static GpsRealData gpsRealData;  
47 -  
48 - static{  
49 - url = ConfigUtil.get("http.gps.real.url");  
50 - list = new ArrayList<>();  
51 - httpClient = HttpClients.createDefault();  
52 - get = new HttpGet(url);  
53 - requestConfig = RequestConfig.custom()  
54 - .setConnectTimeout(2500).setConnectionRequestTimeout(2000)  
55 - .setSocketTimeout(2500).build();  
56 - get.setConfig(requestConfig);  
57 - }  
58 -  
59 - public static List<GpsEntity> load(){  
60 - try{  
61 - if(list.size() > 0)  
62 - list.clear();  
63 -  
64 - response = httpClient.execute(get);  
65 - entity = response.getEntity();  
66 -  
67 - if(null == entity)  
68 - return list;  
69 -  
70 - br = new BufferedReader(new InputStreamReader(entity.getContent()));  
71 -  
72 - StringBuilder sb = new StringBuilder();  
73 - String str;  
74 - while ((str = br.readLine()) != null)  
75 - sb.append(str);  
76 -  
77 - list = JSON.parseArray(JSON.parseObject(sb.toString()).getString("data"), GpsEntity.class);  
78 - //过滤掉无效的点位  
79 - list = GpsDataUtils.clearInvalid(list);  
80 -  
81 - List<GpsEntity> ups = new ArrayList<>();  
82 - String nbbm;  
83 - for (GpsEntity gps : list) {  
84 - if (StringUtils.isBlank(gps.getDeviceId()))  
85 - continue;  
86 -  
87 - if (gps_equals(gpsRealData.get(gps.getDeviceId()), gps))  
88 - continue;  
89 -  
90 - nbbm = BasicData.deviceId2NbbmMap.get(gps.getDeviceId());  
91 - gps.setNbbm(nbbm);  
92 - ups.add(gps);  
93 - }  
94 - list = ups;  
95 -  
96 - if (null != response)  
97 - response.close();  
98 - }catch (Exception e){  
99 - logger.error("", e);  
100 - }  
101 - return list;  
102 - }  
103 -  
104 -  
105 - private static boolean gps_equals(GpsEntity old, GpsEntity gps){  
106 - if(old != null &&  
107 - old.getTimestamp().equals(gps.getTimestamp()) &&  
108 - old.getLat().equals(gps.getLat()) &&  
109 - old.getLon().equals(gps.getLon()))  
110 - return true;  
111 - return false;  
112 - }  
113 -  
114 - @Override  
115 - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
116 - gpsRealData = applicationContext.getBean(GpsRealData.class);  
117 - }  
118 -} 1 +package com.bsth.data.gpsdata_v2.load;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.bsth.data.BasicData;
  5 +import com.bsth.data.gpsdata_v2.GpsRealData;
  6 +import com.bsth.data.gpsdata_v2.entity.GpsEntity;
  7 +import com.bsth.data.gpsdata_v2.utils.GpsDataUtils;
  8 +import com.bsth.util.ConfigUtil;
  9 +import org.apache.commons.lang3.StringUtils;
  10 +import org.apache.http.HttpEntity;
  11 +import org.apache.http.client.config.RequestConfig;
  12 +import org.apache.http.client.methods.CloseableHttpResponse;
  13 +import org.apache.http.client.methods.HttpGet;
  14 +import org.apache.http.impl.client.CloseableHttpClient;
  15 +import org.apache.http.impl.client.HttpClients;
  16 +import org.slf4j.Logger;
  17 +import org.slf4j.LoggerFactory;
  18 +import org.springframework.beans.BeansException;
  19 +import org.springframework.context.ApplicationContext;
  20 +import org.springframework.context.ApplicationContextAware;
  21 +import org.springframework.stereotype.Component;
  22 +
  23 +import java.io.BufferedReader;
  24 +import java.io.InputStreamReader;
  25 +import java.util.ArrayList;
  26 +import java.util.List;
  27 +
  28 +/**
  29 + * 从网关http 接口加载数据
  30 + * Created by panzhao on 2017/11/15.
  31 + */
  32 +@Component
  33 +public class GatewayHttpLoader implements ApplicationContextAware{
  34 +
  35 + static Logger logger = LoggerFactory.getLogger(GatewayHttpLoader.class);
  36 +
  37 + static String url;
  38 + static List<GpsEntity> list;
  39 + static CloseableHttpClient httpClient = null;
  40 + static HttpGet get;
  41 + static RequestConfig requestConfig;
  42 + static CloseableHttpResponse response;
  43 + static HttpEntity entity;
  44 + static BufferedReader br;
  45 +
  46 + static GpsRealData gpsRealData;
  47 +
  48 + static{
  49 + url = ConfigUtil.get("http.gps.real.url");
  50 + list = new ArrayList<>();
  51 + httpClient = HttpClients.createDefault();
  52 + get = new HttpGet(url);
  53 + requestConfig = RequestConfig.custom()
  54 + .setConnectTimeout(2500).setConnectionRequestTimeout(2000)
  55 + .setSocketTimeout(2500).build();
  56 + get.setConfig(requestConfig);
  57 + }
  58 +
  59 + public static List<GpsEntity> load(){
  60 + try{
  61 + if(list.size() > 0)
  62 + list.clear();
  63 +
  64 + response = httpClient.execute(get);
  65 + entity = response.getEntity();
  66 +
  67 + if(null == entity)
  68 + return list;
  69 +
  70 + br = new BufferedReader(new InputStreamReader(entity.getContent()));
  71 +
  72 + StringBuilder sb = new StringBuilder();
  73 + String str;
  74 + while ((str = br.readLine()) != null)
  75 + sb.append(str);
  76 +
  77 + list = JSON.parseArray(JSON.parseObject(sb.toString()).getString("data"), GpsEntity.class);
  78 + //过滤掉无效的点位
  79 + list = GpsDataUtils.clearInvalid(list);
  80 +
  81 + List<GpsEntity> ups = new ArrayList<>();
  82 + String nbbm;
  83 + for (GpsEntity gps : list) {
  84 + if (StringUtils.isBlank(gps.getDeviceId()))
  85 + continue;
  86 +
  87 + if (gps_equals(gpsRealData.get(gps.getDeviceId()), gps))
  88 + continue;
  89 +
  90 + nbbm = BasicData.deviceId2NbbmMap.get(gps.getDeviceId());
  91 + gps.setNbbm(nbbm);
  92 + gps.setRealtime(true);
  93 + ups.add(gps);
  94 + }
  95 + list = ups;
  96 +
  97 + if (null != response)
  98 + response.close();
  99 + }catch (Exception e){
  100 + logger.error("", e);
  101 + }
  102 + return list;
  103 + }
  104 +
  105 +
  106 + private static boolean gps_equals(GpsEntity old, GpsEntity gps){
  107 + if(old != null &&
  108 + old.getTimestamp().equals(gps.getTimestamp()) &&
  109 + old.getLat().equals(gps.getLat()) &&
  110 + old.getLon().equals(gps.getLon()))
  111 + return true;
  112 + return false;
  113 + }
  114 +
  115 + @Override
  116 + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  117 + gpsRealData = applicationContext.getBean(GpsRealData.class);
  118 + }
  119 +}
src/main/java/com/bsth/data/schedule/thread/ScheduleRefreshThread.java
1 -package com.bsth.data.schedule.thread;  
2 -  
3 -import com.bsth.data.LineConfigData;  
4 -import com.bsth.data.directive.DayOfDirectives;  
5 -import com.bsth.data.gpsdata_v2.cache.GpsCacheData;  
6 -import com.bsth.data.pilot80.PilotReport;  
7 -import com.bsth.data.schedule.DayOfSchedule;  
8 -import com.bsth.data.schedule.f_a_l.FirstAndLastHandler;  
9 -import com.bsth.entity.realcontrol.LineConfig;  
10 -import org.slf4j.Logger;  
11 -import org.slf4j.LoggerFactory;  
12 -import org.springframework.beans.factory.annotation.Autowired;  
13 -import org.springframework.stereotype.Component;  
14 -  
15 -import java.util.Collection;  
16 -import java.util.Set;  
17 -  
18 -/**  
19 - *  
20 - * @ClassName: ScheduleRefreshThread  
21 - * @Description: TODO(班次刷新线程,用于在营运开始时间切换到当日排班)  
22 - * @author PanZhao  
23 - * @date 2016年8月17日 下午1:23:34  
24 - *  
25 - */  
26 -@Component  
27 -public class ScheduleRefreshThread extends Thread{  
28 -  
29 - @Autowired  
30 - DayOfSchedule dayOfSchedule;  
31 -  
32 - @Autowired  
33 - LineConfigData lineConfs;  
34 -  
35 - @Autowired  
36 - DayOfDirectives dayOfDirectives;  
37 -  
38 - @Autowired  
39 - PilotReport pilotReport;  
40 -  
41 - Logger logger = LoggerFactory.getLogger(ScheduleRefreshThread.class);  
42 -  
43 - @Override  
44 - public void run() {  
45 - try {  
46 - Collection<LineConfig> confs = lineConfs.getAll();  
47 -  
48 - String currSchDate, oldSchDate;  
49 - String lineCode = null;  
50 - for(LineConfig conf : confs){  
51 - try{  
52 - lineCode = conf.getLine().getLineCode();  
53 - oldSchDate = dayOfSchedule.getCurrSchDate().get(lineCode);  
54 - currSchDate = dayOfSchedule.calcSchDate(lineCode);  
55 -  
56 - if(oldSchDate == null || !oldSchDate.equals(currSchDate)){  
57 -  
58 - try{  
59 - Set<String> cars = dayOfSchedule.findCarByLineCode(lineCode);  
60 - for(String car : cars){  
61 - GpsCacheData.remove(car);  
62 - }  
63 - //清除驾驶员上报数据  
64 - pilotReport.clear(lineCode);  
65 - //清除指令数据 指令数据,直接定时全部清空  
66 - //dayOfDirectives.clear(lineCode);  
67 - }catch (Exception e){  
68 - logger.error("清理 60 和 80出现问题", e);  
69 - }  
70 -  
71 - //重载排班数据  
72 - dayOfSchedule.reloadSch(lineCode, currSchDate, false);  
73 - logger.info(lineCode + "翻班完成, " + currSchDate + " -班次数量:" + dayOfSchedule.findByLineCode(lineCode).size());  
74 - }  
75 - }catch (Exception e){  
76 - logger.error("班次更新失败!! -" + lineCode, e);  
77 - }  
78 - }  
79 -  
80 - //按公司编码索引数据  
81 - dayOfSchedule.groupByGsbm();  
82 -  
83 - //首末班入库(给网关用的数据)  
84 - FirstAndLastHandler.saveAll();  
85 - } catch (Exception e) {  
86 - logger.error("", e);  
87 - }  
88 - }  
89 -} 1 +package com.bsth.data.schedule.thread;
  2 +
  3 +import com.bsth.data.LineConfigData;
  4 +import com.bsth.data.directive.DayOfDirectives;
  5 +import com.bsth.data.gpsdata_v2.cache.GpsCacheData;
  6 +import com.bsth.data.pilot80.PilotReport;
  7 +import com.bsth.data.schedule.DayOfSchedule;
  8 +import com.bsth.data.schedule.f_a_l.FirstAndLastHandler;
  9 +import com.bsth.entity.realcontrol.LineConfig;
  10 +import org.slf4j.Logger;
  11 +import org.slf4j.LoggerFactory;
  12 +import org.springframework.beans.factory.annotation.Autowired;
  13 +import org.springframework.stereotype.Component;
  14 +
  15 +import java.util.Collection;
  16 +import java.util.Set;
  17 +
  18 +/**
  19 + *
  20 + * @ClassName: ScheduleRefreshThread
  21 + * @Description: TODO(班次刷新线程,用于在营运开始时间切换到当日排班)
  22 + * @author PanZhao
  23 + * @date 2016年8月17日 下午1:23:34
  24 + *
  25 + */
  26 +@Component
  27 +public class ScheduleRefreshThread extends Thread{
  28 +
  29 + @Autowired
  30 + DayOfSchedule dayOfSchedule;
  31 +
  32 + @Autowired
  33 + LineConfigData lineConfs;
  34 +
  35 + @Autowired
  36 + DayOfDirectives dayOfDirectives;
  37 +
  38 + @Autowired
  39 + PilotReport pilotReport;
  40 +
  41 + Logger logger = LoggerFactory.getLogger(ScheduleRefreshThread.class);
  42 +
  43 + @Override
  44 + public void run() {
  45 + try {
  46 + Collection<LineConfig> confs = lineConfs.getAll();
  47 +
  48 + String currSchDate, oldSchDate;
  49 + String lineCode = null;
  50 + for(LineConfig conf : confs){
  51 + try{
  52 + lineCode = conf.getLine().getLineCode();
  53 + oldSchDate = dayOfSchedule.getCurrSchDate().get(lineCode);
  54 + currSchDate = dayOfSchedule.calcSchDate(lineCode);
  55 +
  56 + if(oldSchDate == null || !oldSchDate.equals(currSchDate)){
  57 +
  58 + try{
  59 + Set<String> cars = dayOfSchedule.findCarByLineCode(lineCode);
  60 + for(String car : cars){
  61 + GpsCacheData.remove(car, true);
  62 + }
  63 + //清除驾驶员上报数据
  64 + pilotReport.clear(lineCode);
  65 + //清除指令数据 指令数据,直接定时全部清空
  66 + //dayOfDirectives.clear(lineCode);
  67 + }catch (Exception e){
  68 + logger.error("清理 60 和 80出现问题", e);
  69 + }
  70 +
  71 + //重载排班数据
  72 + dayOfSchedule.reloadSch(lineCode, currSchDate, false);
  73 + logger.info(lineCode + "翻班完成, " + currSchDate + " -班次数量:" + dayOfSchedule.findByLineCode(lineCode).size());
  74 + }
  75 + }catch (Exception e){
  76 + logger.error("班次更新失败!! -" + lineCode, e);
  77 + }
  78 + }
  79 +
  80 + //按公司编码索引数据
  81 + dayOfSchedule.groupByGsbm();
  82 +
  83 + //首末班入库(给网关用的数据)
  84 + FirstAndLastHandler.saveAll();
  85 + } catch (Exception e) {
  86 + logger.error("", e);
  87 + }
  88 + }
  89 +}
src/main/java/com/bsth/service/gps/GpsServiceImpl.java
1 -package com.bsth.service.gps;  
2 -  
3 -import com.bsth.common.ResponseCode;  
4 -import com.bsth.data.BasicData;  
5 -import com.bsth.data.forecast.entity.ArrivalEntity;  
6 -import com.bsth.data.gpsdata_v2.GpsRealData;  
7 -import com.bsth.data.gpsdata_v2.cache.GeoCacheData;  
8 -import com.bsth.data.gpsdata_v2.cache.GpsCacheData;  
9 -import com.bsth.data.gpsdata_v2.entity.GpsEntity;  
10 -import com.bsth.data.gpsdata_v2.utils.GeoUtils;  
11 -import com.bsth.data.pilot80.PilotReport;  
12 -import com.bsth.data.safe_driv.SafeDriv;  
13 -import com.bsth.data.safe_driv.SafeDrivCenter;  
14 -import com.bsth.data.schedule.DayOfSchedule;  
15 -import com.bsth.entity.directive.D80;  
16 -import com.bsth.entity.realcontrol.ScheduleRealInfo;  
17 -import com.bsth.repository.CarParkRepository;  
18 -import com.bsth.repository.StationRepository;  
19 -import com.bsth.repository.realcontrol.ScheduleRealInfoRepository;  
20 -import com.bsth.service.gps.entity.*;  
21 -import com.bsth.util.TransGPS;  
22 -import com.bsth.util.TransGPS.Location;  
23 -import com.bsth.util.db.DBUtils_MS;  
24 -import org.apache.commons.lang3.StringUtils;  
25 -import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
26 -import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
27 -import org.apache.poi.ss.usermodel.CellStyle;  
28 -import org.apache.poi.ss.usermodel.Row;  
29 -import org.apache.poi.ss.usermodel.Sheet;  
30 -import org.apache.poi.ss.usermodel.Workbook;  
31 -import org.joda.time.format.DateTimeFormat;  
32 -import org.joda.time.format.DateTimeFormatter;  
33 -import org.slf4j.Logger;  
34 -import org.slf4j.LoggerFactory;  
35 -import org.springframework.beans.factory.annotation.Autowired;  
36 -import org.springframework.dao.DataAccessException;  
37 -import org.springframework.jdbc.core.BeanPropertyRowMapper;  
38 -import org.springframework.jdbc.core.JdbcTemplate;  
39 -import org.springframework.stereotype.Service;  
40 -  
41 -import javax.servlet.http.HttpServletResponse;  
42 -import java.io.IOException;  
43 -import java.io.OutputStream;  
44 -import java.io.UnsupportedEncodingException;  
45 -import java.lang.reflect.Field;  
46 -import java.net.URLEncoder;  
47 -import java.sql.Connection;  
48 -import java.sql.PreparedStatement;  
49 -import java.sql.ResultSet;  
50 -import java.sql.SQLException;  
51 -import java.text.DecimalFormat;  
52 -import java.text.ParseException;  
53 -import java.text.SimpleDateFormat;  
54 -import java.util.*;  
55 -  
56 -@Service  
57 -public class GpsServiceImpl implements GpsService {  
58 - /**  
59 - * 历史gps查询最大范围 24小时  
60 - */  
61 - final static Long GPS_RANGE = 60 * 60 * 24L;  
62 -  
63 - /**  
64 - * jdbc  
65 - */  
66 - Connection conn = null;  
67 - PreparedStatement ps = null;  
68 - ResultSet rs = null;  
69 -  
70 - Logger logger = LoggerFactory.getLogger(this.getClass());  
71 -  
72 - @Autowired  
73 - GpsRealData gpsRealData;  
74 -  
75 - @Autowired  
76 - JdbcTemplate jdbcTemplate;  
77 -  
78 - @Autowired  
79 - DayOfSchedule dayOfSchedule;  
80 -  
81 - @Autowired  
82 - ScheduleRealInfoRepository scheduleRealInfoRepository;  
83 -  
84 - // 历史gps查询  
85 - @Override  
86 - public List<Map<String, Object>> history(String device, Long startTime, Long endTime, int directions) {  
87 - Calendar sCal = Calendar.getInstance();  
88 - sCal.setTime(new Date(startTime));  
89 -  
90 - Calendar eCal = Calendar.getInstance();  
91 - eCal.setTime(new Date(endTime));  
92 -  
93 - int dayOfYear = sCal.get(Calendar.DAY_OF_YEAR);  
94 - /*  
95 - * if(dayOfYear != eCal.get(Calendar.DAY_OF_YEAR)){  
96 - * System.out.println("暂时不支持跨天查询..."); return null; }  
97 - */  
98 -  
99 - String sql = "select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,STOP_NO from bsth_c_gps_info where days_year=? and device_id=? and ts > ? and ts < ?";  
100 - Connection conn = null;  
101 - PreparedStatement ps = null;  
102 - ResultSet rs = null;  
103 - List<Map<String, Object>> list = new ArrayList<>();  
104 - Map<String, Object> map = null;  
105 - try {  
106 - conn = DBUtils_MS.getConnection();  
107 - ps = conn.prepareStatement(sql);  
108 - ps.setInt(1, dayOfYear);  
109 - ps.setString(2, device);  
110 - ps.setLong(3, startTime);  
111 - ps.setLong(4, endTime);  
112 -  
113 - rs = ps.executeQuery();  
114 - Float lon, lat;  
115 - Location location;  
116 - int upDown;  
117 - while (rs.next()) {  
118 - upDown = getUpOrDown(rs.getLong("SERVICE_STATE"));  
119 - if (upDown != directions)  
120 - continue;  
121 -  
122 - // to 百度坐标  
123 - lon = rs.getFloat("LON");  
124 - lat = rs.getFloat("LAT");  
125 - location = TransGPS.LocationMake(lon, lat);  
126 - location = TransGPS.bd_encrypt(TransGPS.transformFromWGSToGCJ(location));  
127 -  
128 - map = new HashMap<>();  
129 - map.put("device", rs.getString("DEVICE_ID"));  
130 - map.put("lon", location.getLng());  
131 - map.put("lat", location.getLat());  
132 - map.put("ts", rs.getLong("TS"));  
133 - map.put("stopNo", rs.getString("STOP_NO"));  
134 - map.put("inout_stop", rs.getInt("INOUT_STOP"));  
135 - // 上下行  
136 - map.put("upDown", upDown);  
137 - list.add(map);  
138 - }  
139 - } catch (Exception e) {  
140 - e.printStackTrace();  
141 - } finally {  
142 - DBUtils_MS.close(rs, ps, conn);  
143 - }  
144 - return list;  
145 - }  
146 -  
147 - /**  
148 - * 王通 2016/6/29 9:23:24 获取车辆线路上下行  
149 - *  
150 - * @return -1无效 0上行 1下行  
151 - */  
152 - public static byte getUpOrDown(long serviceState) {  
153 - /*if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000  
154 - || (serviceState & 0x01000000) == 0x01000000 || (serviceState & 0x08000000) == 0x08000000)  
155 - return -1;*/  
156 - return (byte) (((serviceState & 0x10000000) == 0x10000000) ? 1 : 0);  
157 - }  
158 -  
159 - /**  
160 - * 获取运营状态  
161 - *  
162 - * @return -1无效 0运营 1未运营  
163 - */  
164 - public static byte getService(long serviceState) {  
165 - /*if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000)  
166 - return -1;*/  
167 - return (byte) (((serviceState & 0x02000000) == 0x02000000) ? 1 : 0);  
168 - }  
169 -  
170 - private static DateTimeFormatter fmtyyyy = DateTimeFormat.forPattern("yyyy");  
171 - @Override  
172 - public Map<String, Object> history(String[] nbbmArray, Long st, Long et) {  
173 - Map<String, Object> rsMap = new HashMap<>();  
174 - List<Map<String, Object>> list = new ArrayList<>();  
175 - rsMap.put("list", list);  
176 - if (et - st > GPS_RANGE)  
177 - return rsMap;  
178 -  
179 - st = st * 1000;  
180 - et = et * 1000;  
181 - // day_of_year 分区字段  
182 - Calendar sCal = Calendar.getInstance();  
183 - sCal.setTime(new Date(st));  
184 - int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR);  
185 - Calendar eCal = Calendar.getInstance();  
186 - eCal.setTime(new Date(et));  
187 - int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR);  
188 -  
189 - String nbbm = nbbmArray[0];  
190 -  
191 - List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);  
192 -  
193 - //按年分表  
194 - String tableName = "bsth_c_gps_info_" + fmtyyyy.print(st);  
195 -  
196 - StringBuilder sql = new StringBuilder("");  
197 - long t1,t2;  
198 - DeviceChange dc;  
199 - for(int i = 0,len=dcs.size(); i < len; i++){  
200 - t1 = st;  
201 - t2 = et;  
202 - dc = dcs.get(i);  
203 - if(dc.getSt() > st)  
204 - t1 = dc.getSt();  
205 - if(dc.getEt() < et && dc.getEt()!=0)  
206 - t2 = dc.getEt();  
207 -  
208 - sql.append("select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,STOP_NO,DIRECTION,LINE_ID,SPEED_GPS,SECTION_CODE from "+tableName+" where days_year in ("+sDayOfYear+","+eDayOfYear+") " +  
209 - " and device_id='"+dc.getDevice()+"' and ts >= "+t1+" and ts <= "+t2+" ");  
210 -  
211 - if(i == len - 1)  
212 - sql.append(" ORDER BY device_id,ts,stop_no");  
213 - else  
214 - sql.append(" UNION ");  
215 - }  
216 -  
217 - logger.info("轨迹回放 nbbm: " + nbbm + " -st: " + st + " -et: " + et + " -sql: " + sql.toString());  
218 -  
219 - // 查询到离站数据  
220 - Map<String, ArrivalEntity> arrivalMap = findArrivalByTs(st, et, dcs);  
221 -  
222 - //查询GPS数据  
223 - JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());  
224 - List<Map<String, Object>> dataList = jdbcTemplate_ms.queryForList(sql.toString());  
225 -  
226 - Float lon, lat;  
227 - Location bdLoc, gdLoc;  
228 - int inOutStop;  
229 - long serviceState;  
230 - ArrivalEntity arrival;  
231 -  
232 - Map<String, Object> map = null;  
233 - for(Map<String, Object> rs : dataList){  
234 - serviceState = map_get_long(rs, "SERVICE_STATE");  
235 - if(getGpsValid(serviceState) == 1)  
236 - continue;  
237 -  
238 - map = new HashMap<>();  
239 - lon = map_get_float(rs, "LON");  
240 - lat = map_get_float(rs, "LAT");  
241 - // 高德坐标  
242 - gdLoc = TransGPS.transformFromWGSToGCJ(TransGPS.LocationMake(lon, lat));  
243 - map.put("gcj_lon", gdLoc.getLng());  
244 - map.put("gcj_lat", gdLoc.getLat());  
245 - // 百度坐标  
246 - bdLoc = TransGPS.bd_encrypt(gdLoc);  
247 - map.put("bd_lon", bdLoc.getLng());  
248 - map.put("bd_lat", bdLoc.getLat());  
249 - //原始坐标  
250 - map.put("lon", lon);  
251 - map.put("lat", lat);  
252 -  
253 - map.put("deviceId", map_get_str(rs, "DEVICE_ID"));  
254 - map.put("ts", map_get_long(rs, "TS"));  
255 - map.put("timestamp", map_get_long(rs, "TS"));  
256 - map.put("stopNo", map_get_str(rs, "STOP_NO"));  
257 - map.put("direction", map_get_float(rs,"DIRECTION"));  
258 -  
259 - map.put("lineId", map_get_str(rs, "LINE_ID"));  
260 - map.put("speed", map_get_float(rs,"SPEED_GPS"));  
261 -  
262 - inOutStop = Integer.parseInt(rs.get("INOUT_STOP").toString());  
263 - map.put("inout_stop", inOutStop);  
264 -  
265 - arrival = arrivalMap.get(map_get_str(rs, "DEVICE_ID") + "_" + map_get_long(rs, "TS"));  
266 - if (arrival != null) {  
267 - map.put("inout_stop_info", arrival);  
268 - map.put("inout_stop", arrival.getInOut());  
269 - }  
270 -  
271 - //map.put("nbbm", nbbm);  
272 - map.put("state", getService(serviceState));  
273 - // 上下行  
274 - map.put("upDown", getUpOrDown(serviceState));  
275 - //路段编码  
276 - map.put("section_code", map_get_str(rs,"SECTION_CODE"));  
277 - list.add(map);  
278 - }  
279 - // 按时间排序  
280 - Collections.sort(list, new Comparator<Map<String, Object>>() {  
281 -  
282 - @Override  
283 - public int compare(Map<String, Object> o1, Map<String, Object> o2) {  
284 - return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));  
285 - }  
286 - });  
287 -  
288 - rsMap.put("list", list);  
289 - rsMap.put("dcs", dcs);  
290 - return rsMap;  
291 - }  
292 -  
293 - private String map_get_str(Map<String, Object> map, String key){  
294 - return map.containsKey(key)?map.get(key).toString():"";  
295 - }  
296 -  
297 - private Long map_get_long(Map<String, Object> map, String key){  
298 - return map.containsKey(key)?Long.parseLong(map.get(key).toString()):-1;  
299 - }  
300 -  
301 - private Float map_get_float(Map<String, Object> map, String key){  
302 - return map.containsKey(key)?Float.parseFloat(map.get(key).toString()):-1;  
303 - }  
304 -  
305 - private List<DeviceChange> findDeviceChangeLogs(String nbbm, long et, long st){  
306 - List<DeviceChange> dcs = null;  
307 - List<DeviceChange> rs = new ArrayList<>();  
308 - try{  
309 -  
310 - //JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());  
311 - dcs = jdbcTemplate.query("select cl_zbh as nbbm,new_device_no as device,old_device_no as old_device,UNIX_TIMESTAMP(qyrq) * 1000 as st from bsth_c_car_device where is_cancel=0 and cl_zbh='"+nbbm+"' order by qyrq"  
312 - , BeanPropertyRowMapper.newInstance(DeviceChange.class));  
313 -  
314 -  
315 - //生成一条初始记录  
316 - if(dcs.size() > 0){  
317 - DeviceChange first = dcs.get(0);  
318 -  
319 - DeviceChange initDv = new DeviceChange();  
320 - initDv.setDevice(first.getOldDevice());  
321 - if(StringUtils.isNotEmpty(initDv.getDevice())){  
322 - initDv.setNbbm(first.getNbbm());  
323 - initDv.setSt(0);  
324 - initDv.setEt(first.getSt());  
325 - dcs.add(0, initDv);  
326 - }  
327 - }  
328 - for(int i = 0,len=dcs.size(); i < len - 1; i++){  
329 - dcs.get(i).setEt(dcs.get(i + 1).getSt());  
330 - }  
331 -  
332 - for(DeviceChange dc : dcs){  
333 - if(dc.getEt() < st && dc.getEt() != 0)  
334 - continue;  
335 - if(dc.getSt() > et)  
336 - continue;  
337 -  
338 - rs.add(dc);  
339 - }  
340 -  
341 - //没有设备变更记录,则参考车辆信息上的设备号  
342 - if(null == rs || rs.size() == 0){  
343 - DeviceChange dc = new DeviceChange();  
344 - dc.setNbbm(nbbm);  
345 - dc.setDevice(BasicData.deviceId2NbbmMap.inverse().get(nbbm));  
346 - dc.setSt(st);  
347 - dc.setEt(et);  
348 - dc.setType(1);  
349 -  
350 - rs.add(dc);  
351 - }  
352 - }catch (Exception e){  
353 - logger.error("", e);  
354 - }  
355 - return rs;  
356 - }  
357 -  
358 - public static byte getGpsValid(long serviceState) {  
359 - return (byte)(((serviceState & 0x80000000) == 0x80000000) ? 1 : 0);  
360 - }  
361 -  
362 - public static void main(String[] args){  
363 - System.out.println(getGpsValid(-2147483648));  
364 - }  
365 -  
366 - public Map<String, ArrivalEntity> findArrivalByTs(Long st, Long et, List<DeviceChange> dcs) {  
367 - Map<String, ArrivalEntity> map = new HashMap<>();  
368 -  
369 - // weeks_year 分区字段  
370 - Calendar sCal = Calendar.getInstance();  
371 - sCal.setTime(new Date(st));  
372 - int sWeekOfYear = sCal.get(Calendar.WEEK_OF_YEAR);  
373 - Calendar eCal = Calendar.getInstance();  
374 - eCal.setTime(new Date(et));  
375 - int eWeekOfYear = eCal.get(Calendar.WEEK_OF_YEAR);  
376 -  
377 - //按年分表  
378 - String tableName = "bsth_c_arrival_info_" + fmtyyyy.print(st);  
379 -  
380 - StringBuilder sql = new StringBuilder("");  
381 - long t1,t2;  
382 - DeviceChange dc;  
383 - for(int i = 0,len=dcs.size(); i < len; i++){  
384 - t1 = st;  
385 - t2 = et;  
386 - dc = dcs.get(i);  
387 - if(dc.getSt() > st)  
388 - t1 = dc.getSt();  
389 - if(dc.getEt() < et && dc.getEt() != 0)  
390 - t2 = dc.getEt();  
391 -  
392 - sql.append("SELECT DEVICE_ID,LINE_ID as LINE_CODE,STOP_NO,TS,UP_DOWN,IN_OUT,WEEKS_YEAR,CREATE_DATE FROM " + tableName +  
393 - " where weeks_year in ("+sWeekOfYear+", "+eWeekOfYear+") and device_id='"+dc.getDevice()+"' and ts > "+t1+" and ts < " + t2);  
394 -  
395 - if(i == len - 1)  
396 - sql.append(" ORDER BY device_id,ts,stop_no ");  
397 - else  
398 - sql.append(" UNION ");  
399 - }  
400 -  
401 - logger.info("arrivl sql : " + sql.toString());  
402 - JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());  
403 - List<ArrivalEntity> list = jdbcTemplate_ms.query(sql.toString(), BeanPropertyRowMapper.newInstance(ArrivalEntity.class));  
404 -  
405 - String stationName, prefix;  
406 - for(ArrivalEntity arr : list){  
407 - prefix = arr.getLineCode() + "_" + arr.getUpDown() + "_";  
408 - stationName = BasicData.getStationNameByCode(arr.getStopNo(), prefix);  
409 -  
410 - arr.setStopName(stationName);  
411 -  
412 - // 反转进出状态  
413 - map.put(arr.getDeviceId() + "_" + arr.getTs(), arr);  
414 - }  
415 - return map;  
416 - }  
417 -  
418 -  
419 - @Autowired  
420 - StationRepository stationRepository;  
421 -  
422 - @Autowired  
423 - CarParkRepository carParkRepository;  
424 -  
425 - @Override  
426 - public Map<String, Object> findBuffAeraByCode(String code, String type) {  
427 - Object[][] obj = null;  
428 - if (type.equals("station"))  
429 - obj = stationRepository.bufferAera(code);  
430 - else if (type.equals("park"))  
431 - obj = carParkRepository.bufferAera(code);  
432 -  
433 - Map<String, Object> rs = new HashMap<>();  
434 -  
435 - Object[] subObj = obj[0];  
436 - if (subObj != null && subObj.length == 6) {  
437 - rs.put("polygon", subObj[0]);  
438 - rs.put("type", subObj[1]);  
439 - rs.put("cPoint", subObj[2]);  
440 - rs.put("radius", subObj[3]);  
441 - rs.put("code", subObj[4]);  
442 - rs.put("text", subObj[5]);  
443 - }  
444 -  
445 - return rs;  
446 - }  
447 -  
448 - @Override  
449 - public Map<String, Object> search(Map<String, Object> map, int page, int size, String order, String direction) {  
450 - Map<String, Object> rsMap = new HashMap<>();  
451 - try {  
452 - //全量  
453 - List<GpsEntity> list = new ArrayList<>(gpsRealData.all());  
454 - //过滤后的  
455 - List<GpsEntity> rs = new ArrayList<>();  
456 - Field[] fields = GpsEntity.class.getDeclaredFields();  
457 - //参与过滤的字段  
458 - List<Field> fs = new ArrayList<>();  
459 - for (Field f : fields) {  
460 - f.setAccessible(true);  
461 - if (map.containsKey(f.getName()))  
462 - fs.add(f);  
463 - }  
464 - //过滤数据  
465 - for (GpsEntity gps : list) {  
466 - if (fieldEquals(fs, gps, map))  
467 - rs.add(gps);  
468 - }  
469 -  
470 - //时间戳排序  
471 - Collections.sort(rs, new Comparator<GpsEntity>() {  
472 - @Override  
473 - public int compare(GpsEntity o1, GpsEntity o2) {  
474 - return o2.getTimestamp().intValue() - o1.getTimestamp().intValue();  
475 - }  
476 - });  
477 -  
478 - //分页  
479 - int count = rs.size(), s = page * size, e = s + size;  
480 - if (e > count)  
481 - e = count;  
482 -  
483 - rsMap.put("list", rs.subList(s, e));  
484 - rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);  
485 - rsMap.put("page", page);  
486 - rsMap.put("status", ResponseCode.SUCCESS);  
487 - } catch (Exception e) {  
488 - logger.error("", e);  
489 - rsMap.put("status", ResponseCode.ERROR);  
490 - }  
491 - return rsMap;  
492 - }  
493 -  
494 - @Override  
495 - public Map<String, Object> removeRealGps(String device) {  
496 - Map<String, Object> rs = new HashMap<>();  
497 - try {  
498 -  
499 - gpsRealData.remove(device);  
500 - GpsCacheData.remove(BasicData.deviceId2NbbmMap.get(device));  
501 - rs.put("status", ResponseCode.SUCCESS);  
502 - } catch (Exception e) {  
503 - rs.put("status", ResponseCode.ERROR);  
504 - }  
505 - return rs;  
506 - }  
507 -  
508 - @Override  
509 - public Map<String, Object> findRoadSpeed(String lineCode) {  
510 - Map<String, Object> rs = new HashMap<>();  
511 -  
512 - try {  
513 - String sql = "select ID, ST_AsText(GROAD_VECTOR) as GROAD_VECTOR,ROAD_CODE,ROAD_NAME,SPEED from bsth_c_road where road_code in(select section_code from bsth_c_sectionroute where line_code=? and destroy=0)";  
514 - List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, lineCode);  
515 - rs.put("status", ResponseCode.SUCCESS);  
516 - rs.put("roads", list);  
517 - } catch (DataAccessException e) {  
518 - logger.error("", e);  
519 - rs.put("status", ResponseCode.ERROR);  
520 - }  
521 - return rs;  
522 - }  
523 -  
524 - /**  
525 - * gps补全  
526 - *  
527 - * @param schId  
528 - * @return  
529 - */  
530 - @Override  
531 - public Map<String, Object> gpsCompletion(long schId, int type) {  
532 - Map<String, Object> rs = new HashMap<>();  
533 -  
534 - try {  
535 - ScheduleRealInfo sch = dayOfSchedule.get(schId);  
536 - if (sch == null) {  
537 - rs.put("status", ResponseCode.ERROR);  
538 - rs.put("msg", "找不到对应班次!!!");  
539 - return rs;  
540 - }  
541 -  
542 - if (sch.isReissue()) {  
543 - rs.put("status", ResponseCode.ERROR);  
544 - rs.put("msg", "你不能重复这个操作");  
545 - return rs;  
546 - }  
547 -  
548 - String sql = "select * from bsth_gps_template where line_id='" + sch.getXlBm() + "' and up_down=" + sch.getXlDir();  
549 - List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);  
550 -  
551 - if (list.size() == 0) {  
552 - rs.put("status", ResponseCode.ERROR);  
553 - rs.put("msg", "缺少模板数据,请联系系统管理员!!");  
554 - return rs;  
555 - }  
556 - //排序  
557 - Collections.sort(list, new Comparator<Map<String, Object>>() {  
558 - @Override  
559 - public int compare(Map<String, Object> o1, Map<String, Object> o2) {  
560 - return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));  
561 - }  
562 - });  
563 - Map<String, Object> fs = list.get(0);  
564 - //替换设备号和时间  
565 - long diff = ((sch.getDfsjT() - Long.parseLong(fs.get("ts").toString())) - 1000 * 70);  
566 -  
567 - String deviceId = BasicData.deviceId2NbbmMap.inverse().get(sch.getClZbh());  
568 - int serviceState;  
569 - for (Map<String, Object> map : list) {  
570 - map.put("device_id", deviceId);  
571 - map.put("ts", Long.parseLong(map.get("ts").toString()) + diff);  
572 - if(type==1){  
573 - //走补传协议  
574 - serviceState = Integer.parseInt(map.get("service_state").toString());  
575 - map.put("service_state", serviceState |= 0x00100000);  
576 - }  
577 - }  
578 -  
579 - String sqlBefore = "insert into bsth_c_template(", sqlValues = " values(";  
580 -  
581 - Set<String> ks = fs.keySet();  
582 - for (String k : ks) {  
583 - sqlBefore += (k + ",");  
584 - sqlValues += "?,";  
585 - }  
586 - sqlBefore = sqlBefore.substring(0, sqlBefore.length() - 1) + ", create_ts)";  
587 - sqlValues = sqlValues.substring(0, sqlValues.length() - 1) + ", " + System.currentTimeMillis() + ")";  
588 - sql = sqlBefore + " " + sqlValues;  
589 -  
590 - Connection conn = DBUtils_MS.getConnection();  
591 - conn.setAutoCommit(false);  
592 - ps = conn.prepareStatement(sql);  
593 - int fsize = ks.size();  
594 - List<Object> vs;  
595 - for (Map<String, Object> map : list) {  
596 - vs = new ArrayList<>(map.values());  
597 - for (int i = 0; i < fsize; i++) {  
598 - ps.setObject(i + 1, vs.get(i));  
599 - }  
600 - ps.addBatch();  
601 - }  
602 - ps.executeBatch();  
603 - conn.commit();  
604 -  
605 - rs.put("status", ResponseCode.SUCCESS);  
606 -  
607 - //标记班次  
608 - sch.setReissue(true);  
609 - scheduleRealInfoRepository.save(sch);  
610 -  
611 - rs.put("status", ResponseCode.SUCCESS);  
612 - } catch (Exception e) {  
613 - logger.error("", e);  
614 - rs.put("status", ResponseCode.ERROR);  
615 - }  
616 - return rs;  
617 - }  
618 -  
619 - @Override  
620 - public Map<String, Object> history_v2(String nbbm, long st, long et) {  
621 - Map<String, Object> rs = new HashMap<>();  
622 -  
623 - try {  
624 - //获取历史gps 数据  
625 - List<HistoryGps_DTO> list = HistoryGps_DTO.craete((List<Map<String, Object>>) history(new String[]{nbbm}, st, et).get("list"));  
626 - if (list != null && list.size() > 0) {  
627 - //获取路段信息  
628 - String sql = "select ID, ST_AsText(GROAD_VECTOR) as GROAD_VECTOR,ROAD_CODE,ROAD_NAME,SPEED from bsth_c_road where road_code in(select section_code from bsth_c_sectionroute where line_code=? and destroy=0)";  
629 - List<Road_DTO> roads = Road_DTO.craete(jdbcTemplate.queryForList(sql, list.get(0).getLineId()));  
630 -  
631 - //为GPS数据关联路段信息  
632 - for (HistoryGps_DTO gps : list) {  
633 - matchRoadToGps(gps, roads);  
634 - }  
635 - }  
636 -  
637 - //超速数据  
638 - List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);  
639 - //越界数据  
640 - List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);  
641 - //计算里程  
642 - List<HistoryGps_DTO> effList = new ArrayList<>();  
643 - for(HistoryGps_DTO gps : list){  
644 - if(gps.getLat() != 0 && gps.getLon() != 0)  
645 - effList.add(gps);  
646 - }  
647 - double sum = 0, dist;  
648 - for (int i = 0; i < effList.size() - 1; i++) {  
649 - dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());  
650 - //点位相同时,dist会NaN  
651 - if(String.valueOf(dist).matches("^[0.0-9.0]+$"))  
652 - sum += dist;  
653 - }  
654 -  
655 - rs.put("status", ResponseCode.SUCCESS);  
656 - rs.put("list", removeDuplicate(effList));  
657 - rs.put("speedList", speedList);  
658 - rs.put("outboundList", outboundList);  
659 - rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));  
660 - } catch (Exception e) {  
661 - logger.error("", e);  
662 - rs.put("status", ResponseCode.ERROR);  
663 - }  
664 - return rs;  
665 - }  
666 -  
667 -  
668 - @Override  
669 - public Map<String, Object> history_v3(String nbbm, long st, long et) {  
670 - Map<String, Object> rs = new HashMap<>();  
671 -  
672 - try {  
673 - //获取历史gps 数据  
674 - Map<String, Object> gpsMap = history(new String[]{nbbm}, st, et);  
675 - List<HistoryGps_DTOV3> list = HistoryGps_DTOV3.craete((List<Map<String, Object>>) gpsMap.get("list"));  
676 - if (list != null && list.size() > 0) {  
677 - //关联路段名称  
678 - Map<String, String> sectionCode2Name = GeoCacheData.sectionCode2NameMap();  
679 - for(HistoryGps_DTOV3 gps : list){  
680 - if(StringUtils.isNotEmpty(gps.getSection_code()))  
681 - gps.setSection_name(sectionCode2Name.get(gps.getSection_code()));  
682 - else{  
683 - gps.setSection_code("-00404");  
684 - gps.setSection_name("未知路段");  
685 - }  
686 - }  
687 - }  
688 -  
689 - //超速数据  
690 - List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);  
691 -  
692 - //越界数据  
693 - List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);  
694 -  
695 - //计算里程  
696 - List<HistoryGps_DTOV3> effList = new ArrayList<>();  
697 - for(HistoryGps_DTOV3 gps : list){  
698 - if(gps.getLat() != 0 && gps.getLon() != 0)  
699 - effList.add(gps);  
700 - }  
701 - double sum = 0, dist;  
702 - for (int i = 0; i < effList.size() - 1; i++) {  
703 - dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());  
704 - //点位相同时,dist会NaN  
705 - if(String.valueOf(dist).matches("^[0.0-9.0]+$")){  
706 - if(dist > 0.8)  
707 - sum += dist;  
708 - }  
709 - }  
710 -  
711 - rs.put("status", ResponseCode.SUCCESS);  
712 - rs.put("list", removeDuplicateV3(effList));  
713 - rs.put("speedList", speedList);  
714 - rs.put("outboundList", outboundList);  
715 - rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));  
716 - rs.put("dcs", gpsMap.get("dcs"));  
717 - } catch (Exception e) {  
718 - logger.error("", e);  
719 - rs.put("status", ResponseCode.ERROR);  
720 - rs.put("msg", e.getMessage());  
721 - }  
722 - return rs;  
723 - }  
724 -  
725 - @Override  
726 - public void trailExcel(String nbbm, long st, long et, HttpServletResponse resp) {  
727 - //获取历史gps 数据  
728 - List<HistoryGps_DTOV3> list = HistoryGps_DTOV3.craete((List<Map<String, Object>>) history(new String[]{nbbm}, st, et).get("list"));  
729 - if (list != null && list.size() > 0) {  
730 - //关联路段名称  
731 - Map<String, String> sectionCode2Name = GeoCacheData.sectionCode2NameMap();  
732 - for(HistoryGps_DTOV3 gps : list){  
733 - if(StringUtils.isNotEmpty(gps.getSection_code()))  
734 - gps.setSection_name(sectionCode2Name.get(gps.getSection_code()));  
735 - else{  
736 - gps.setSection_code("-00404");  
737 - gps.setSection_name("未知路段");  
738 - }  
739 - }  
740 - }  
741 -  
742 - //创建excel工作簿  
743 - Workbook wb = new HSSFWorkbook();  
744 - Sheet sheet = wb.createSheet("行车轨迹");  
745 - //表头  
746 - Row row = sheet.createRow(0);  
747 - row.setHeight((short) (1.5 * 256));  
748 - row.createCell(0).setCellValue("序号");  
749 - row.createCell(1).setCellValue("车辆");  
750 - row.createCell(2).setCellValue("牌照号");  
751 - row.createCell(3).setCellValue("所在道路");  
752 - row.createCell(4).setCellValue("经度");  
753 - row.createCell(5).setCellValue("纬度");  
754 - row.createCell(6).setCellValue("时间");  
755 - row.createCell(7).setCellValue("速度");  
756 - //数据  
757 - DateTimeFormatter fmtHHmmss = DateTimeFormat.forPattern("HH:mm.ss"),  
758 - fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");  
759 - HistoryGps_DTOV3 gps;  
760 - for(int i = 0; i < list.size(); i ++){  
761 - gps = list.get(i);  
762 - row = sheet.createRow(i + 1);  
763 - row.createCell(0).setCellValue(i + 1);  
764 - row.createCell(1).setCellValue(nbbm);  
765 - row.createCell(2).setCellValue(BasicData.nbbmCompanyPlateMap.get(nbbm));  
766 - row.createCell(3).setCellValue(gps.getSection_name());  
767 - row.createCell(4).setCellValue(gps.getLon());  
768 - row.createCell(5).setCellValue(gps.getLat());  
769 - row.createCell(6).setCellValue(fmtHHmmss.print(gps.getTimestamp()));  
770 - row.createCell(7).setCellValue(gps.getSpeed());  
771 - }  
772 -  
773 - st = st * 1000;  
774 - et = et * 1000;  
775 - String filename = nbbm + "轨迹数据" + fmt.print(st) + "至" + fmt.print(et) + ".xls";  
776 - try {  
777 - resp.setContentType("application/x-msdownload");  
778 - resp.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));  
779 -  
780 - OutputStream out=resp.getOutputStream();  
781 - wb.write(out);  
782 - out.flush();  
783 - out.close();  
784 - } catch (UnsupportedEncodingException e) {  
785 - logger.error("", e);  
786 - } catch (IOException e) {  
787 - logger.error("", e);  
788 - }  
789 - }  
790 -  
791 - @Override  
792 - public void abnormalExcel(String nbbm, long st, long et, HttpServletResponse resp) {  
793 - //超速数据  
794 - List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);  
795 - //越界数据  
796 - List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);  
797 -  
798 - //创建excel工作簿  
799 - Workbook wb = new HSSFWorkbook();  
800 -  
801 - DateTimeFormatter fmtHHmmss = DateTimeFormat.forPattern("HH:mm.ss"),  
802 - fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");  
803 - if(speedList.size() > 0){  
804 - Sheet sheet = wb.createSheet("超速");  
805 - //表头  
806 - Row row = sheet.createRow(0);  
807 - row.setHeight((short) (1.5 * 256));  
808 - row.createCell(0).setCellValue("异常信息");  
809 - row.createCell(1).setCellValue("最大速度");  
810 - row.createCell(2).setCellValue("开始时间");  
811 - row.createCell(3).setCellValue("结束时间");  
812 - row.createCell(4).setCellValue("持续(秒)");  
813 - row.createCell(5).setCellValue("所在路段");  
814 -  
815 - GpsSpeed_DTO speed;  
816 - for(int i = 0; i < speedList.size(); i++){  
817 - speed = speedList.get(i);  
818 - row = sheet.createRow(i + 1);  
819 - row.createCell(0).setCellValue("超速");  
820 - row.createCell(1).setCellValue(speed.getSpeed());  
821 - row.createCell(2).setCellValue(fmtHHmmss.print(speed.getSt()));  
822 - row.createCell(3).setCellValue(fmtHHmmss.print(speed.getEt()));  
823 - if(speed.getEt() != 0)  
824 - row.createCell(4).setCellValue((speed.getEt() - speed.getSt()) / 1000);  
825 - row.createCell(5).setCellValue("");  
826 - }  
827 - }  
828 -  
829 - if(outboundList.size() > 0){  
830 - Sheet sheet = wb.createSheet("越界");  
831 - //表头  
832 - Row row = sheet.createRow(0);  
833 - row.setHeight((short) (1.5 * 256));  
834 - row.createCell(0).setCellValue("异常信息");  
835 - row.createCell(1).setCellValue("开始时间");  
836 - row.createCell(2).setCellValue("结束时间");  
837 - row.createCell(3).setCellValue("持续(秒)");  
838 - row.createCell(4).setCellValue("所在路段");  
839 - row.createCell(5).setCellValue("路径");  
840 -  
841 - GpsOutbound_DTO outbound;  
842 - //设置路径单元格 水平对齐 填充  
843 - CellStyle cs = wb.createCellStyle();  
844 - cs.setAlignment(HSSFCellStyle.ALIGN_FILL);  
845 - for(int i = 0; i < outboundList.size(); i++){  
846 - outbound = outboundList.get(i);  
847 - row = sheet.createRow(i + 1);  
848 - row.createCell(0).setCellValue("超速");  
849 - row.createCell(1).setCellValue(fmtHHmmss.print(outbound.getSt()));  
850 - row.createCell(2).setCellValue(fmtHHmmss.print(outbound.getEt()));  
851 - if(outbound.getEt() != 0)  
852 - row.createCell(3).setCellValue((outbound.getEt() - outbound.getSt()) / 1000);  
853 - row.createCell(4).setCellValue("");  
854 - row.createCell(5).setCellValue(outbound.getLocations());  
855 -  
856 - row.getCell(5).setCellStyle(cs);  
857 - }  
858 - }  
859 -  
860 - st = st * 1000;  
861 - et = et * 1000;  
862 - String filename = nbbm + "异常信息" + fmt.print(st) + "至" + fmt.print(et) + ".xls";  
863 - try {  
864 - resp.setContentType("application/x-msdownload");  
865 - resp.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));  
866 -  
867 - OutputStream out=resp.getOutputStream();  
868 - wb.write(out);  
869 - out.flush();  
870 - out.close();  
871 - } catch (UnsupportedEncodingException e) {  
872 - logger.error("", e);  
873 - } catch (IOException e) {  
874 - logger.error("", e);  
875 - }  
876 - }  
877 -  
878 - @Override  
879 - public void arrivalExcel(String nbbm, long st, long et, HttpServletResponse resp) {  
880 -  
881 - }  
882 -  
883 - @Override  
884 - public List<GpsSpeed_DTO> speeds(String nbbm, long st, long et) {  
885 - st = st * 1000;  
886 - et = et * 1000;  
887 - //按周分区  
888 - Calendar sCal = Calendar.getInstance();  
889 - sCal.setTime(new Date(st));  
890 - int sWeekYear = sCal.get(Calendar.WEEK_OF_YEAR);  
891 - Calendar eCal = Calendar.getInstance();  
892 - eCal.setTime(new Date(et));  
893 - int eWeekYear = eCal.get(Calendar.WEEK_OF_YEAR);  
894 -  
895 - //按年分表  
896 - String tableName = "bsth_c_speeding_" + fmtyyyy.print(st);  
897 -  
898 - List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);  
899 - StringBuilder sql = new StringBuilder("");  
900 - long t1,t2;  
901 - DeviceChange dc;  
902 - for(int i = 0,len=dcs.size(); i < len; i++){  
903 - t1 = st;  
904 - t2 = et;  
905 - dc = dcs.get(i);  
906 - if(dc.getSt() > st)  
907 - t1 = dc.getSt();  
908 - if(dc.getEt() < et && dc.getEt()!=0)  
909 - t2 = dc.getEt();  
910 -  
911 - sql.append(" select vehicle, line, up_down, lon, lat, speed,timestamp from "+tableName+" where " +  
912 - " weeks_year in ("+sWeekYear+", "+eWeekYear+") and vehicle='"+dc.getDevice()+"' and timestamp>="+t1+" and timestamp<= " + t2);  
913 -  
914 - if(i == len - 1)  
915 - sql.append(" ORDER BY vehicle,timestamp");  
916 - else  
917 - sql.append(" UNION ");  
918 - }  
919 -  
920 - logger.info("speed sql : " + sql.toString());  
921 - return GpsSpeed_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql.toString()));  
922 - }  
923 -  
924 - @Override  
925 - public List<GpsOutbound_DTO> outbounds(String nbbm, long st, long et) {  
926 - st = st * 1000;  
927 - et = et * 1000;  
928 - //按周分区  
929 - Calendar sCal = Calendar.getInstance();  
930 - sCal.setTime(new Date(st));  
931 - int sWeekYear = sCal.get(Calendar.WEEK_OF_YEAR);  
932 - Calendar eCal = Calendar.getInstance();  
933 - eCal.setTime(new Date(et));  
934 - int eWeekYear = eCal.get(Calendar.WEEK_OF_YEAR);  
935 -  
936 - //按年分表  
937 - String tableName = "bsth_c_outbound_" + fmtyyyy.print(st);  
938 -  
939 - List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);  
940 - StringBuilder sql = new StringBuilder("");  
941 - long t1,t2;  
942 - DeviceChange dc;  
943 - for(int i = 0,len=dcs.size(); i < len; i++){  
944 - t1 = st;  
945 - t2 = et;  
946 - dc = dcs.get(i);  
947 - if(dc.getSt() > st)  
948 - t1 = dc.getSt();  
949 - if(dc.getEt() < et && dc.getEt()!=0)  
950 - t2 = dc.getEt();  
951 -  
952 - sql.append("select vehicle,line,up_down,lon,lat,timestamp from "+tableName+" where " +  
953 - " weeks_year in ("+sWeekYear+", "+eWeekYear+") and vehicle='"+dc.getDevice()+"' and timestamp>="+t1+" and timestamp<=" + t2);  
954 -  
955 - if(i == len - 1)  
956 - sql.append(" ORDER BY vehicle,timestamp");  
957 - else  
958 - sql.append(" UNION ");  
959 - }  
960 -  
961 - logger.info("outbounds sql : " + sql.toString());  
962 - return GpsOutbound_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql.toString()));  
963 - }  
964 -  
965 - @Override  
966 - public Map<String, Object> safeDrivList(Map<String, Object> map, int page, int size, String order, String direction) {  
967 - Map<String, Object> rsMap = new HashMap<>();  
968 - try {  
969 - //全量  
970 - List<SafeDriv> list = new ArrayList<>(SafeDrivCenter.findAll());  
971 - //过滤后的  
972 - List<SafeDriv> rs = new ArrayList<>();  
973 - Field[] fields = SafeDriv.class.getDeclaredFields();  
974 - //参与过滤的字段  
975 - List<Field> fs = new ArrayList<>();  
976 - for (Field f : fields) {  
977 - f.setAccessible(true);  
978 - if (map.containsKey(f.getName()))  
979 - fs.add(f);  
980 - }  
981 - //过滤数据  
982 - for (SafeDriv sd : list) {  
983 - if (fieldEquals(fs, sd, map))  
984 - rs.add(sd);  
985 - }  
986 -  
987 - //时间戳排序  
988 - Collections.sort(rs, new Comparator<SafeDriv>() {  
989 - @Override  
990 - public int compare(SafeDriv o1, SafeDriv o2) {  
991 - return o2.getTs().intValue() - o1.getTs().intValue();  
992 - }  
993 - });  
994 -  
995 - //分页  
996 - int count = rs.size(), s = page * size, e = s + size;  
997 - if (e > count)  
998 - e = count;  
999 -  
1000 - rsMap.put("list", rs.subList(s, e));  
1001 - rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);  
1002 - rsMap.put("page", page);  
1003 - rsMap.put("status", ResponseCode.SUCCESS);  
1004 - } catch (Exception e) {  
1005 - logger.error("", e);  
1006 - rsMap.put("status", ResponseCode.ERROR);  
1007 - }  
1008 - return rsMap;  
1009 - }  
1010 -  
1011 - private void matchRoadToGps(HistoryGps_DTO gps, List<Road_DTO> roads) {  
1012 - double min = -1, distance;  
1013 - Road_DTO nearRoad = null;  
1014 - for (Road_DTO road : roads) {  
1015 - distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());  
1016 -  
1017 - if (min > distance || min == -1) {  
1018 - min = distance;  
1019 - nearRoad = road;  
1020 - }  
1021 - }  
1022 -  
1023 - gps.setRoad(nearRoad);  
1024 - gps.setRoadMinDistance(min);  
1025 - }  
1026 -  
1027 -  
1028 - private void matchRoadToGps(HistoryGps_DTOV3 gps, List<Road_DTO> roads) {  
1029 - double min = -1, distance;  
1030 - Road_DTO nearRoad = null;  
1031 - for (Road_DTO road : roads) {  
1032 - distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());  
1033 -  
1034 - if (min > distance || min == -1) {  
1035 - min = distance;  
1036 - nearRoad = road;  
1037 - }  
1038 - }  
1039 -  
1040 - if(min < 200){  
1041 - gps.setSection_code(nearRoad.getROAD_CODE());  
1042 - gps.setSection_name(nearRoad.getROAD_NAME());  
1043 - }  
1044 - else {  
1045 - gps.setSection_code("-00404");  
1046 - gps.setSection_name("未知路段");  
1047 - }  
1048 - //gps.setRoad(nearRoad);  
1049 - //gps.setRoadMinDistance(min);  
1050 - }  
1051 -  
1052 - /**  
1053 - * 去重复  
1054 - *  
1055 - * @param list  
1056 - * @return  
1057 - */  
1058 - private Set<HistoryGps_DTO> removeDuplicate(List<HistoryGps_DTO> list) {  
1059 - Set<HistoryGps_DTO> set = new HashSet<>();  
1060 - for (HistoryGps_DTO gps : list) {  
1061 - set.add(gps);  
1062 - }  
1063 - return set;  
1064 - }  
1065 -  
1066 - /**  
1067 - * 去重复  
1068 - *  
1069 - * @param list  
1070 - * @return  
1071 - */  
1072 - private Set<HistoryGps_DTOV3> removeDuplicateV3(List<HistoryGps_DTOV3> list) {  
1073 - Set<HistoryGps_DTOV3> set = new HashSet<>();  
1074 - for (HistoryGps_DTOV3 gps : list) {  
1075 - set.add(gps);  
1076 - }  
1077 - return set;  
1078 - }  
1079 -  
1080 -  
1081 - private void sortGpsList(final Field f, List<GpsEntity> rs) {  
1082 - Collections.sort(rs, new Comparator<GpsEntity>() {  
1083 -  
1084 - @Override  
1085 - public int compare(GpsEntity o1, GpsEntity o2) {  
1086 - try {  
1087 - if (f.get(o1) == f.get(o2))  
1088 - return 0;  
1089 -  
1090 - if (null == f.get(o1))  
1091 - return 1;  
1092 -  
1093 - if (null == f.get(o2))  
1094 - return -1;  
1095 -  
1096 - return f.get(o1).toString().compareTo(f.get(o2).toString());  
1097 - } catch (Exception e) {  
1098 - logger.error("", e);  
1099 - return -1;  
1100 - }  
1101 - }  
1102 - });  
1103 - }  
1104 -  
1105 - public boolean fieldEquals(List<Field> fs, Object obj, Map<String, Object> map) {  
1106 - try {  
1107 - String fv, v;  
1108 - for (Field f : fs) {  
1109 - if (StringUtils.isEmpty(map.get(f.getName()).toString()))  
1110 - continue;  
1111 -  
1112 - if(f.get(obj) == null)  
1113 - return false;  
1114 -  
1115 - fv = f.get(obj).toString();  
1116 - v = map.get(f.getName()).toString();  
1117 -  
1118 - if(!fv.startsWith(v)/* && !fv.endsWith(v)*/)  
1119 - return false;  
1120 - }  
1121 - } catch (Exception e) {  
1122 - logger.error("", e);  
1123 - return false;  
1124 - }  
1125 - return true;  
1126 - }  
1127 -  
1128 - @Override  
1129 - public List<GpsSpeed> findPosition(String deviceid, String startdate,  
1130 - String enddate) throws ParseException{  
1131 - SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
1132 - Calendar c = Calendar.getInstance();  
1133 - Date date = sdf.parse(startdate);  
1134 - c.setTime(date);  
1135 - int daysYear = c.get(Calendar.DAY_OF_YEAR);//获取当前是今年的第几天。  
1136 -  
1137 - long startTime = sdf.parse(startdate).getTime();  
1138 - long endTime = sdf.parse(enddate).getTime();  
1139 -  
1140 - String sql = "select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,speed_gps from bsth_c_gps_info where days_year=? and device_id=? and ts >= ? and ts <= ?" +  
1141 - " ORDER BY TS ";  
1142 - Connection conn = null;  
1143 - PreparedStatement ps = null;  
1144 - ResultSet rs = null;  
1145 - List<GpsSpeed> listResult = new ArrayList<GpsSpeed>();  
1146 - GpsSpeed gpsSpeed = null;  
1147 - try {  
1148 - conn = DBUtils_MS.getConnection();  
1149 - ps = conn.prepareStatement(sql);  
1150 - ps.setInt(1, daysYear);  
1151 - ps.setString(2, deviceid);  
1152 - ps.setLong(3,startTime);  
1153 - ps.setLong(4,endTime);  
1154 - rs = ps.executeQuery();  
1155 - Float lon, lat;  
1156 - Location location;  
1157 - while (rs.next()) {  
1158 - gpsSpeed = new GpsSpeed();  
1159 - // to 百度坐标  
1160 - lon = rs.getFloat("LON");  
1161 - lat = rs.getFloat("LAT");  
1162 - location = TransGPS.LocationMake(lon, lat);  
1163 - location = TransGPS.bd_encrypt(TransGPS.transformFromWGSToGCJ(location));  
1164 - gpsSpeed.setVehicle(rs.getString("device_id"));  
1165 - gpsSpeed.setLon((float)location.getLng());  
1166 - gpsSpeed.setLat((float)location.getLat());  
1167 - gpsSpeed.setSpeed(rs.getFloat("speed_gps"));  
1168 - gpsSpeed.setTimestamp(rs.getLong("TS"));  
1169 - // 上下行  
1170 - listResult.add(gpsSpeed);  
1171 - }  
1172 - } catch (Exception e) {  
1173 - e.printStackTrace();  
1174 - } finally {  
1175 - DBUtils_MS.close(rs, ps, conn);  
1176 - }  
1177 - return listResult;  
1178 -  
1179 - }  
1180 -  
1181 - @Override  
1182 - public Map<String, Object> Pagequery(Map<String, Object> map) {  
1183 - SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
1184 - Integer totalDays = 0;//数据跨越天数  
1185 - try {  
1186 - totalDays = (int) ((sdf.parse(map.get("endDate").toString()+" 23:59:59").getTime()-sdf.parse(map.get("startDate").toString()+" 00:00:00").getTime()+1)/(3600*24*1000))+1;  
1187 - } catch (ParseException e) {  
1188 - e.printStackTrace();  
1189 - }//总页数  
1190 - map.put("totalDays",totalDays);  
1191 - List<GpsSpeed> list=findAll(map);  
1192 - List<GpsSpeed> listResult = new ArrayList<GpsSpeed>();  
1193 - int curPage = 0;//页码  
1194 - int pageData = 0;//每页的记录条数  
1195 - if(list.size()>1){  
1196 - GpsSpeed GpsSpeedNow;//下标为i的车辆行驶记录  
1197 - GpsSpeed GpsSpeedLast;//下标为i-1的车辆行驶记录  
1198 - GpsSpeed spped = null;//整合后的车辆行驶记录  
1199 - String strNow;  
1200 - String strLast;  
1201 - boolean Flag = false;//判断是否有连续超速记录,默认没有  
1202 - for(int i = 1;i<list.size();i++){  
1203 - GpsSpeedNow = list.get(i);  
1204 - GpsSpeedLast = list.get(i-1);  
1205 - strNow = GpsSpeedNow.getVehicle()+GpsSpeedNow.getLine()+GpsSpeedNow.getUp_down();  
1206 - strLast = GpsSpeedLast.getVehicle()+GpsSpeedLast.getLine()+GpsSpeedLast.getUp_down();  
1207 - if(GpsSpeedNow.getSpeed()>60 && GpsSpeedLast.getSpeed()>60 && strNow.equals(strLast)){//如果两条连续的记录都是超速且属于同一辆车。  
1208 - if(Flag==false){//  
1209 - spped = new GpsSpeed();  
1210 - spped.setLine(GpsSpeedLast.getLine());//设置连续超速记录线路  
1211 - spped.setLineName(GpsSpeedLast.getLineName());//设置连续超速记录线路名称  
1212 - spped.setVehicle(GpsSpeedLast.getVehicle());//设置连续超速记录的车辆编号  
1213 - spped.setUp_down(GpsSpeedLast.getUp_down());//设置上下行  
1214 - spped.setLon(GpsSpeedLast.getLon());//设置开始时经度  
1215 - spped.setLat(GpsSpeedLast.getLat());//设置开始时纬度  
1216 - spped.setTimestamp(GpsSpeedLast.getTimestamp());//设置连续超速记录的开始时间  
1217 - spped.setTimestampDate(GpsSpeedLast.getTimestampDate());//设置连续超速记录的开始时间戳  
1218 - }  
1219 - spped.setEndtimestamp(GpsSpeedNow.getTimestamp());//设置结束时间戳  
1220 - spped.setEndtimestampDate(sdf.format(new Date(GpsSpeedNow.getTimestamp())));//设置结束时间  
1221 - spped.setEndlon(GpsSpeedNow.getLon());//设置结束时的经度  
1222 - spped.setEndlat(GpsSpeedNow.getLat());//设置结束时的纬度  
1223 - Flag = true;  
1224 - }else{  
1225 - if(Flag){//如果上一条记录超速。  
1226 - listResult.add(spped);  
1227 - Flag = false;  
1228 - }  
1229 - }  
1230 - }  
1231 - if(listResult.size()>0){  
1232 - Iterator<GpsSpeed> speedIt = listResult.iterator();  
1233 - while(speedIt.hasNext()){  
1234 - GpsSpeed GpsSpeed = speedIt.next();  
1235 - if(GpsSpeed.getEndtimestamp()-GpsSpeed.getTimestamp()<=1000){  
1236 - speedIt.remove();  
1237 - }  
1238 - }  
1239 - }  
1240 - }  
1241 - if(map.get("curPage") == null || map.get("curPage").equals("0")){  
1242 - curPage = 0;  
1243 - }else{  
1244 - curPage = Integer.parseInt((String) map.get("curPage"));  
1245 - }  
1246 - Integer totalPage = totalDays;  
1247 - pageData = listResult.size();//每页的记录条数就是当前页查出的全部数据。  
1248 - Map<String,Object> paramMap = new HashMap<String,Object>();  
1249 - paramMap.put("totalPage", totalPage);  
1250 - paramMap.put("page", curPage);  
1251 - paramMap.put("pageData", pageData);  
1252 - paramMap.put("list", listResult);  
1253 - return paramMap;  
1254 - }  
1255 -  
1256 - @Override  
1257 - public Map<String, Object> allCarsByLine(String lineCode) {  
1258 - Map<String, Object> map = new HashMap();  
1259 - try{  
1260 - List<Map<String, Object>> list = new ArrayList<>();  
1261 - Map<String, Object> item;  
1262 - GpsEntity gps;  
1263 - //当天线路下营运的车辆  
1264 - Set<String> cars = dayOfSchedule.findCarByLineCode(lineCode);  
1265 - ScheduleRealInfo sch;  
1266 - String device;  
1267 -  
1268 - Map<String, Integer> allDevices = new HashMap<>();  
1269 - String execStr = "";  
1270 - D80 d80;  
1271 - for(String nbbm : cars){  
1272 - item = new HashMap<>();  
1273 - device = BasicData.deviceId2NbbmMap.inverse().get(nbbm);  
1274 - allDevices.put(device, 1);  
1275 - item.put("nbbm", nbbm);  
1276 - item.put("device", device);  
1277 -  
1278 - sch = dayOfSchedule.executeCurr(nbbm);  
1279 - if(null != sch){  
1280 - execStr = (sch.getXlDir().equals("0")?"上行":"下行") + "("+sch.getDfsj()+")";  
1281 - if(!sch.getXlBm().equals(lineCode))  
1282 - execStr = sch.getXlName()+execStr;  
1283 - else  
1284 - item.put("schId", sch.getId());  
1285 - item.put("exec", execStr);  
1286 - }  
1287 -  
1288 - gps = gpsRealData.get(device);  
1289 - if(null != gps){  
1290 - item.put("loc", gps.getStationName());  
1291 - item.put("lineCodeReal", gps.getLineId());  
1292 - item.put("status", gps.isOffline()?"离线":"在线");  
1293 - item.put("gpsTs", gps.getTimestamp());  
1294 - }  
1295 - //请求出场时间  
1296 - d80 = PilotReport.qqccMap.get(device);  
1297 - if(null != d80)  
1298 - item.put("qqcc", d80.getTimestamp());  
1299 -  
1300 - list.add(item);  
1301 - }  
1302 -  
1303 - //车载编码落在该线路的设备  
1304 - Set<String> devices = gpsRealData.findDevices(lineCode);  
1305 - for(String d : devices){  
1306 - if(allDevices.containsKey(d))  
1307 - continue;  
1308 -  
1309 - gps = gpsRealData.get(d);  
1310 - if(null == gps)  
1311 - continue;  
1312 -  
1313 - item = new HashMap<>();  
1314 - item.put("nbbm", gps.getNbbm());  
1315 - item.put("device", d);  
1316 - item.put("loc", gps.getStationName());  
1317 - item.put("lineCodeReal", gps.getLineId());  
1318 - item.put("status", gps.isOffline()?"离线":"在线");  
1319 - item.put("gpsTs", gps.getTimestamp());  
1320 -  
1321 - //请求出场时间  
1322 - d80 = PilotReport.qqccMap.get(d);  
1323 - if(null != d80)  
1324 - item.put("qqcc", d80.getTimestamp());  
1325 -  
1326 - list.add(item);  
1327 - }  
1328 -  
1329 - map.put("list", list);  
1330 - map.put("status", ResponseCode.SUCCESS);  
1331 - }catch (Exception e){  
1332 - logger.error("", e);  
1333 - map.put("status", ResponseCode.ERROR);  
1334 - map.put("msg", e.getMessage());  
1335 - }  
1336 - return map;  
1337 - }  
1338 -  
1339 - static List<GpsSpeed> findAll(Map<String, Object> map) {  
1340 - Connection conn = null;  
1341 - PreparedStatement ps = null;  
1342 - ResultSet rs = null;  
1343 - List<GpsSpeed> list=new ArrayList<GpsSpeed>();  
1344 - String sql="select * from bsth_c_gps_info where 1=1 ";  
1345 - Object line=map.get("line");  
1346 - Object nbbm=map.get("nbbm");  
1347 - Object updown=map.get("updown");  
1348 - Object startDate=map.get("startDate");  
1349 - Object endDate=map.get("endDate");  
1350 - Integer totalDays = Integer.valueOf(map.get("totalDays").toString());  
1351 - Integer curPage = 0;//页码  
1352 - if(map.get("curPage") == null || map.get("curPage").equals("0")){  
1353 - curPage = 0;  
1354 - }else{  
1355 - curPage = Integer.parseInt((String) map.get("curPage"));  
1356 - }  
1357 -  
1358 - SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
1359 - if(line!=null){  
1360 - sql +=" and line_id like'%"+line.toString().trim()+"%'";  
1361 - }  
1362 -  
1363 - if(nbbm!=null){  
1364 - nbbm=BasicData.deviceId2NbbmMap.inverse().get(nbbm);  
1365 - if(nbbm!=null)  
1366 - sql +=" and vehicle like '%"+nbbm.toString()+"%'";  
1367 - }  
1368 -  
1369 - if(updown!=null){  
1370 - sql +="and industry_code like '%"+updown.toString()+"%'";  
1371 - }  
1372 - if(startDate!=null){  
1373 - if (startDate.toString().length()>0) {  
1374 - try {  
1375 - Long t1=sdf.parse(startDate.toString()+" 00:00:00").getTime()+curPage*3600*24*1000;  
1376 - sql += " and ts >="+t1;  
1377 - } catch (ParseException e) {  
1378 - e.printStackTrace();  
1379 - }  
1380 - }  
1381 -  
1382 - }  
1383 - if(endDate!=null){  
1384 - if (endDate.toString().length()>0) {  
1385 - try {  
1386 - Long t2=sdf.parse(endDate.toString()+" 23:59:59").getTime()-(totalDays-1-curPage)*3600*24*1000;  
1387 - sql += " and ts <="+t2;  
1388 - } catch (ParseException e) {  
1389 - e.printStackTrace();  
1390 - }  
1391 - }  
1392 -  
1393 - }  
1394 -  
1395 - try {  
1396 - conn = DBUtils_MS.getConnection();  
1397 - ps = conn.prepareStatement(sql);  
1398 - rs = ps.executeQuery();  
1399 - list = resultSet2Set(rs);  
1400 - } catch (SQLException e) {  
1401 - e.printStackTrace();  
1402 - }finally {  
1403 - DBUtils_MS.close(rs, ps, conn);  
1404 - }  
1405 -  
1406 - return list;  
1407 - }  
1408 -  
1409 - static List<GpsSpeed> resultSet2Set(ResultSet rs) throws SQLException{  
1410 - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
1411 - List<GpsSpeed> list=new ArrayList<GpsSpeed>();  
1412 - GpsSpeed GpsSpeed;  
1413 - Float lon, lat;  
1414 - Location location;  
1415 - while(rs.next()){  
1416 - lon = rs.getFloat("lon");  
1417 - lat = rs.getFloat("lat");  
1418 - location = TransGPS.LocationMake(lon, lat);  
1419 - location = TransGPS.bd_encrypt(TransGPS.transformFromWGSToGCJ(location));  
1420 - GpsSpeed=new GpsSpeed();  
1421 - GpsSpeed.setLon((float)location.getLng());  
1422 - GpsSpeed.setLat((float)location.getLat());  
1423 - GpsSpeed.setLine(rs.getObject("line_id").toString());  
1424 - //run 时注解  
1425 - GpsSpeed.setLineName(BasicData.lineCode2NameMap.get(GpsSpeed.getLine().toString()));  
1426 - GpsSpeed.setSpeed(Float.valueOf(rs.getObject("speed_gps").toString()));  
1427 - GpsSpeed.setTimestamp((Long.valueOf(rs.getObject("ts").toString())));  
1428 - GpsSpeed.setTimestampDate(sdf.format(new Date(GpsSpeed.getTimestamp())));  
1429 - GpsSpeed.setUp_down(((Integer.valueOf(rs.getObject("service_state").toString())) & 0x10000000)==0?0:1);  
1430 - GpsSpeed.setVehicle(BasicData.deviceId2NbbmMap.get(rs.getObject("device_id").toString()));  
1431 - list.add(GpsSpeed);  
1432 - }  
1433 - return list;  
1434 - }  
1435 -  
1436 -}  
1437 - 1 +package com.bsth.service.gps;
  2 +
  3 +import com.bsth.common.ResponseCode;
  4 +import com.bsth.data.BasicData;
  5 +import com.bsth.data.forecast.entity.ArrivalEntity;
  6 +import com.bsth.data.gpsdata_v2.GpsRealData;
  7 +import com.bsth.data.gpsdata_v2.cache.GeoCacheData;
  8 +import com.bsth.data.gpsdata_v2.cache.GpsCacheData;
  9 +import com.bsth.data.gpsdata_v2.entity.GpsEntity;
  10 +import com.bsth.data.gpsdata_v2.utils.GeoUtils;
  11 +import com.bsth.data.pilot80.PilotReport;
  12 +import com.bsth.data.safe_driv.SafeDriv;
  13 +import com.bsth.data.safe_driv.SafeDrivCenter;
  14 +import com.bsth.data.schedule.DayOfSchedule;
  15 +import com.bsth.entity.directive.D80;
  16 +import com.bsth.entity.realcontrol.ScheduleRealInfo;
  17 +import com.bsth.repository.CarParkRepository;
  18 +import com.bsth.repository.StationRepository;
  19 +import com.bsth.repository.realcontrol.ScheduleRealInfoRepository;
  20 +import com.bsth.service.gps.entity.*;
  21 +import com.bsth.util.TransGPS;
  22 +import com.bsth.util.TransGPS.Location;
  23 +import com.bsth.util.db.DBUtils_MS;
  24 +import org.apache.commons.lang3.StringUtils;
  25 +import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  26 +import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  27 +import org.apache.poi.ss.usermodel.CellStyle;
  28 +import org.apache.poi.ss.usermodel.Row;
  29 +import org.apache.poi.ss.usermodel.Sheet;
  30 +import org.apache.poi.ss.usermodel.Workbook;
  31 +import org.joda.time.format.DateTimeFormat;
  32 +import org.joda.time.format.DateTimeFormatter;
  33 +import org.slf4j.Logger;
  34 +import org.slf4j.LoggerFactory;
  35 +import org.springframework.beans.factory.annotation.Autowired;
  36 +import org.springframework.dao.DataAccessException;
  37 +import org.springframework.jdbc.core.BeanPropertyRowMapper;
  38 +import org.springframework.jdbc.core.JdbcTemplate;
  39 +import org.springframework.stereotype.Service;
  40 +
  41 +import javax.servlet.http.HttpServletResponse;
  42 +import java.io.IOException;
  43 +import java.io.OutputStream;
  44 +import java.io.UnsupportedEncodingException;
  45 +import java.lang.reflect.Field;
  46 +import java.net.URLEncoder;
  47 +import java.sql.Connection;
  48 +import java.sql.PreparedStatement;
  49 +import java.sql.ResultSet;
  50 +import java.sql.SQLException;
  51 +import java.text.DecimalFormat;
  52 +import java.text.ParseException;
  53 +import java.text.SimpleDateFormat;
  54 +import java.util.*;
  55 +
  56 +@Service
  57 +public class GpsServiceImpl implements GpsService {
  58 + /**
  59 + * 历史gps查询最大范围 24小时
  60 + */
  61 + final static Long GPS_RANGE = 60 * 60 * 24L;
  62 +
  63 + /**
  64 + * jdbc
  65 + */
  66 + Connection conn = null;
  67 + PreparedStatement ps = null;
  68 + ResultSet rs = null;
  69 +
  70 + Logger logger = LoggerFactory.getLogger(this.getClass());
  71 +
  72 + @Autowired
  73 + GpsRealData gpsRealData;
  74 +
  75 + @Autowired
  76 + JdbcTemplate jdbcTemplate;
  77 +
  78 + @Autowired
  79 + DayOfSchedule dayOfSchedule;
  80 +
  81 + @Autowired
  82 + ScheduleRealInfoRepository scheduleRealInfoRepository;
  83 +
  84 + // 历史gps查询
  85 + @Override
  86 + public List<Map<String, Object>> history(String device, Long startTime, Long endTime, int directions) {
  87 + Calendar sCal = Calendar.getInstance();
  88 + sCal.setTime(new Date(startTime));
  89 +
  90 + Calendar eCal = Calendar.getInstance();
  91 + eCal.setTime(new Date(endTime));
  92 +
  93 + int dayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
  94 + /*
  95 + * if(dayOfYear != eCal.get(Calendar.DAY_OF_YEAR)){
  96 + * System.out.println("暂时不支持跨天查询..."); return null; }
  97 + */
  98 +
  99 + String sql = "select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,STOP_NO from bsth_c_gps_info where days_year=? and device_id=? and ts > ? and ts < ?";
  100 + Connection conn = null;
  101 + PreparedStatement ps = null;
  102 + ResultSet rs = null;
  103 + List<Map<String, Object>> list = new ArrayList<>();
  104 + Map<String, Object> map = null;
  105 + try {
  106 + conn = DBUtils_MS.getConnection();
  107 + ps = conn.prepareStatement(sql);
  108 + ps.setInt(1, dayOfYear);
  109 + ps.setString(2, device);
  110 + ps.setLong(3, startTime);
  111 + ps.setLong(4, endTime);
  112 +
  113 + rs = ps.executeQuery();
  114 + Float lon, lat;
  115 + Location location;
  116 + int upDown;
  117 + while (rs.next()) {
  118 + upDown = getUpOrDown(rs.getLong("SERVICE_STATE"));
  119 + if (upDown != directions)
  120 + continue;
  121 +
  122 + // to 百度坐标
  123 + lon = rs.getFloat("LON");
  124 + lat = rs.getFloat("LAT");
  125 + location = TransGPS.LocationMake(lon, lat);
  126 + location = TransGPS.bd_encrypt(TransGPS.transformFromWGSToGCJ(location));
  127 +
  128 + map = new HashMap<>();
  129 + map.put("device", rs.getString("DEVICE_ID"));
  130 + map.put("lon", location.getLng());
  131 + map.put("lat", location.getLat());
  132 + map.put("ts", rs.getLong("TS"));
  133 + map.put("stopNo", rs.getString("STOP_NO"));
  134 + map.put("inout_stop", rs.getInt("INOUT_STOP"));
  135 + // 上下行
  136 + map.put("upDown", upDown);
  137 + list.add(map);
  138 + }
  139 + } catch (Exception e) {
  140 + e.printStackTrace();
  141 + } finally {
  142 + DBUtils_MS.close(rs, ps, conn);
  143 + }
  144 + return list;
  145 + }
  146 +
  147 + /**
  148 + * 王通 2016/6/29 9:23:24 获取车辆线路上下行
  149 + *
  150 + * @return -1无效 0上行 1下行
  151 + */
  152 + public static byte getUpOrDown(long serviceState) {
  153 + /*if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000
  154 + || (serviceState & 0x01000000) == 0x01000000 || (serviceState & 0x08000000) == 0x08000000)
  155 + return -1;*/
  156 + return (byte) (((serviceState & 0x10000000) == 0x10000000) ? 1 : 0);
  157 + }
  158 +
  159 + /**
  160 + * 获取运营状态
  161 + *
  162 + * @return -1无效 0运营 1未运营
  163 + */
  164 + public static byte getService(long serviceState) {
  165 + /*if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000)
  166 + return -1;*/
  167 + return (byte) (((serviceState & 0x02000000) == 0x02000000) ? 1 : 0);
  168 + }
  169 +
  170 + private static DateTimeFormatter fmtyyyy = DateTimeFormat.forPattern("yyyy");
  171 + @Override
  172 + public Map<String, Object> history(String[] nbbmArray, Long st, Long et) {
  173 + Map<String, Object> rsMap = new HashMap<>();
  174 + List<Map<String, Object>> list = new ArrayList<>();
  175 + rsMap.put("list", list);
  176 + if (et - st > GPS_RANGE)
  177 + return rsMap;
  178 +
  179 + st = st * 1000;
  180 + et = et * 1000;
  181 + // day_of_year 分区字段
  182 + Calendar sCal = Calendar.getInstance();
  183 + sCal.setTime(new Date(st));
  184 + int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
  185 + Calendar eCal = Calendar.getInstance();
  186 + eCal.setTime(new Date(et));
  187 + int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR);
  188 +
  189 + String nbbm = nbbmArray[0];
  190 +
  191 + List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
  192 +
  193 + //按年分表
  194 + String tableName = "bsth_c_gps_info_" + fmtyyyy.print(st);
  195 +
  196 + StringBuilder sql = new StringBuilder("");
  197 + long t1,t2;
  198 + DeviceChange dc;
  199 + for(int i = 0,len=dcs.size(); i < len; i++){
  200 + t1 = st;
  201 + t2 = et;
  202 + dc = dcs.get(i);
  203 + if(dc.getSt() > st)
  204 + t1 = dc.getSt();
  205 + if(dc.getEt() < et && dc.getEt()!=0)
  206 + t2 = dc.getEt();
  207 +
  208 + sql.append("select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,STOP_NO,DIRECTION,LINE_ID,SPEED_GPS,SECTION_CODE from "+tableName+" where days_year in ("+sDayOfYear+","+eDayOfYear+") " +
  209 + " and device_id='"+dc.getDevice()+"' and ts >= "+t1+" and ts <= "+t2+" ");
  210 +
  211 + if(i == len - 1)
  212 + sql.append(" ORDER BY device_id,ts,stop_no");
  213 + else
  214 + sql.append(" UNION ");
  215 + }
  216 +
  217 + logger.info("轨迹回放 nbbm: " + nbbm + " -st: " + st + " -et: " + et + " -sql: " + sql.toString());
  218 +
  219 + // 查询到离站数据
  220 + Map<String, ArrivalEntity> arrivalMap = findArrivalByTs(st, et, dcs);
  221 +
  222 + //查询GPS数据
  223 + JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
  224 + List<Map<String, Object>> dataList = jdbcTemplate_ms.queryForList(sql.toString());
  225 +
  226 + Float lon, lat;
  227 + Location bdLoc, gdLoc;
  228 + int inOutStop;
  229 + long serviceState;
  230 + ArrivalEntity arrival;
  231 +
  232 + Map<String, Object> map = null;
  233 + for(Map<String, Object> rs : dataList){
  234 + serviceState = map_get_long(rs, "SERVICE_STATE");
  235 + if(getGpsValid(serviceState) == 1)
  236 + continue;
  237 +
  238 + map = new HashMap<>();
  239 + lon = map_get_float(rs, "LON");
  240 + lat = map_get_float(rs, "LAT");
  241 + // 高德坐标
  242 + gdLoc = TransGPS.transformFromWGSToGCJ(TransGPS.LocationMake(lon, lat));
  243 + map.put("gcj_lon", gdLoc.getLng());
  244 + map.put("gcj_lat", gdLoc.getLat());
  245 + // 百度坐标
  246 + bdLoc = TransGPS.bd_encrypt(gdLoc);
  247 + map.put("bd_lon", bdLoc.getLng());
  248 + map.put("bd_lat", bdLoc.getLat());
  249 + //原始坐标
  250 + map.put("lon", lon);
  251 + map.put("lat", lat);
  252 +
  253 + map.put("deviceId", map_get_str(rs, "DEVICE_ID"));
  254 + map.put("ts", map_get_long(rs, "TS"));
  255 + map.put("timestamp", map_get_long(rs, "TS"));
  256 + map.put("stopNo", map_get_str(rs, "STOP_NO"));
  257 + map.put("direction", map_get_float(rs,"DIRECTION"));
  258 +
  259 + map.put("lineId", map_get_str(rs, "LINE_ID"));
  260 + map.put("speed", map_get_float(rs,"SPEED_GPS"));
  261 +
  262 + inOutStop = Integer.parseInt(rs.get("INOUT_STOP").toString());
  263 + map.put("inout_stop", inOutStop);
  264 +
  265 + arrival = arrivalMap.get(map_get_str(rs, "DEVICE_ID") + "_" + map_get_long(rs, "TS"));
  266 + if (arrival != null) {
  267 + map.put("inout_stop_info", arrival);
  268 + map.put("inout_stop", arrival.getInOut());
  269 + }
  270 +
  271 + //map.put("nbbm", nbbm);
  272 + map.put("state", getService(serviceState));
  273 + // 上下行
  274 + map.put("upDown", getUpOrDown(serviceState));
  275 + //路段编码
  276 + map.put("section_code", map_get_str(rs,"SECTION_CODE"));
  277 + list.add(map);
  278 + }
  279 + // 按时间排序
  280 + Collections.sort(list, new Comparator<Map<String, Object>>() {
  281 +
  282 + @Override
  283 + public int compare(Map<String, Object> o1, Map<String, Object> o2) {
  284 + return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
  285 + }
  286 + });
  287 +
  288 + rsMap.put("list", list);
  289 + rsMap.put("dcs", dcs);
  290 + return rsMap;
  291 + }
  292 +
  293 + private String map_get_str(Map<String, Object> map, String key){
  294 + return map.containsKey(key)?map.get(key).toString():"";
  295 + }
  296 +
  297 + private Long map_get_long(Map<String, Object> map, String key){
  298 + return map.containsKey(key)?Long.parseLong(map.get(key).toString()):-1;
  299 + }
  300 +
  301 + private Float map_get_float(Map<String, Object> map, String key){
  302 + return map.containsKey(key)?Float.parseFloat(map.get(key).toString()):-1;
  303 + }
  304 +
  305 + private List<DeviceChange> findDeviceChangeLogs(String nbbm, long et, long st){
  306 + List<DeviceChange> dcs = null;
  307 + List<DeviceChange> rs = new ArrayList<>();
  308 + try{
  309 +
  310 + //JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
  311 + dcs = jdbcTemplate.query("select cl_zbh as nbbm,new_device_no as device,old_device_no as old_device,UNIX_TIMESTAMP(qyrq) * 1000 as st from bsth_c_car_device where is_cancel=0 and cl_zbh='"+nbbm+"' order by qyrq"
  312 + , BeanPropertyRowMapper.newInstance(DeviceChange.class));
  313 +
  314 +
  315 + //生成一条初始记录
  316 + if(dcs.size() > 0){
  317 + DeviceChange first = dcs.get(0);
  318 +
  319 + DeviceChange initDv = new DeviceChange();
  320 + initDv.setDevice(first.getOldDevice());
  321 + if(StringUtils.isNotEmpty(initDv.getDevice())){
  322 + initDv.setNbbm(first.getNbbm());
  323 + initDv.setSt(0);
  324 + initDv.setEt(first.getSt());
  325 + dcs.add(0, initDv);
  326 + }
  327 + }
  328 + for(int i = 0,len=dcs.size(); i < len - 1; i++){
  329 + dcs.get(i).setEt(dcs.get(i + 1).getSt());
  330 + }
  331 +
  332 + for(DeviceChange dc : dcs){
  333 + if(dc.getEt() < st && dc.getEt() != 0)
  334 + continue;
  335 + if(dc.getSt() > et)
  336 + continue;
  337 +
  338 + rs.add(dc);
  339 + }
  340 +
  341 + //没有设备变更记录,则参考车辆信息上的设备号
  342 + if(null == rs || rs.size() == 0){
  343 + DeviceChange dc = new DeviceChange();
  344 + dc.setNbbm(nbbm);
  345 + dc.setDevice(BasicData.deviceId2NbbmMap.inverse().get(nbbm));
  346 + dc.setSt(st);
  347 + dc.setEt(et);
  348 + dc.setType(1);
  349 +
  350 + rs.add(dc);
  351 + }
  352 + }catch (Exception e){
  353 + logger.error("", e);
  354 + }
  355 + return rs;
  356 + }
  357 +
  358 + public static byte getGpsValid(long serviceState) {
  359 + return (byte)(((serviceState & 0x80000000) == 0x80000000) ? 1 : 0);
  360 + }
  361 +
  362 + public static void main(String[] args){
  363 + System.out.println(getGpsValid(-2147483648));
  364 + }
  365 +
  366 + public Map<String, ArrivalEntity> findArrivalByTs(Long st, Long et, List<DeviceChange> dcs) {
  367 + Map<String, ArrivalEntity> map = new HashMap<>();
  368 +
  369 + // weeks_year 分区字段
  370 + Calendar sCal = Calendar.getInstance();
  371 + sCal.setTime(new Date(st));
  372 + int sWeekOfYear = sCal.get(Calendar.WEEK_OF_YEAR);
  373 + Calendar eCal = Calendar.getInstance();
  374 + eCal.setTime(new Date(et));
  375 + int eWeekOfYear = eCal.get(Calendar.WEEK_OF_YEAR);
  376 +
  377 + //按年分表
  378 + String tableName = "bsth_c_arrival_info_" + fmtyyyy.print(st);
  379 +
  380 + StringBuilder sql = new StringBuilder("");
  381 + long t1,t2;
  382 + DeviceChange dc;
  383 + for(int i = 0,len=dcs.size(); i < len; i++){
  384 + t1 = st;
  385 + t2 = et;
  386 + dc = dcs.get(i);
  387 + if(dc.getSt() > st)
  388 + t1 = dc.getSt();
  389 + if(dc.getEt() < et && dc.getEt() != 0)
  390 + t2 = dc.getEt();
  391 +
  392 + sql.append("SELECT DEVICE_ID,LINE_ID as LINE_CODE,STOP_NO,TS,UP_DOWN,IN_OUT,WEEKS_YEAR,CREATE_DATE FROM " + tableName +
  393 + " where weeks_year in ("+sWeekOfYear+", "+eWeekOfYear+") and device_id='"+dc.getDevice()+"' and ts > "+t1+" and ts < " + t2);
  394 +
  395 + if(i == len - 1)
  396 + sql.append(" ORDER BY device_id,ts,stop_no ");
  397 + else
  398 + sql.append(" UNION ");
  399 + }
  400 +
  401 + logger.info("arrivl sql : " + sql.toString());
  402 + JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
  403 + List<ArrivalEntity> list = jdbcTemplate_ms.query(sql.toString(), BeanPropertyRowMapper.newInstance(ArrivalEntity.class));
  404 +
  405 + String stationName, prefix;
  406 + for(ArrivalEntity arr : list){
  407 + prefix = arr.getLineCode() + "_" + arr.getUpDown() + "_";
  408 + stationName = BasicData.getStationNameByCode(arr.getStopNo(), prefix);
  409 +
  410 + arr.setStopName(stationName);
  411 +
  412 + // 反转进出状态
  413 + map.put(arr.getDeviceId() + "_" + arr.getTs(), arr);
  414 + }
  415 + return map;
  416 + }
  417 +
  418 +
  419 + @Autowired
  420 + StationRepository stationRepository;
  421 +
  422 + @Autowired
  423 + CarParkRepository carParkRepository;
  424 +
  425 + @Override
  426 + public Map<String, Object> findBuffAeraByCode(String code, String type) {
  427 + Object[][] obj = null;
  428 + if (type.equals("station"))
  429 + obj = stationRepository.bufferAera(code);
  430 + else if (type.equals("park"))
  431 + obj = carParkRepository.bufferAera(code);
  432 +
  433 + Map<String, Object> rs = new HashMap<>();
  434 +
  435 + Object[] subObj = obj[0];
  436 + if (subObj != null && subObj.length == 6) {
  437 + rs.put("polygon", subObj[0]);
  438 + rs.put("type", subObj[1]);
  439 + rs.put("cPoint", subObj[2]);
  440 + rs.put("radius", subObj[3]);
  441 + rs.put("code", subObj[4]);
  442 + rs.put("text", subObj[5]);
  443 + }
  444 +
  445 + return rs;
  446 + }
  447 +
  448 + @Override
  449 + public Map<String, Object> search(Map<String, Object> map, int page, int size, String order, String direction) {
  450 + Map<String, Object> rsMap = new HashMap<>();
  451 + try {
  452 + //全量
  453 + List<GpsEntity> list = new ArrayList<>(gpsRealData.all());
  454 + //过滤后的
  455 + List<GpsEntity> rs = new ArrayList<>();
  456 + Field[] fields = GpsEntity.class.getDeclaredFields();
  457 + //参与过滤的字段
  458 + List<Field> fs = new ArrayList<>();
  459 + for (Field f : fields) {
  460 + f.setAccessible(true);
  461 + if (map.containsKey(f.getName()))
  462 + fs.add(f);
  463 + }
  464 + //过滤数据
  465 + for (GpsEntity gps : list) {
  466 + if (fieldEquals(fs, gps, map))
  467 + rs.add(gps);
  468 + }
  469 +
  470 + //时间戳排序
  471 + Collections.sort(rs, new Comparator<GpsEntity>() {
  472 + @Override
  473 + public int compare(GpsEntity o1, GpsEntity o2) {
  474 + return o2.getTimestamp().intValue() - o1.getTimestamp().intValue();
  475 + }
  476 + });
  477 +
  478 + //分页
  479 + int count = rs.size(), s = page * size, e = s + size;
  480 + if (e > count)
  481 + e = count;
  482 +
  483 + rsMap.put("list", rs.subList(s, e));
  484 + rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);
  485 + rsMap.put("page", page);
  486 + rsMap.put("status", ResponseCode.SUCCESS);
  487 + } catch (Exception e) {
  488 + logger.error("", e);
  489 + rsMap.put("status", ResponseCode.ERROR);
  490 + }
  491 + return rsMap;
  492 + }
  493 +
  494 + @Override
  495 + public Map<String, Object> removeRealGps(String device) {
  496 + Map<String, Object> rs = new HashMap<>();
  497 + try {
  498 +
  499 + gpsRealData.remove(device);
  500 + GpsCacheData.remove(BasicData.deviceId2NbbmMap.get(device), true);
  501 + rs.put("status", ResponseCode.SUCCESS);
  502 + } catch (Exception e) {
  503 + rs.put("status", ResponseCode.ERROR);
  504 + }
  505 + return rs;
  506 + }
  507 +
  508 + @Override
  509 + public Map<String, Object> findRoadSpeed(String lineCode) {
  510 + Map<String, Object> rs = new HashMap<>();
  511 +
  512 + try {
  513 + String sql = "select ID, ST_AsText(GROAD_VECTOR) as GROAD_VECTOR,ROAD_CODE,ROAD_NAME,SPEED from bsth_c_road where road_code in(select section_code from bsth_c_sectionroute where line_code=? and destroy=0)";
  514 + List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, lineCode);
  515 + rs.put("status", ResponseCode.SUCCESS);
  516 + rs.put("roads", list);
  517 + } catch (DataAccessException e) {
  518 + logger.error("", e);
  519 + rs.put("status", ResponseCode.ERROR);
  520 + }
  521 + return rs;
  522 + }
  523 +
  524 + /**
  525 + * gps补全
  526 + *
  527 + * @param schId
  528 + * @return
  529 + */
  530 + @Override
  531 + public Map<String, Object> gpsCompletion(long schId, int type) {
  532 + Map<String, Object> rs = new HashMap<>();
  533 +
  534 + try {
  535 + ScheduleRealInfo sch = dayOfSchedule.get(schId);
  536 + if (sch == null) {
  537 + rs.put("status", ResponseCode.ERROR);
  538 + rs.put("msg", "找不到对应班次!!!");
  539 + return rs;
  540 + }
  541 +
  542 + if (sch.isReissue()) {
  543 + rs.put("status", ResponseCode.ERROR);
  544 + rs.put("msg", "你不能重复这个操作");
  545 + return rs;
  546 + }
  547 +
  548 + String sql = "select * from bsth_gps_template where line_id='" + sch.getXlBm() + "' and up_down=" + sch.getXlDir();
  549 + List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
  550 +
  551 + if (list.size() == 0) {
  552 + rs.put("status", ResponseCode.ERROR);
  553 + rs.put("msg", "缺少模板数据,请联系系统管理员!!");
  554 + return rs;
  555 + }
  556 + //排序
  557 + Collections.sort(list, new Comparator<Map<String, Object>>() {
  558 + @Override
  559 + public int compare(Map<String, Object> o1, Map<String, Object> o2) {
  560 + return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
  561 + }
  562 + });
  563 + Map<String, Object> fs = list.get(0);
  564 + //替换设备号和时间
  565 + long diff = ((sch.getDfsjT() - Long.parseLong(fs.get("ts").toString())) - 1000 * 70);
  566 +
  567 + String deviceId = BasicData.deviceId2NbbmMap.inverse().get(sch.getClZbh());
  568 + int serviceState;
  569 + for (Map<String, Object> map : list) {
  570 + map.put("device_id", deviceId);
  571 + map.put("ts", Long.parseLong(map.get("ts").toString()) + diff);
  572 + if(type==1){
  573 + //走补传协议
  574 + serviceState = Integer.parseInt(map.get("service_state").toString());
  575 + map.put("service_state", serviceState |= 0x00100000);
  576 + }
  577 + }
  578 +
  579 + String sqlBefore = "insert into bsth_c_template(", sqlValues = " values(";
  580 +
  581 + Set<String> ks = fs.keySet();
  582 + for (String k : ks) {
  583 + sqlBefore += (k + ",");
  584 + sqlValues += "?,";
  585 + }
  586 + sqlBefore = sqlBefore.substring(0, sqlBefore.length() - 1) + ", create_ts)";
  587 + sqlValues = sqlValues.substring(0, sqlValues.length() - 1) + ", " + System.currentTimeMillis() + ")";
  588 + sql = sqlBefore + " " + sqlValues;
  589 +
  590 + Connection conn = DBUtils_MS.getConnection();
  591 + conn.setAutoCommit(false);
  592 + ps = conn.prepareStatement(sql);
  593 + int fsize = ks.size();
  594 + List<Object> vs;
  595 + for (Map<String, Object> map : list) {
  596 + vs = new ArrayList<>(map.values());
  597 + for (int i = 0; i < fsize; i++) {
  598 + ps.setObject(i + 1, vs.get(i));
  599 + }
  600 + ps.addBatch();
  601 + }
  602 + ps.executeBatch();
  603 + conn.commit();
  604 +
  605 + rs.put("status", ResponseCode.SUCCESS);
  606 +
  607 + //标记班次
  608 + sch.setReissue(true);
  609 + scheduleRealInfoRepository.save(sch);
  610 +
  611 + rs.put("status", ResponseCode.SUCCESS);
  612 + } catch (Exception e) {
  613 + logger.error("", e);
  614 + rs.put("status", ResponseCode.ERROR);
  615 + }
  616 + return rs;
  617 + }
  618 +
  619 + @Override
  620 + public Map<String, Object> history_v2(String nbbm, long st, long et) {
  621 + Map<String, Object> rs = new HashMap<>();
  622 +
  623 + try {
  624 + //获取历史gps 数据
  625 + List<HistoryGps_DTO> list = HistoryGps_DTO.craete((List<Map<String, Object>>) history(new String[]{nbbm}, st, et).get("list"));
  626 + if (list != null && list.size() > 0) {
  627 + //获取路段信息
  628 + String sql = "select ID, ST_AsText(GROAD_VECTOR) as GROAD_VECTOR,ROAD_CODE,ROAD_NAME,SPEED from bsth_c_road where road_code in(select section_code from bsth_c_sectionroute where line_code=? and destroy=0)";
  629 + List<Road_DTO> roads = Road_DTO.craete(jdbcTemplate.queryForList(sql, list.get(0).getLineId()));
  630 +
  631 + //为GPS数据关联路段信息
  632 + for (HistoryGps_DTO gps : list) {
  633 + matchRoadToGps(gps, roads);
  634 + }
  635 + }
  636 +
  637 + //超速数据
  638 + List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
  639 + //越界数据
  640 + List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
  641 + //计算里程
  642 + List<HistoryGps_DTO> effList = new ArrayList<>();
  643 + for(HistoryGps_DTO gps : list){
  644 + if(gps.getLat() != 0 && gps.getLon() != 0)
  645 + effList.add(gps);
  646 + }
  647 + double sum = 0, dist;
  648 + for (int i = 0; i < effList.size() - 1; i++) {
  649 + dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());
  650 + //点位相同时,dist会NaN
  651 + if(String.valueOf(dist).matches("^[0.0-9.0]+$"))
  652 + sum += dist;
  653 + }
  654 +
  655 + rs.put("status", ResponseCode.SUCCESS);
  656 + rs.put("list", removeDuplicate(effList));
  657 + rs.put("speedList", speedList);
  658 + rs.put("outboundList", outboundList);
  659 + rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));
  660 + } catch (Exception e) {
  661 + logger.error("", e);
  662 + rs.put("status", ResponseCode.ERROR);
  663 + }
  664 + return rs;
  665 + }
  666 +
  667 +
  668 + @Override
  669 + public Map<String, Object> history_v3(String nbbm, long st, long et) {
  670 + Map<String, Object> rs = new HashMap<>();
  671 +
  672 + try {
  673 + //获取历史gps 数据
  674 + Map<String, Object> gpsMap = history(new String[]{nbbm}, st, et);
  675 + List<HistoryGps_DTOV3> list = HistoryGps_DTOV3.craete((List<Map<String, Object>>) gpsMap.get("list"));
  676 + if (list != null && list.size() > 0) {
  677 + //关联路段名称
  678 + Map<String, String> sectionCode2Name = GeoCacheData.sectionCode2NameMap();
  679 + for(HistoryGps_DTOV3 gps : list){
  680 + if(StringUtils.isNotEmpty(gps.getSection_code()))
  681 + gps.setSection_name(sectionCode2Name.get(gps.getSection_code()));
  682 + else{
  683 + gps.setSection_code("-00404");
  684 + gps.setSection_name("未知路段");
  685 + }
  686 + }
  687 + }
  688 +
  689 + //超速数据
  690 + List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
  691 +
  692 + //越界数据
  693 + List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
  694 +
  695 + //计算里程
  696 + List<HistoryGps_DTOV3> effList = new ArrayList<>();
  697 + for(HistoryGps_DTOV3 gps : list){
  698 + if(gps.getLat() != 0 && gps.getLon() != 0)
  699 + effList.add(gps);
  700 + }
  701 + double sum = 0, dist;
  702 + for (int i = 0; i < effList.size() - 1; i++) {
  703 + dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());
  704 + //点位相同时,dist会NaN
  705 + if(String.valueOf(dist).matches("^[0.0-9.0]+$")){
  706 + if(dist > 0.8)
  707 + sum += dist;
  708 + }
  709 + }
  710 +
  711 + rs.put("status", ResponseCode.SUCCESS);
  712 + rs.put("list", removeDuplicateV3(effList));
  713 + rs.put("speedList", speedList);
  714 + rs.put("outboundList", outboundList);
  715 + rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));
  716 + rs.put("dcs", gpsMap.get("dcs"));
  717 + } catch (Exception e) {
  718 + logger.error("", e);
  719 + rs.put("status", ResponseCode.ERROR);
  720 + rs.put("msg", e.getMessage());
  721 + }
  722 + return rs;
  723 + }
  724 +
  725 + @Override
  726 + public void trailExcel(String nbbm, long st, long et, HttpServletResponse resp) {
  727 + //获取历史gps 数据
  728 + List<HistoryGps_DTOV3> list = HistoryGps_DTOV3.craete((List<Map<String, Object>>) history(new String[]{nbbm}, st, et).get("list"));
  729 + if (list != null && list.size() > 0) {
  730 + //关联路段名称
  731 + Map<String, String> sectionCode2Name = GeoCacheData.sectionCode2NameMap();
  732 + for(HistoryGps_DTOV3 gps : list){
  733 + if(StringUtils.isNotEmpty(gps.getSection_code()))
  734 + gps.setSection_name(sectionCode2Name.get(gps.getSection_code()));
  735 + else{
  736 + gps.setSection_code("-00404");
  737 + gps.setSection_name("未知路段");
  738 + }
  739 + }
  740 + }
  741 +
  742 + //创建excel工作簿
  743 + Workbook wb = new HSSFWorkbook();
  744 + Sheet sheet = wb.createSheet("行车轨迹");
  745 + //表头
  746 + Row row = sheet.createRow(0);
  747 + row.setHeight((short) (1.5 * 256));
  748 + row.createCell(0).setCellValue("序号");
  749 + row.createCell(1).setCellValue("车辆");
  750 + row.createCell(2).setCellValue("牌照号");
  751 + row.createCell(3).setCellValue("所在道路");
  752 + row.createCell(4).setCellValue("经度");
  753 + row.createCell(5).setCellValue("纬度");
  754 + row.createCell(6).setCellValue("时间");
  755 + row.createCell(7).setCellValue("速度");
  756 + //数据
  757 + DateTimeFormatter fmtHHmmss = DateTimeFormat.forPattern("HH:mm.ss"),
  758 + fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
  759 + HistoryGps_DTOV3 gps;
  760 + for(int i = 0; i < list.size(); i ++){
  761 + gps = list.get(i);
  762 + row = sheet.createRow(i + 1);
  763 + row.createCell(0).setCellValue(i + 1);
  764 + row.createCell(1).setCellValue(nbbm);
  765 + row.createCell(2).setCellValue(BasicData.nbbmCompanyPlateMap.get(nbbm));
  766 + row.createCell(3).setCellValue(gps.getSection_name());
  767 + row.createCell(4).setCellValue(gps.getLon());
  768 + row.createCell(5).setCellValue(gps.getLat());
  769 + row.createCell(6).setCellValue(fmtHHmmss.print(gps.getTimestamp()));
  770 + row.createCell(7).setCellValue(gps.getSpeed());
  771 + }
  772 +
  773 + st = st * 1000;
  774 + et = et * 1000;
  775 + String filename = nbbm + "轨迹数据" + fmt.print(st) + "至" + fmt.print(et) + ".xls";
  776 + try {
  777 + resp.setContentType("application/x-msdownload");
  778 + resp.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
  779 +
  780 + OutputStream out=resp.getOutputStream();
  781 + wb.write(out);
  782 + out.flush();
  783 + out.close();
  784 + } catch (UnsupportedEncodingException e) {
  785 + logger.error("", e);
  786 + } catch (IOException e) {
  787 + logger.error("", e);
  788 + }
  789 + }
  790 +
  791 + @Override
  792 + public void abnormalExcel(String nbbm, long st, long et, HttpServletResponse resp) {
  793 + //超速数据
  794 + List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
  795 + //越界数据
  796 + List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
  797 +
  798 + //创建excel工作簿
  799 + Workbook wb = new HSSFWorkbook();
  800 +
  801 + DateTimeFormatter fmtHHmmss = DateTimeFormat.forPattern("HH:mm.ss"),
  802 + fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
  803 + if(speedList.size() > 0){
  804 + Sheet sheet = wb.createSheet("超速");
  805 + //表头
  806 + Row row = sheet.createRow(0);
  807 + row.setHeight((short) (1.5 * 256));
  808 + row.createCell(0).setCellValue("异常信息");
  809 + row.createCell(1).setCellValue("最大速度");
  810 + row.createCell(2).setCellValue("开始时间");
  811 + row.createCell(3).setCellValue("结束时间");
  812 + row.createCell(4).setCellValue("持续(秒)");
  813 + row.createCell(5).setCellValue("所在路段");
  814 +
  815 + GpsSpeed_DTO speed;
  816 + for(int i = 0; i < speedList.size(); i++){
  817 + speed = speedList.get(i);
  818 + row = sheet.createRow(i + 1);
  819 + row.createCell(0).setCellValue("超速");
  820 + row.createCell(1).setCellValue(speed.getSpeed());
  821 + row.createCell(2).setCellValue(fmtHHmmss.print(speed.getSt()));
  822 + row.createCell(3).setCellValue(fmtHHmmss.print(speed.getEt()));
  823 + if(speed.getEt() != 0)
  824 + row.createCell(4).setCellValue((speed.getEt() - speed.getSt()) / 1000);
  825 + row.createCell(5).setCellValue("");
  826 + }
  827 + }
  828 +
  829 + if(outboundList.size() > 0){
  830 + Sheet sheet = wb.createSheet("越界");
  831 + //表头
  832 + Row row = sheet.createRow(0);
  833 + row.setHeight((short) (1.5 * 256));
  834 + row.createCell(0).setCellValue("异常信息");
  835 + row.createCell(1).setCellValue("开始时间");
  836 + row.createCell(2).setCellValue("结束时间");
  837 + row.createCell(3).setCellValue("持续(秒)");
  838 + row.createCell(4).setCellValue("所在路段");
  839 + row.createCell(5).setCellValue("路径");
  840 +
  841 + GpsOutbound_DTO outbound;
  842 + //设置路径单元格 水平对齐 填充
  843 + CellStyle cs = wb.createCellStyle();
  844 + cs.setAlignment(HSSFCellStyle.ALIGN_FILL);
  845 + for(int i = 0; i < outboundList.size(); i++){
  846 + outbound = outboundList.get(i);
  847 + row = sheet.createRow(i + 1);
  848 + row.createCell(0).setCellValue("超速");
  849 + row.createCell(1).setCellValue(fmtHHmmss.print(outbound.getSt()));
  850 + row.createCell(2).setCellValue(fmtHHmmss.print(outbound.getEt()));
  851 + if(outbound.getEt() != 0)
  852 + row.createCell(3).setCellValue((outbound.getEt() - outbound.getSt()) / 1000);
  853 + row.createCell(4).setCellValue("");
  854 + row.createCell(5).setCellValue(outbound.getLocations());
  855 +
  856 + row.getCell(5).setCellStyle(cs);
  857 + }
  858 + }
  859 +
  860 + st = st * 1000;
  861 + et = et * 1000;
  862 + String filename = nbbm + "异常信息" + fmt.print(st) + "至" + fmt.print(et) + ".xls";
  863 + try {
  864 + resp.setContentType("application/x-msdownload");
  865 + resp.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
  866 +
  867 + OutputStream out=resp.getOutputStream();
  868 + wb.write(out);
  869 + out.flush();
  870 + out.close();
  871 + } catch (UnsupportedEncodingException e) {
  872 + logger.error("", e);
  873 + } catch (IOException e) {
  874 + logger.error("", e);
  875 + }
  876 + }
  877 +
  878 + @Override
  879 + public void arrivalExcel(String nbbm, long st, long et, HttpServletResponse resp) {
  880 +
  881 + }
  882 +
  883 + @Override
  884 + public List<GpsSpeed_DTO> speeds(String nbbm, long st, long et) {
  885 + st = st * 1000;
  886 + et = et * 1000;
  887 + //按周分区
  888 + Calendar sCal = Calendar.getInstance();
  889 + sCal.setTime(new Date(st));
  890 + int sWeekYear = sCal.get(Calendar.WEEK_OF_YEAR);
  891 + Calendar eCal = Calendar.getInstance();
  892 + eCal.setTime(new Date(et));
  893 + int eWeekYear = eCal.get(Calendar.WEEK_OF_YEAR);
  894 +
  895 + //按年分表
  896 + String tableName = "bsth_c_speeding_" + fmtyyyy.print(st);
  897 +
  898 + List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
  899 + StringBuilder sql = new StringBuilder("");
  900 + long t1,t2;
  901 + DeviceChange dc;
  902 + for(int i = 0,len=dcs.size(); i < len; i++){
  903 + t1 = st;
  904 + t2 = et;
  905 + dc = dcs.get(i);
  906 + if(dc.getSt() > st)
  907 + t1 = dc.getSt();
  908 + if(dc.getEt() < et && dc.getEt()!=0)
  909 + t2 = dc.getEt();
  910 +
  911 + sql.append(" select vehicle, line, up_down, lon, lat, speed,timestamp from "+tableName+" where " +
  912 + " weeks_year in ("+sWeekYear+", "+eWeekYear+") and vehicle='"+dc.getDevice()+"' and timestamp>="+t1+" and timestamp<= " + t2);
  913 +
  914 + if(i == len - 1)
  915 + sql.append(" ORDER BY vehicle,timestamp");
  916 + else
  917 + sql.append(" UNION ");
  918 + }
  919 +
  920 + logger.info("speed sql : " + sql.toString());
  921 + return GpsSpeed_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql.toString()));
  922 + }
  923 +
  924 + @Override
  925 + public List<GpsOutbound_DTO> outbounds(String nbbm, long st, long et) {
  926 + st = st * 1000;
  927 + et = et * 1000;
  928 + //按周分区
  929 + Calendar sCal = Calendar.getInstance();
  930 + sCal.setTime(new Date(st));
  931 + int sWeekYear = sCal.get(Calendar.WEEK_OF_YEAR);
  932 + Calendar eCal = Calendar.getInstance();
  933 + eCal.setTime(new Date(et));
  934 + int eWeekYear = eCal.get(Calendar.WEEK_OF_YEAR);
  935 +
  936 + //按年分表
  937 + String tableName = "bsth_c_outbound_" + fmtyyyy.print(st);
  938 +
  939 + List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
  940 + StringBuilder sql = new StringBuilder("");
  941 + long t1,t2;
  942 + DeviceChange dc;
  943 + for(int i = 0,len=dcs.size(); i < len; i++){
  944 + t1 = st;
  945 + t2 = et;
  946 + dc = dcs.get(i);
  947 + if(dc.getSt() > st)
  948 + t1 = dc.getSt();
  949 + if(dc.getEt() < et && dc.getEt()!=0)
  950 + t2 = dc.getEt();
  951 +
  952 + sql.append("select vehicle,line,up_down,lon,lat,timestamp from "+tableName+" where " +
  953 + " weeks_year in ("+sWeekYear+", "+eWeekYear+") and vehicle='"+dc.getDevice()+"' and timestamp>="+t1+" and timestamp<=" + t2);
  954 +
  955 + if(i == len - 1)
  956 + sql.append(" ORDER BY vehicle,timestamp");
  957 + else
  958 + sql.append(" UNION ");
  959 + }
  960 +
  961 + logger.info("outbounds sql : " + sql.toString());
  962 + return GpsOutbound_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql.toString()));
  963 + }
  964 +
  965 + @Override
  966 + public Map<String, Object> safeDrivList(Map<String, Object> map, int page, int size, String order, String direction) {
  967 + Map<String, Object> rsMap = new HashMap<>();
  968 + try {
  969 + //全量
  970 + List<SafeDriv> list = new ArrayList<>(SafeDrivCenter.findAll());
  971 + //过滤后的
  972 + List<SafeDriv> rs = new ArrayList<>();
  973 + Field[] fields = SafeDriv.class.getDeclaredFields();
  974 + //参与过滤的字段
  975 + List<Field> fs = new ArrayList<>();
  976 + for (Field f : fields) {
  977 + f.setAccessible(true);
  978 + if (map.containsKey(f.getName()))
  979 + fs.add(f);
  980 + }
  981 + //过滤数据
  982 + for (SafeDriv sd : list) {
  983 + if (fieldEquals(fs, sd, map))
  984 + rs.add(sd);
  985 + }
  986 +
  987 + //时间戳排序
  988 + Collections.sort(rs, new Comparator<SafeDriv>() {
  989 + @Override
  990 + public int compare(SafeDriv o1, SafeDriv o2) {
  991 + return o2.getTs().intValue() - o1.getTs().intValue();
  992 + }
  993 + });
  994 +
  995 + //分页
  996 + int count = rs.size(), s = page * size, e = s + size;
  997 + if (e > count)
  998 + e = count;
  999 +
  1000 + rsMap.put("list", rs.subList(s, e));
  1001 + rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);
  1002 + rsMap.put("page", page);
  1003 + rsMap.put("status", ResponseCode.SUCCESS);
  1004 + } catch (Exception e) {
  1005 + logger.error("", e);
  1006 + rsMap.put("status", ResponseCode.ERROR);
  1007 + }
  1008 + return rsMap;
  1009 + }
  1010 +
  1011 + private void matchRoadToGps(HistoryGps_DTO gps, List<Road_DTO> roads) {
  1012 + double min = -1, distance;
  1013 + Road_DTO nearRoad = null;
  1014 + for (Road_DTO road : roads) {
  1015 + distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());
  1016 +
  1017 + if (min > distance || min == -1) {
  1018 + min = distance;
  1019 + nearRoad = road;
  1020 + }
  1021 + }
  1022 +
  1023 + gps.setRoad(nearRoad);
  1024 + gps.setRoadMinDistance(min);
  1025 + }
  1026 +
  1027 +
  1028 + private void matchRoadToGps(HistoryGps_DTOV3 gps, List<Road_DTO> roads) {
  1029 + double min = -1, distance;
  1030 + Road_DTO nearRoad = null;
  1031 + for (Road_DTO road : roads) {
  1032 + distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());
  1033 +
  1034 + if (min > distance || min == -1) {
  1035 + min = distance;
  1036 + nearRoad = road;
  1037 + }
  1038 + }
  1039 +
  1040 + if(min < 200){
  1041 + gps.setSection_code(nearRoad.getROAD_CODE());
  1042 + gps.setSection_name(nearRoad.getROAD_NAME());
  1043 + }
  1044 + else {
  1045 + gps.setSection_code("-00404");
  1046 + gps.setSection_name("未知路段");
  1047 + }
  1048 + //gps.setRoad(nearRoad);
  1049 + //gps.setRoadMinDistance(min);
  1050 + }
  1051 +
  1052 + /**
  1053 + * 去重复
  1054 + *
  1055 + * @param list
  1056 + * @return
  1057 + */
  1058 + private Set<HistoryGps_DTO> removeDuplicate(List<HistoryGps_DTO> list) {
  1059 + Set<HistoryGps_DTO> set = new HashSet<>();
  1060 + for (HistoryGps_DTO gps : list) {
  1061 + set.add(gps);
  1062 + }
  1063 + return set;
  1064 + }
  1065 +
  1066 + /**
  1067 + * 去重复
  1068 + *
  1069 + * @param list
  1070 + * @return
  1071 + */
  1072 + private Set<HistoryGps_DTOV3> removeDuplicateV3(List<HistoryGps_DTOV3> list) {
  1073 + Set<HistoryGps_DTOV3> set = new HashSet<>();
  1074 + for (HistoryGps_DTOV3 gps : list) {
  1075 + set.add(gps);
  1076 + }
  1077 + return set;
  1078 + }
  1079 +
  1080 +
  1081 + private void sortGpsList(final Field f, List<GpsEntity> rs) {
  1082 + Collections.sort(rs, new Comparator<GpsEntity>() {
  1083 +
  1084 + @Override
  1085 + public int compare(GpsEntity o1, GpsEntity o2) {
  1086 + try {
  1087 + if (f.get(o1) == f.get(o2))
  1088 + return 0;
  1089 +
  1090 + if (null == f.get(o1))
  1091 + return 1;
  1092 +
  1093 + if (null == f.get(o2))
  1094 + return -1;
  1095 +
  1096 + return f.get(o1).toString().compareTo(f.get(o2).toString());
  1097 + } catch (Exception e) {
  1098 + logger.error("", e);
  1099 + return -1;
  1100 + }
  1101 + }
  1102 + });
  1103 + }
  1104 +
  1105 + public boolean fieldEquals(List<Field> fs, Object obj, Map<String, Object> map) {
  1106 + try {
  1107 + String fv, v;
  1108 + for (Field f : fs) {
  1109 + if (StringUtils.isEmpty(map.get(f.getName()).toString()))
  1110 + continue;
  1111 +
  1112 + if(f.get(obj) == null)
  1113 + return false;
  1114 +
  1115 + fv = f.get(obj).toString();
  1116 + v = map.get(f.getName()).toString();
  1117 +
  1118 + if(!fv.startsWith(v)/* && !fv.endsWith(v)*/)
  1119 + return false;
  1120 + }
  1121 + } catch (Exception e) {
  1122 + logger.error("", e);
  1123 + return false;
  1124 + }
  1125 + return true;
  1126 + }
  1127 +
  1128 + @Override
  1129 + public List<GpsSpeed> findPosition(String deviceid, String startdate,
  1130 + String enddate) throws ParseException{
  1131 + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1132 + Calendar c = Calendar.getInstance();
  1133 + Date date = sdf.parse(startdate);
  1134 + c.setTime(date);
  1135 + int daysYear = c.get(Calendar.DAY_OF_YEAR);//获取当前是今年的第几天。
  1136 +
  1137 + long startTime = sdf.parse(startdate).getTime();
  1138 + long endTime = sdf.parse(enddate).getTime();
  1139 +
  1140 + String sql = "select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,speed_gps from bsth_c_gps_info where days_year=? and device_id=? and ts >= ? and ts <= ?" +
  1141 + " ORDER BY TS ";
  1142 + Connection conn = null;
  1143 + PreparedStatement ps = null;
  1144 + ResultSet rs = null;
  1145 + List<GpsSpeed> listResult = new ArrayList<GpsSpeed>();
  1146 + GpsSpeed gpsSpeed = null;
  1147 + try {
  1148 + conn = DBUtils_MS.getConnection();
  1149 + ps = conn.prepareStatement(sql);
  1150 + ps.setInt(1, daysYear);
  1151 + ps.setString(2, deviceid);
  1152 + ps.setLong(3,startTime);
  1153 + ps.setLong(4,endTime);
  1154 + rs = ps.executeQuery();
  1155 + Float lon, lat;
  1156 + Location location;
  1157 + while (rs.next()) {
  1158 + gpsSpeed = new GpsSpeed();
  1159 + // to 百度坐标
  1160 + lon = rs.getFloat("LON");
  1161 + lat = rs.getFloat("LAT");
  1162 + location = TransGPS.LocationMake(lon, lat);
  1163 + location = TransGPS.bd_encrypt(TransGPS.transformFromWGSToGCJ(location));
  1164 + gpsSpeed.setVehicle(rs.getString("device_id"));
  1165 + gpsSpeed.setLon((float)location.getLng());
  1166 + gpsSpeed.setLat((float)location.getLat());
  1167 + gpsSpeed.setSpeed(rs.getFloat("speed_gps"));
  1168 + gpsSpeed.setTimestamp(rs.getLong("TS"));
  1169 + // 上下行
  1170 + listResult.add(gpsSpeed);
  1171 + }
  1172 + } catch (Exception e) {
  1173 + e.printStackTrace();
  1174 + } finally {
  1175 + DBUtils_MS.close(rs, ps, conn);
  1176 + }
  1177 + return listResult;
  1178 +
  1179 + }
  1180 +
  1181 + @Override
  1182 + public Map<String, Object> Pagequery(Map<String, Object> map) {
  1183 + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1184 + Integer totalDays = 0;//数据跨越天数
  1185 + try {
  1186 + totalDays = (int) ((sdf.parse(map.get("endDate").toString()+" 23:59:59").getTime()-sdf.parse(map.get("startDate").toString()+" 00:00:00").getTime()+1)/(3600*24*1000))+1;
  1187 + } catch (ParseException e) {
  1188 + e.printStackTrace();
  1189 + }//总页数
  1190 + map.put("totalDays",totalDays);
  1191 + List<GpsSpeed> list=findAll(map);
  1192 + List<GpsSpeed> listResult = new ArrayList<GpsSpeed>();
  1193 + int curPage = 0;//页码
  1194 + int pageData = 0;//每页的记录条数
  1195 + if(list.size()>1){
  1196 + GpsSpeed GpsSpeedNow;//下标为i的车辆行驶记录
  1197 + GpsSpeed GpsSpeedLast;//下标为i-1的车辆行驶记录
  1198 + GpsSpeed spped = null;//整合后的车辆行驶记录
  1199 + String strNow;
  1200 + String strLast;
  1201 + boolean Flag = false;//判断是否有连续超速记录,默认没有
  1202 + for(int i = 1;i<list.size();i++){
  1203 + GpsSpeedNow = list.get(i);
  1204 + GpsSpeedLast = list.get(i-1);
  1205 + strNow = GpsSpeedNow.getVehicle()+GpsSpeedNow.getLine()+GpsSpeedNow.getUp_down();
  1206 + strLast = GpsSpeedLast.getVehicle()+GpsSpeedLast.getLine()+GpsSpeedLast.getUp_down();
  1207 + if(GpsSpeedNow.getSpeed()>60 && GpsSpeedLast.getSpeed()>60 && strNow.equals(strLast)){//如果两条连续的记录都是超速且属于同一辆车。
  1208 + if(Flag==false){//
  1209 + spped = new GpsSpeed();
  1210 + spped.setLine(GpsSpeedLast.getLine());//设置连续超速记录线路
  1211 + spped.setLineName(GpsSpeedLast.getLineName());//设置连续超速记录线路名称
  1212 + spped.setVehicle(GpsSpeedLast.getVehicle());//设置连续超速记录的车辆编号
  1213 + spped.setUp_down(GpsSpeedLast.getUp_down());//设置上下行
  1214 + spped.setLon(GpsSpeedLast.getLon());//设置开始时经度
  1215 + spped.setLat(GpsSpeedLast.getLat());//设置开始时纬度
  1216 + spped.setTimestamp(GpsSpeedLast.getTimestamp());//设置连续超速记录的开始时间
  1217 + spped.setTimestampDate(GpsSpeedLast.getTimestampDate());//设置连续超速记录的开始时间戳
  1218 + }
  1219 + spped.setEndtimestamp(GpsSpeedNow.getTimestamp());//设置结束时间戳
  1220 + spped.setEndtimestampDate(sdf.format(new Date(GpsSpeedNow.getTimestamp())));//设置结束时间
  1221 + spped.setEndlon(GpsSpeedNow.getLon());//设置结束时的经度
  1222 + spped.setEndlat(GpsSpeedNow.getLat());//设置结束时的纬度
  1223 + Flag = true;
  1224 + }else{
  1225 + if(Flag){//如果上一条记录超速。
  1226 + listResult.add(spped);
  1227 + Flag = false;
  1228 + }
  1229 + }
  1230 + }
  1231 + if(listResult.size()>0){
  1232 + Iterator<GpsSpeed> speedIt = listResult.iterator();
  1233 + while(speedIt.hasNext()){
  1234 + GpsSpeed GpsSpeed = speedIt.next();
  1235 + if(GpsSpeed.getEndtimestamp()-GpsSpeed.getTimestamp()<=1000){
  1236 + speedIt.remove();
  1237 + }
  1238 + }
  1239 + }
  1240 + }
  1241 + if(map.get("curPage") == null || map.get("curPage").equals("0")){
  1242 + curPage = 0;
  1243 + }else{
  1244 + curPage = Integer.parseInt((String) map.get("curPage"));
  1245 + }
  1246 + Integer totalPage = totalDays;
  1247 + pageData = listResult.size();//每页的记录条数就是当前页查出的全部数据。
  1248 + Map<String,Object> paramMap = new HashMap<String,Object>();
  1249 + paramMap.put("totalPage", totalPage);
  1250 + paramMap.put("page", curPage);
  1251 + paramMap.put("pageData", pageData);
  1252 + paramMap.put("list", listResult);
  1253 + return paramMap;
  1254 + }
  1255 +
  1256 + @Override
  1257 + public Map<String, Object> allCarsByLine(String lineCode) {
  1258 + Map<String, Object> map = new HashMap();
  1259 + try{
  1260 + List<Map<String, Object>> list = new ArrayList<>();
  1261 + Map<String, Object> item;
  1262 + GpsEntity gps;
  1263 + //当天线路下营运的车辆
  1264 + Set<String> cars = dayOfSchedule.findCarByLineCode(lineCode);
  1265 + ScheduleRealInfo sch;
  1266 + String device;
  1267 +
  1268 + Map<String, Integer> allDevices = new HashMap<>();
  1269 + String execStr = "";
  1270 + D80 d80;
  1271 + for(String nbbm : cars){
  1272 + item = new HashMap<>();
  1273 + device = BasicData.deviceId2NbbmMap.inverse().get(nbbm);
  1274 + allDevices.put(device, 1);
  1275 + item.put("nbbm", nbbm);
  1276 + item.put("device", device);
  1277 +
  1278 + sch = dayOfSchedule.executeCurr(nbbm);
  1279 + if(null != sch){
  1280 + execStr = (sch.getXlDir().equals("0")?"上行":"下行") + "("+sch.getDfsj()+")";
  1281 + if(!sch.getXlBm().equals(lineCode))
  1282 + execStr = sch.getXlName()+execStr;
  1283 + else
  1284 + item.put("schId", sch.getId());
  1285 + item.put("exec", execStr);
  1286 + }
  1287 +
  1288 + gps = gpsRealData.get(device);
  1289 + if(null != gps){
  1290 + item.put("loc", gps.getStationName());
  1291 + item.put("lineCodeReal", gps.getLineId());
  1292 + item.put("status", gps.isOffline()?"离线":"在线");
  1293 + item.put("gpsTs", gps.getTimestamp());
  1294 + }
  1295 + //请求出场时间
  1296 + d80 = PilotReport.qqccMap.get(device);
  1297 + if(null != d80)
  1298 + item.put("qqcc", d80.getTimestamp());
  1299 +
  1300 + list.add(item);
  1301 + }
  1302 +
  1303 + //车载编码落在该线路的设备
  1304 + Set<String> devices = gpsRealData.findDevices(lineCode);
  1305 + for(String d : devices){
  1306 + if(allDevices.containsKey(d))
  1307 + continue;
  1308 +
  1309 + gps = gpsRealData.get(d);
  1310 + if(null == gps)
  1311 + continue;
  1312 +
  1313 + item = new HashMap<>();
  1314 + item.put("nbbm", gps.getNbbm());
  1315 + item.put("device", d);
  1316 + item.put("loc", gps.getStationName());
  1317 + item.put("lineCodeReal", gps.getLineId());
  1318 + item.put("status", gps.isOffline()?"离线":"在线");
  1319 + item.put("gpsTs", gps.getTimestamp());
  1320 +
  1321 + //请求出场时间
  1322 + d80 = PilotReport.qqccMap.get(d);
  1323 + if(null != d80)
  1324 + item.put("qqcc", d80.getTimestamp());
  1325 +
  1326 + list.add(item);
  1327 + }
  1328 +
  1329 + map.put("list", list);
  1330 + map.put("status", ResponseCode.SUCCESS);
  1331 + }catch (Exception e){
  1332 + logger.error("", e);
  1333 + map.put("status", ResponseCode.ERROR);
  1334 + map.put("msg", e.getMessage());
  1335 + }
  1336 + return map;
  1337 + }
  1338 +
  1339 + static List<GpsSpeed> findAll(Map<String, Object> map) {
  1340 + Connection conn = null;
  1341 + PreparedStatement ps = null;
  1342 + ResultSet rs = null;
  1343 + List<GpsSpeed> list=new ArrayList<GpsSpeed>();
  1344 + String sql="select * from bsth_c_gps_info where 1=1 ";
  1345 + Object line=map.get("line");
  1346 + Object nbbm=map.get("nbbm");
  1347 + Object updown=map.get("updown");
  1348 + Object startDate=map.get("startDate");
  1349 + Object endDate=map.get("endDate");
  1350 + Integer totalDays = Integer.valueOf(map.get("totalDays").toString());
  1351 + Integer curPage = 0;//页码
  1352 + if(map.get("curPage") == null || map.get("curPage").equals("0")){
  1353 + curPage = 0;
  1354 + }else{
  1355 + curPage = Integer.parseInt((String) map.get("curPage"));
  1356 + }
  1357 +
  1358 + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1359 + if(line!=null){
  1360 + sql +=" and line_id like'%"+line.toString().trim()+"%'";
  1361 + }
  1362 +
  1363 + if(nbbm!=null){
  1364 + nbbm=BasicData.deviceId2NbbmMap.inverse().get(nbbm);
  1365 + if(nbbm!=null)
  1366 + sql +=" and vehicle like '%"+nbbm.toString()+"%'";
  1367 + }
  1368 +
  1369 + if(updown!=null){
  1370 + sql +="and industry_code like '%"+updown.toString()+"%'";
  1371 + }
  1372 + if(startDate!=null){
  1373 + if (startDate.toString().length()>0) {
  1374 + try {
  1375 + Long t1=sdf.parse(startDate.toString()+" 00:00:00").getTime()+curPage*3600*24*1000;
  1376 + sql += " and ts >="+t1;
  1377 + } catch (ParseException e) {
  1378 + e.printStackTrace();
  1379 + }
  1380 + }
  1381 +
  1382 + }
  1383 + if(endDate!=null){
  1384 + if (endDate.toString().length()>0) {
  1385 + try {
  1386 + Long t2=sdf.parse(endDate.toString()+" 23:59:59").getTime()-(totalDays-1-curPage)*3600*24*1000;
  1387 + sql += " and ts <="+t2;
  1388 + } catch (ParseException e) {
  1389 + e.printStackTrace();
  1390 + }
  1391 + }
  1392 +
  1393 + }
  1394 +
  1395 + try {
  1396 + conn = DBUtils_MS.getConnection();
  1397 + ps = conn.prepareStatement(sql);
  1398 + rs = ps.executeQuery();
  1399 + list = resultSet2Set(rs);
  1400 + } catch (SQLException e) {
  1401 + e.printStackTrace();
  1402 + }finally {
  1403 + DBUtils_MS.close(rs, ps, conn);
  1404 + }
  1405 +
  1406 + return list;
  1407 + }
  1408 +
  1409 + static List<GpsSpeed> resultSet2Set(ResultSet rs) throws SQLException{
  1410 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1411 + List<GpsSpeed> list=new ArrayList<GpsSpeed>();
  1412 + GpsSpeed GpsSpeed;
  1413 + Float lon, lat;
  1414 + Location location;
  1415 + while(rs.next()){
  1416 + lon = rs.getFloat("lon");
  1417 + lat = rs.getFloat("lat");
  1418 + location = TransGPS.LocationMake(lon, lat);
  1419 + location = TransGPS.bd_encrypt(TransGPS.transformFromWGSToGCJ(location));
  1420 + GpsSpeed=new GpsSpeed();
  1421 + GpsSpeed.setLon((float)location.getLng());
  1422 + GpsSpeed.setLat((float)location.getLat());
  1423 + GpsSpeed.setLine(rs.getObject("line_id").toString());
  1424 + //run 时注解
  1425 + GpsSpeed.setLineName(BasicData.lineCode2NameMap.get(GpsSpeed.getLine().toString()));
  1426 + GpsSpeed.setSpeed(Float.valueOf(rs.getObject("speed_gps").toString()));
  1427 + GpsSpeed.setTimestamp((Long.valueOf(rs.getObject("ts").toString())));
  1428 + GpsSpeed.setTimestampDate(sdf.format(new Date(GpsSpeed.getTimestamp())));
  1429 + GpsSpeed.setUp_down(((Integer.valueOf(rs.getObject("service_state").toString())) & 0x10000000)==0?0:1);
  1430 + GpsSpeed.setVehicle(BasicData.deviceId2NbbmMap.get(rs.getObject("device_id").toString()));
  1431 + list.add(GpsSpeed);
  1432 + }
  1433 + return list;
  1434 + }
  1435 +
  1436 +}
  1437 +