Commit 0ccf4fdcfe41753bc4dff866d53c99cb373b3323

Authored by 王通
1 parent 4f1f960c

1.加入历史到离站信息查询接口

src/main/java/com/bsth/server_rs/gps/GpsRestService.java
1   -package com.bsth.server_rs.gps;
2   -
3   -import java.text.ParseException;
4   -import java.util.ArrayList;
5   -import java.util.Collection;
6   -import java.util.Date;
7   -import java.util.HashMap;
8   -import java.util.List;
9   -import java.util.Map;
10   -import java.util.Set;
11   -
12   -import javax.ws.rs.GET;
13   -import javax.ws.rs.Path;
14   -import javax.ws.rs.PathParam;
15   -import javax.ws.rs.Produces;
16   -import javax.ws.rs.core.MediaType;
17   -
18   -import org.springframework.beans.factory.annotation.Autowired;
19   -import org.springframework.stereotype.Component;
20   -
21   -import com.bsth.server_rs.gps.buffer.BasicDataBuffer;
22   -import com.bsth.server_rs.gps.buffer.GpsRealDataBuffer;
23   -import com.bsth.server_rs.gps.dao.HistoryGpsDao;
24   -import com.bsth.server_rs.gps.entity.GpsEntity;
25   -import com.bsth.server_rs.gps.entity.LineInfo;
26   -import com.bsth.server_rs.gps.entity.StopInfo;
27   -import com.bsth.util.ThreadLocalDateUtil;
28   -
29   -/**
30   - * Created by panzhao on 2017/3/28.
31   - */
32   -@Component
33   -@Path("/gps")
34   -@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
35   -public class GpsRestService {
36   -
37   - @Autowired
38   - HistoryGpsDao historyGpsDao;
39   -
40   - @GET
41   - @Path("/{deviceId}")
42   - public GpsEntity findOne(@PathParam("deviceId") String deviceId) {
43   - return GpsRealDataBuffer.get(deviceId);
44   - }
45   -
46   - @GET
47   - @Path("/all")
48   - public Collection<GpsEntity> findAll() {
49   - return GpsRealDataBuffer.all();
50   - }
51   -
52   - @GET
53   - @Path("/history/{nbbm}/{st}/{et}")
54   - public Collection<Map<String, Object>> history(@PathParam("nbbm") String nbbm
55   - , @PathParam("st") String st
56   - , @PathParam("et") String et) {
57   - return historyGpsDao.query(nbbm, Long.parseLong(st), Long.parseLong(et));
58   - }
59   -
60   - @GET
61   - @Path("/gpsReport")
62   - public List<Map<String, Object>> gpsReport() {
63   - List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
64   - Collection<GpsEntity> gpss = GpsRealDataBuffer.all();
65   - Set<Integer> lines = BasicDataBuffer.getAllLine();
66   - for (GpsEntity gps : gpss) {
67   - String device = gps.getDeviceId();
68   - if (lines.contains(Integer.parseInt(gps.getLineId()))) {
69   - Map<String, Object> map = new HashMap<String, Object>();
70   - map.put("vehicleNumberPlate", BasicDataBuffer.getPlateByDevice(device));
71   - try {
72   - map.put("gpsDateTime", ThreadLocalDateUtil.formatDate(new Date(gps.getTimestamp())));
73   - } catch (ParseException e) {
74   - // TODO Auto-generated catch block
75   - e.printStackTrace();
76   - }
77   - map.put("gpsLongitude", gps.getLon());
78   - map.put("gpsLatitude", gps.getLat());
79   - map.put("gpsDirection", gps.getDirection());
80   - map.put("gpsSpeed", gps.getSpeed());
81   - map.put("gpsIsValid", gps.getValid());
82   - map.put("lineId", gps.getLineId());
83   - map.put("lineVersion", 0);
84   - map.put("upDownMark", gps.getUpDown());
85   - map.put("stationOrder", getCurrStop(gps));
86   - map.put("inOutStationState", gps.getInOrOutStation());
87   - map.put("operationalState", gps.getState());
88   -
89   - result.add(map);
90   - }
91   - }
92   -
93   - return result;
94   - }
95   -
96   - private static int getCurrStop(GpsEntity gps) {
97   - int res = 0;
98   -
99   - LineInfo line = BasicDataBuffer.getLineById(Integer.parseInt(gps.getLineId()));
100   - if (line != null) {
101   - List<StopInfo> upStops = new ArrayList<>(line.getStopsUp()), downStops = new ArrayList<>(line.getStopsDown());
102   - int updown = gps.getUpDown();
103   - // 环线、内外换的线路
104   - boolean isRing = line.getLinePlayType() == 1;
105   - if (isRing) {
106   - updown = 0;
107   - downStops.clear();
108   - }
109   - List<StopInfo> stops = new ArrayList<StopInfo>();
110   - stops.addAll(upStops);
111   - stops.addAll(downStops);
112   -
113   - int idx = 1;
114   - if (updown == 0) {
115   - for (StopInfo stop : upStops) {
116   - if (gps.getStopNo().trim().equals(stop.getStationCod())) break;
117   - idx++;
118   - }
119   - } else {
120   - for (StopInfo stop : downStops) {
121   - if (gps.getStopNo().trim().equals(stop.getStationCod())) break;
122   - idx++;
123   - }
124   - }
125   - if (idx <= stops.size()) {
126   - res = idx;
127   - }
128   - }
129   -
130   - return res;
131   - }
132   -}
  1 +package com.bsth.server_rs.gps;
  2 +
  3 +import java.text.ParseException;
  4 +import java.util.ArrayList;
  5 +import java.util.Collection;
  6 +import java.util.Date;
  7 +import java.util.HashMap;
  8 +import java.util.List;
  9 +import java.util.Map;
  10 +import java.util.Set;
  11 +
  12 +import javax.ws.rs.GET;
  13 +import javax.ws.rs.Path;
  14 +import javax.ws.rs.PathParam;
  15 +import javax.ws.rs.Produces;
  16 +import javax.ws.rs.core.MediaType;
  17 +
  18 +import com.bsth.server_rs.gps.entity.HistoryArrivalEntity;
  19 +import org.springframework.beans.factory.annotation.Autowired;
  20 +import org.springframework.stereotype.Component;
  21 +
  22 +import com.bsth.server_rs.gps.buffer.BasicDataBuffer;
  23 +import com.bsth.server_rs.gps.buffer.GpsRealDataBuffer;
  24 +import com.bsth.server_rs.gps.dao.HistoryGpsDao;
  25 +import com.bsth.server_rs.gps.entity.GpsEntity;
  26 +import com.bsth.server_rs.gps.entity.LineInfo;
  27 +import com.bsth.server_rs.gps.entity.StopInfo;
  28 +import com.bsth.util.ThreadLocalDateUtil;
  29 +
  30 +/**
  31 + * Created by panzhao on 2017/3/28.
  32 + */
  33 +@Component
  34 +@Path("/gps")
  35 +@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  36 +public class GpsRestService {
  37 +
  38 + @Autowired
  39 + HistoryGpsDao historyGpsDao;
  40 +
  41 + @GET
  42 + @Path("/{deviceId}")
  43 + public GpsEntity findOne(@PathParam("deviceId") String deviceId) {
  44 + return GpsRealDataBuffer.get(deviceId);
  45 + }
  46 +
  47 + @GET
  48 + @Path("/all")
  49 + public Collection<GpsEntity> findAll() {
  50 + return GpsRealDataBuffer.all();
  51 + }
  52 +
  53 + @GET
  54 + @Path("/history/{nbbm}/{st}/{et}")
  55 + public Collection<Map<String, Object>> history(@PathParam("nbbm") String nbbm
  56 + , @PathParam("st") String st
  57 + , @PathParam("et") String et) {
  58 + return historyGpsDao.query(nbbm, Long.parseLong(st), Long.parseLong(et));
  59 + }
  60 +
  61 + @GET
  62 + @Path("/history-arrival/{line}/{st}/{et}")
  63 + public List<HistoryArrivalEntity> historyArrival(@PathParam("line") String line
  64 + , @PathParam("st") String st
  65 + , @PathParam("et") String et) {
  66 + return historyGpsDao.queryArrival(line, Long.parseLong(st), Long.parseLong(et));
  67 + }
  68 +
  69 + @GET
  70 + @Path("/gpsReport")
  71 + public List<Map<String, Object>> gpsReport() {
  72 + List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
  73 + Collection<GpsEntity> gpss = GpsRealDataBuffer.all();
  74 + Set<Integer> lines = BasicDataBuffer.getAllLine();
  75 + for (GpsEntity gps : gpss) {
  76 + String device = gps.getDeviceId();
  77 + if (lines.contains(Integer.parseInt(gps.getLineId()))) {
  78 + Map<String, Object> map = new HashMap<String, Object>();
  79 + map.put("vehicleNumberPlate", BasicDataBuffer.getPlateByDevice(device));
  80 + try {
  81 + map.put("gpsDateTime", ThreadLocalDateUtil.formatDate(new Date(gps.getTimestamp())));
  82 + } catch (ParseException e) {
  83 + // TODO Auto-generated catch block
  84 + e.printStackTrace();
  85 + }
  86 + map.put("gpsLongitude", gps.getLon());
  87 + map.put("gpsLatitude", gps.getLat());
  88 + map.put("gpsDirection", gps.getDirection());
  89 + map.put("gpsSpeed", gps.getSpeed());
  90 + map.put("gpsIsValid", gps.getValid());
  91 + map.put("lineId", gps.getLineId());
  92 + map.put("lineVersion", 0);
  93 + map.put("upDownMark", gps.getUpDown());
  94 + map.put("stationOrder", getCurrStop(gps));
  95 + map.put("inOutStationState", gps.getInOrOutStation());
  96 + map.put("operationalState", gps.getState());
  97 +
  98 + result.add(map);
  99 + }
  100 + }
  101 +
  102 + return result;
  103 + }
  104 +
  105 + private static int getCurrStop(GpsEntity gps) {
  106 + int res = 0;
  107 +
  108 + LineInfo line = BasicDataBuffer.getLineById(Integer.parseInt(gps.getLineId()));
  109 + if (line != null) {
  110 + List<StopInfo> upStops = new ArrayList<>(line.getStopsUp()), downStops = new ArrayList<>(line.getStopsDown());
  111 + int updown = gps.getUpDown();
  112 + // 环线、内外换的线路
  113 + boolean isRing = line.getLinePlayType() == 1;
  114 + if (isRing) {
  115 + updown = 0;
  116 + downStops.clear();
  117 + }
  118 + List<StopInfo> stops = new ArrayList<StopInfo>();
  119 + stops.addAll(upStops);
  120 + stops.addAll(downStops);
  121 +
  122 + int idx = 1;
  123 + if (updown == 0) {
  124 + for (StopInfo stop : upStops) {
  125 + if (gps.getStopNo().trim().equals(stop.getStationCod())) break;
  126 + idx++;
  127 + }
  128 + } else {
  129 + for (StopInfo stop : downStops) {
  130 + if (gps.getStopNo().trim().equals(stop.getStationCod())) break;
  131 + idx++;
  132 + }
  133 + }
  134 + if (idx <= stops.size()) {
  135 + res = idx;
  136 + }
  137 + }
  138 +
  139 + return res;
  140 + }
  141 +}
... ...
src/main/java/com/bsth/server_rs/gps/dao/HistoryGpsDao.java
1   -package com.bsth.server_rs.gps.dao;
2   -
3   -import com.bsth.redis.util.DateUtils;
4   -import com.bsth.server_rs.base_info.car.Car;
5   -import com.bsth.server_rs.base_info.car.buffer.CarBufferData;
6   -import com.bsth.server_rs.gps.entity.DeviceChange;
7   -import com.bsth.server_rs.gps.entity.HistoryGpsEntity;
8   -import com.bsth.util.DBUtils_MS;
9   -import org.apache.commons.lang3.StringUtils;
10   -import org.joda.time.format.DateTimeFormat;
11   -import org.joda.time.format.DateTimeFormatter;
12   -import org.slf4j.Logger;
13   -import org.slf4j.LoggerFactory;
14   -import org.springframework.beans.factory.annotation.Autowired;
15   -import org.springframework.jdbc.core.BeanPropertyRowMapper;
16   -import org.springframework.jdbc.core.JdbcTemplate;
17   -import org.springframework.stereotype.Component;
18   -
19   -import java.util.*;
20   -
21   -/**
22   - * Created by panzhao on 2017/8/31.
23   - */
24   -@Component
25   -public class HistoryGpsDao {
26   -
27   - Logger logger = LoggerFactory.getLogger(this.getClass());
28   -
29   - @Autowired
30   - JdbcTemplate jdbcTemplate;
31   -
32   - /**
33   - * 最大查询间隔
34   - */
35   - private static final long GPS_RANGE = 1000 * 60 * 60 * 24;
36   -
37   - private static DateTimeFormatter fmtyyyy = DateTimeFormat.forPattern("yyyy");
38   -
39   - public Collection<Map<String, Object>> query(String nbbm, Long st, Long et) {
40   - List<Map<String, Object>> list = new ArrayList<>();
41   - if (et - st > GPS_RANGE)
42   - return list;
43   -
44   - // day_of_year 分区字段
45   - Calendar sCal = Calendar.getInstance();
46   - sCal.setTime(new Date(st));
47   - int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
48   - Calendar eCal = Calendar.getInstance();
49   - eCal.setTime(new Date(et));
50   - int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR);
51   -
52   - List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
53   -
54   - //按年分表
55   - String tableName = "bsth_c_gps_info_" + fmtyyyy.print(st);
56   -
57   - StringBuilder sql = new StringBuilder("");
58   - long t1,t2;
59   - DeviceChange dc;
60   - for(int i = 0,len=dcs.size(); i < len; i++){
61   - t1 = st;
62   - t2 = et;
63   - dc = dcs.get(i);
64   - if(dc.getSt() > st)
65   - t1 = dc.getSt();
66   - if(dc.getEt() < et && dc.getEt()!=0)
67   - t2 = dc.getEt();
68   -
69   - 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+") " +
70   - " and device_id='"+dc.getDevice()+"' and ts >= "+t1+" and ts <= "+t2+" ");
71   -
72   - if(i == len - 1)
73   - sql.append(" ORDER BY device_id,ts,stop_no");
74   - else
75   - sql.append(" UNION ");
76   - }
77   -
78   - logger.info("轨迹回放 nbbm: " + nbbm + " -st: " + st + " -et: " + et + " -sql: " + sql.toString());
79   -
80   - //查询GPS数据
81   - JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
82   - List<Map<String, Object>> dataList = jdbcTemplate_ms.queryForList(sql.toString());
83   -
84   - Float lon, lat;
85   - int inOutStop;
86   - long serviceState;
87   -
88   - Map<String, Object> map;
89   - for(Map<String, Object> rs : dataList){
90   - serviceState = map_get_long(rs, "SERVICE_STATE");
91   - if(getGpsValid(serviceState) == 1)
92   - continue;
93   -
94   - map = new HashMap<>();
95   -
96   - lon = map_get_float(rs, "LON");
97   - lat = map_get_float(rs, "LAT");
98   - //原始坐标
99   - map.put("lon", lon);
100   - map.put("lat", lat);
101   -
102   - map.put("deviceId", map_get_str(rs, "DEVICE_ID"));
103   - map.put("ts", map_get_long(rs, "TS"));
104   - map.put("timestamp", map_get_long(rs, "TS"));
105   - map.put("stopNo", map_get_str(rs, "STOP_NO"));
106   - map.put("direction", map_get_float(rs,"DIRECTION"));
107   -
108   - map.put("lineId", map_get_str(rs, "LINE_ID"));
109   - map.put("speed", map_get_float(rs,"SPEED_GPS"));
110   -
111   - inOutStop = Integer.parseInt(rs.get("INOUT_STOP").toString());
112   - map.put("inout_stop", inOutStop);
113   -
114   -
115   - map.put("nbbm", nbbm);
116   - map.put("state", getService(serviceState));
117   - // 上下行
118   - map.put("upDown", getUpOrDown(serviceState));
119   - //路段编码
120   - map.put("section_code", map_get_str(rs,"SECTION_CODE"));
121   - list.add(map);
122   - }
123   - // 按时间排序
124   - Collections.sort(list, new Comparator<Map<String, Object>>() {
125   -
126   - @Override
127   - public int compare(Map<String, Object> o1, Map<String, Object> o2) {
128   - return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
129   - }
130   - });
131   -
132   - return list;
133   - }
134   -
135   -
136   - private List<DeviceChange> findDeviceChangeLogs(String nbbm, long et, long st){
137   - List<DeviceChange> dcs = null;
138   - List<DeviceChange> rs = new ArrayList<>();
139   - try{
140   -
141   - 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"
142   - , BeanPropertyRowMapper.newInstance(DeviceChange.class));
143   -
144   -
145   - //生成一条初始记录
146   - if(dcs.size() > 0){
147   - DeviceChange first = dcs.get(0);
148   -
149   - DeviceChange initDv = new DeviceChange();
150   - initDv.setDevice(first.getOldDevice());
151   - if(StringUtils.isNotEmpty(initDv.getDevice())){
152   - initDv.setNbbm(first.getNbbm());
153   - initDv.setSt(0);
154   - initDv.setEt(first.getSt());
155   - dcs.add(0, initDv);
156   - }
157   - }
158   - for(int i = 0,len=dcs.size(); i < len - 1; i++){
159   - dcs.get(i).setEt(dcs.get(i + 1).getSt());
160   - }
161   -
162   - for(DeviceChange dc : dcs){
163   - if(dc.getEt() < st && dc.getEt() != 0)
164   - continue;
165   - if(dc.getSt() > et)
166   - continue;
167   -
168   - rs.add(dc);
169   - }
170   -
171   - //没有设备变更记录,则参考车辆信息上的设备号
172   - if(null == rs || rs.size() == 0){
173   - Car car = CarBufferData.findOne(nbbm);
174   -
175   - if(null != car){
176   - DeviceChange dc = new DeviceChange();
177   - dc.setNbbm(nbbm);
178   - dc.setDevice(car.getEquipmentCode());
179   - dc.setSt(st);
180   - dc.setEt(et);
181   - dc.setType(1);
182   -
183   - rs.add(dc);
184   - }
185   - }
186   - }catch (Exception e){
187   - logger.error("", e);
188   - }
189   - return rs;
190   - }
191   -
192   - private static DateTimeFormatter fmtyyyyMMdd = DateTimeFormat.forPattern("yyyy-MM-dd");
193   - private List<HistoryGpsEntity> query(String deviceId, Calendar sCal, Calendar eCal) {
194   - int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
195   - int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR);
196   - long st = sCal.getTimeInMillis();
197   - long et = eCal.getTimeInMillis();
198   -
199   - List<HistoryGpsEntity> list = new ArrayList<>();
200   - // 如果是同一天
201   - if (sDayOfYear == eDayOfYear) {
202   - list = query(sDayOfYear, st, et, deviceId);
203   - } else {
204   - // 跨天
205   - Long tempSt, tempEt;
206   - for (int i = sDayOfYear; i <= eDayOfYear; i++) {
207   -
208   - if (i == sDayOfYear) {
209   - tempSt = st;
210   - tempEt = fmtyyyyMMdd.parseMillis(fmtyyyyMMdd.print(tempSt)) + 1000 * 60 * 60 * 24;
211   - } else if (i == eDayOfYear) {
212   - tempSt = fmtyyyyMMdd.parseMillis(fmtyyyyMMdd.print(et));
213   - tempEt = et;
214   - } else {
215   - tempSt = DateUtils.getTimesmorning(sCal) * 1000;
216   - tempEt = DateUtils.getTimesnight(sCal);
217   - }
218   -
219   - list.addAll(query(sDayOfYear, tempSt, tempEt, deviceId));
220   - // 加一天
221   - sCal.add(Calendar.DATE, 1);
222   - }
223   - }
224   - return list;
225   - }
226   -
227   - private List<HistoryGpsEntity> query(int dayOfYear, Long st, Long et, String deviceId) {
228   - String sql = "select device_id,line_id,service_state,direction,lon,lat,ts,stop_no,speed_gps as speed,inout_stop,section_code from bsth_c_gps_info where days_year=" + dayOfYear + " and device_id='"+deviceId+"' and ts > " + st + " and ts < " + et;
229   -
230   - JdbcTemplate jdbcTemplate = new JdbcTemplate(DBUtils_MS.getDataSource());
231   - List<HistoryGpsEntity> list = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(HistoryGpsEntity.class));
232   - return list;
233   - }
234   -
235   - /**
236   - * 王通 2016/6/29 9:23:24 获取车辆线路上下行
237   - *
238   - * @return -1无效 0上行 1下行
239   - */
240   - private static byte getUpOrDown(long serviceState) {
241   - if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000
242   - || (serviceState & 0x01000000) == 0x01000000 || (serviceState & 0x08000000) == 0x08000000)
243   - return -1;
244   - return (byte) (((serviceState & 0x10000000) == 0x10000000) ? 1 : 0);
245   - }
246   -
247   - /**
248   - * 获取运营状态
249   - *
250   - * @return -1无效 0运营 1未运营
251   - */
252   - private static byte getService(long serviceState) {
253   - if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000)
254   - return -1;
255   - return (byte) (((serviceState & 0x02000000) == 0x02000000) ? 1 : 0);
256   - }
257   -
258   - private String map_get_str(Map<String, Object> map, String key){
259   - return map.containsKey(key)?map.get(key).toString():"";
260   - }
261   -
262   - private Long map_get_long(Map<String, Object> map, String key){
263   - return map.containsKey(key)?Long.parseLong(map.get(key).toString()):-1;
264   - }
265   -
266   - private Float map_get_float(Map<String, Object> map, String key){
267   - return map.containsKey(key)?Float.parseFloat(map.get(key).toString()):-1;
268   - }
269   -
270   - public static byte getGpsValid(long serviceState) {
271   - return (byte)(((serviceState & 0x80000000) == 0x80000000) ? 1 : 0);
272   - }
273   -}
  1 +package com.bsth.server_rs.gps.dao;
  2 +
  3 +import com.bsth.redis.util.DateUtils;
  4 +import com.bsth.server_rs.base_info.car.Car;
  5 +import com.bsth.server_rs.base_info.car.buffer.CarBufferData;
  6 +import com.bsth.server_rs.gps.entity.DeviceChange;
  7 +import com.bsth.server_rs.gps.entity.HistoryArrivalEntity;
  8 +import com.bsth.server_rs.gps.entity.HistoryGpsEntity;
  9 +import com.bsth.util.DBUtils_MS;
  10 +import org.apache.commons.lang3.StringUtils;
  11 +import org.joda.time.format.DateTimeFormat;
  12 +import org.joda.time.format.DateTimeFormatter;
  13 +import org.slf4j.Logger;
  14 +import org.slf4j.LoggerFactory;
  15 +import org.springframework.beans.factory.annotation.Autowired;
  16 +import org.springframework.jdbc.core.BeanPropertyRowMapper;
  17 +import org.springframework.jdbc.core.JdbcTemplate;
  18 +import org.springframework.stereotype.Component;
  19 +
  20 +import java.util.*;
  21 +
  22 +/**
  23 + * Created by panzhao on 2017/8/31.
  24 + */
  25 +@Component
  26 +public class HistoryGpsDao {
  27 +
  28 + Logger logger = LoggerFactory.getLogger(this.getClass());
  29 +
  30 + @Autowired
  31 + JdbcTemplate jdbcTemplate;
  32 +
  33 + /**
  34 + * 最大查询间隔
  35 + */
  36 + private static final long GPS_RANGE = 1000 * 60 * 60 * 24;
  37 +
  38 + private static DateTimeFormatter fmtyyyy = DateTimeFormat.forPattern("yyyy");
  39 +
  40 + public Collection<Map<String, Object>> query(String nbbm, Long st, Long et) {
  41 + List<Map<String, Object>> list = new ArrayList<>();
  42 + if (et - st > GPS_RANGE)
  43 + return list;
  44 +
  45 + // day_of_year 分区字段
  46 + Calendar sCal = Calendar.getInstance();
  47 + sCal.setTime(new Date(st));
  48 + int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
  49 + Calendar eCal = Calendar.getInstance();
  50 + eCal.setTime(new Date(et));
  51 + int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR);
  52 +
  53 + List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
  54 +
  55 + //按年分表
  56 + String tableName = "bsth_c_gps_info_" + fmtyyyy.print(st);
  57 +
  58 + StringBuilder sql = new StringBuilder("");
  59 + long t1,t2;
  60 + DeviceChange dc;
  61 + for(int i = 0,len=dcs.size(); i < len; i++){
  62 + t1 = st;
  63 + t2 = et;
  64 + dc = dcs.get(i);
  65 + if(dc.getSt() > st)
  66 + t1 = dc.getSt();
  67 + if(dc.getEt() < et && dc.getEt()!=0)
  68 + t2 = dc.getEt();
  69 +
  70 + 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+") " +
  71 + " and device_id='"+dc.getDevice()+"' and ts >= "+t1+" and ts <= "+t2+" ");
  72 +
  73 + if(i == len - 1)
  74 + sql.append(" ORDER BY device_id,ts,stop_no");
  75 + else
  76 + sql.append(" UNION ");
  77 + }
  78 +
  79 + logger.info("轨迹回放 nbbm: " + nbbm + " -st: " + st + " -et: " + et + " -sql: " + sql.toString());
  80 +
  81 + //查询GPS数据
  82 + JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
  83 + List<Map<String, Object>> dataList = jdbcTemplate_ms.queryForList(sql.toString());
  84 +
  85 + Float lon, lat;
  86 + int inOutStop;
  87 + long serviceState;
  88 +
  89 + Map<String, Object> map;
  90 + for(Map<String, Object> rs : dataList){
  91 + serviceState = map_get_long(rs, "SERVICE_STATE");
  92 + if(getGpsValid(serviceState) == 1)
  93 + continue;
  94 +
  95 + map = new HashMap<>();
  96 +
  97 + lon = map_get_float(rs, "LON");
  98 + lat = map_get_float(rs, "LAT");
  99 + //原始坐标
  100 + map.put("lon", lon);
  101 + map.put("lat", lat);
  102 +
  103 + map.put("deviceId", map_get_str(rs, "DEVICE_ID"));
  104 + map.put("ts", map_get_long(rs, "TS"));
  105 + map.put("timestamp", map_get_long(rs, "TS"));
  106 + map.put("stopNo", map_get_str(rs, "STOP_NO"));
  107 + map.put("direction", map_get_float(rs,"DIRECTION"));
  108 +
  109 + map.put("lineId", map_get_str(rs, "LINE_ID"));
  110 + map.put("speed", map_get_float(rs,"SPEED_GPS"));
  111 +
  112 + inOutStop = Integer.parseInt(rs.get("INOUT_STOP").toString());
  113 + map.put("inout_stop", inOutStop);
  114 +
  115 +
  116 + map.put("nbbm", nbbm);
  117 + map.put("state", getService(serviceState));
  118 + // 上下行
  119 + map.put("upDown", getUpOrDown(serviceState));
  120 + //路段编码
  121 + map.put("section_code", map_get_str(rs,"SECTION_CODE"));
  122 + list.add(map);
  123 + }
  124 + // 按时间排序
  125 + Collections.sort(list, new Comparator<Map<String, Object>>() {
  126 +
  127 + @Override
  128 + public int compare(Map<String, Object> o1, Map<String, Object> o2) {
  129 + return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
  130 + }
  131 + });
  132 +
  133 + return list;
  134 + }
  135 +
  136 + public List<HistoryArrivalEntity> queryArrival(String line, Long st, Long et) {
  137 + if (et - st > GPS_RANGE)
  138 + return new ArrayList<>();
  139 +
  140 + // day_of_year 分区字段
  141 + Calendar sCal = Calendar.getInstance();
  142 + sCal.setTime(new Date(st));
  143 + int startWeek = sCal.get(Calendar.WEEK_OF_YEAR), startYear = sCal.get(Calendar.YEAR);
  144 + Calendar eCal = Calendar.getInstance();
  145 + eCal.setTime(new Date(et));
  146 + int endWeek = eCal.get(Calendar.WEEK_OF_YEAR), endYear = eCal.get(Calendar.YEAR);
  147 +
  148 + //按年分表
  149 + String tableName1 = "bsth_c_arrival_info_" + startYear, tableName2 = "bsth_c_arrival_info_" + endYear;
  150 +
  151 + String sql = "SELECT device_id, line_id, stop_no, ts, up_down, in_out FROM %s WHERE weeks_year = %d AND line_id = %s AND ts BETWEEN %d AND %d";
  152 + StringBuilder builder = new StringBuilder(String.format(sql, tableName1, startWeek, line, st, et));
  153 + if (startYear == endYear) {
  154 + if (startWeek != endWeek) {
  155 + builder.append(" UNION ").append(String.format(sql, tableName1, endWeek, line, st, et));
  156 + }
  157 + } else {
  158 + builder.append(" UNION ").append(String.format(sql, tableName2, endWeek, line, st, et));
  159 + }
  160 +
  161 + logger.info("到离站查询 line: {} -st: {} -et: {} -sql: {}", line, st, et, builder);
  162 +
  163 + //查询GPS数据
  164 + JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
  165 + return jdbcTemplate_ms.query(builder.toString(), BeanPropertyRowMapper.newInstance(HistoryArrivalEntity.class));
  166 + }
  167 +
  168 +
  169 + private List<DeviceChange> findDeviceChangeLogs(String nbbm, long et, long st){
  170 + List<DeviceChange> dcs = null;
  171 + List<DeviceChange> rs = new ArrayList<>();
  172 + try{
  173 +
  174 + 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"
  175 + , BeanPropertyRowMapper.newInstance(DeviceChange.class));
  176 +
  177 +
  178 + //生成一条初始记录
  179 + if(dcs.size() > 0){
  180 + DeviceChange first = dcs.get(0);
  181 +
  182 + DeviceChange initDv = new DeviceChange();
  183 + initDv.setDevice(first.getOldDevice());
  184 + if(StringUtils.isNotEmpty(initDv.getDevice())){
  185 + initDv.setNbbm(first.getNbbm());
  186 + initDv.setSt(0);
  187 + initDv.setEt(first.getSt());
  188 + dcs.add(0, initDv);
  189 + }
  190 + }
  191 + for(int i = 0,len=dcs.size(); i < len - 1; i++){
  192 + dcs.get(i).setEt(dcs.get(i + 1).getSt());
  193 + }
  194 +
  195 + for(DeviceChange dc : dcs){
  196 + if(dc.getEt() < st && dc.getEt() != 0)
  197 + continue;
  198 + if(dc.getSt() > et)
  199 + continue;
  200 +
  201 + rs.add(dc);
  202 + }
  203 +
  204 + //没有设备变更记录,则参考车辆信息上的设备号
  205 + if(null == rs || rs.size() == 0){
  206 + Car car = CarBufferData.findOne(nbbm);
  207 +
  208 + if(null != car){
  209 + DeviceChange dc = new DeviceChange();
  210 + dc.setNbbm(nbbm);
  211 + dc.setDevice(car.getEquipmentCode());
  212 + dc.setSt(st);
  213 + dc.setEt(et);
  214 + dc.setType(1);
  215 +
  216 + rs.add(dc);
  217 + }
  218 + }
  219 + }catch (Exception e){
  220 + logger.error("", e);
  221 + }
  222 + return rs;
  223 + }
  224 +
  225 + private static DateTimeFormatter fmtyyyyMMdd = DateTimeFormat.forPattern("yyyy-MM-dd");
  226 + private List<HistoryGpsEntity> query(String deviceId, Calendar sCal, Calendar eCal) {
  227 + int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
  228 + int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR);
  229 + long st = sCal.getTimeInMillis();
  230 + long et = eCal.getTimeInMillis();
  231 +
  232 + List<HistoryGpsEntity> list = new ArrayList<>();
  233 + // 如果是同一天
  234 + if (sDayOfYear == eDayOfYear) {
  235 + list = query(sDayOfYear, st, et, deviceId);
  236 + } else {
  237 + // 跨天
  238 + Long tempSt, tempEt;
  239 + for (int i = sDayOfYear; i <= eDayOfYear; i++) {
  240 +
  241 + if (i == sDayOfYear) {
  242 + tempSt = st;
  243 + tempEt = fmtyyyyMMdd.parseMillis(fmtyyyyMMdd.print(tempSt)) + 1000 * 60 * 60 * 24;
  244 + } else if (i == eDayOfYear) {
  245 + tempSt = fmtyyyyMMdd.parseMillis(fmtyyyyMMdd.print(et));
  246 + tempEt = et;
  247 + } else {
  248 + tempSt = DateUtils.getTimesmorning(sCal) * 1000;
  249 + tempEt = DateUtils.getTimesnight(sCal);
  250 + }
  251 +
  252 + list.addAll(query(sDayOfYear, tempSt, tempEt, deviceId));
  253 + // 加一天
  254 + sCal.add(Calendar.DATE, 1);
  255 + }
  256 + }
  257 + return list;
  258 + }
  259 +
  260 + private List<HistoryGpsEntity> query(int dayOfYear, Long st, Long et, String deviceId) {
  261 + String sql = "select device_id,line_id,service_state,direction,lon,lat,ts,stop_no,speed_gps as speed,inout_stop,section_code from bsth_c_gps_info where days_year=" + dayOfYear + " and device_id='"+deviceId+"' and ts > " + st + " and ts < " + et;
  262 +
  263 + JdbcTemplate jdbcTemplate = new JdbcTemplate(DBUtils_MS.getDataSource());
  264 + List<HistoryGpsEntity> list = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(HistoryGpsEntity.class));
  265 + return list;
  266 + }
  267 +
  268 + /**
  269 + * 王通 2016/6/29 9:23:24 获取车辆线路上下行
  270 + *
  271 + * @return -1无效 0上行 1下行
  272 + */
  273 + private static byte getUpOrDown(long serviceState) {
  274 + if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000
  275 + || (serviceState & 0x01000000) == 0x01000000 || (serviceState & 0x08000000) == 0x08000000)
  276 + return -1;
  277 + return (byte) (((serviceState & 0x10000000) == 0x10000000) ? 1 : 0);
  278 + }
  279 +
  280 + /**
  281 + * 获取运营状态
  282 + *
  283 + * @return -1无效 0运营 1未运营
  284 + */
  285 + private static byte getService(long serviceState) {
  286 + if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000)
  287 + return -1;
  288 + return (byte) (((serviceState & 0x02000000) == 0x02000000) ? 1 : 0);
  289 + }
  290 +
  291 + private String map_get_str(Map<String, Object> map, String key){
  292 + return map.containsKey(key)?map.get(key).toString():"";
  293 + }
  294 +
  295 + private Long map_get_long(Map<String, Object> map, String key){
  296 + return map.containsKey(key)?Long.parseLong(map.get(key).toString()):-1;
  297 + }
  298 +
  299 + private Float map_get_float(Map<String, Object> map, String key){
  300 + return map.containsKey(key)?Float.parseFloat(map.get(key).toString()):-1;
  301 + }
  302 +
  303 + public static byte getGpsValid(long serviceState) {
  304 + return (byte)(((serviceState & 0x80000000) == 0x80000000) ? 1 : 0);
  305 + }
  306 +}
... ...
src/main/java/com/bsth/server_rs/schedule/real/ScheduleRealService.java
... ... @@ -360,7 +360,7 @@ public class ScheduleRealService implements InitializingBean {
360 360  
361 361 @Override
362 362 public void afterPropertiesSet() throws Exception {
363   - Application.mainServices.scheduleWithFixedDelay(new Runnable() {
  363 + /*Application.mainServices.scheduleWithFixedDelay(new Runnable() {
364 364 @Override
365 365 public void run() {
366 366 try {
... ... @@ -419,6 +419,6 @@ public class ScheduleRealService implements InitializingBean {
419 419 logger.error("kafka发电子路单调度异常", e);
420 420 }
421 421 }
422   - }, 30, 240, TimeUnit.SECONDS);
  422 + }, 30, 240, TimeUnit.SECONDS);*/
423 423 }
424 424 }
... ...