Jelajahi Sumber

Fixing of GetLastObservations service

Complete different approach of the GetLastObserations service functions
to load last observations from DB

Small fix of Export functions
mkepka 3 tahun lalu
induk
melakukan
0e7f18799b

+ 23 - 0
src/main/java/cz/hsrs/db/model/composite/ObservationValue.java

@@ -10,6 +10,11 @@ import java.util.logging.Level;
 import cz.hsrs.db.DBObject;
 import cz.hsrs.db.pool.SQLExecutor;
 
+/**
+ * Class models simple observation
+ * @author mkepka
+ *
+ */
 public class ObservationValue implements DBObject {
 
     private final double value;
@@ -23,12 +28,30 @@ public class ObservationValue implements DBObject {
         this(0, null, 0);
     }
 
+    /**
+     * 
+     * @param value - observed_value
+     * @param timeStamp - time_stamp
+     * @param gid
+     */
     public ObservationValue(double value, String timeStamp, int gid) {
         super();
         this.value = value;
         this.time_string = timeStamp;
         this.gid = gid;
     }
+    
+    /**
+     * 
+     * @param value - observed_value
+     * @param timeStamp - time_stamp
+     */
+    public ObservationValue(double value, String timeStamp) {
+        super();
+        this.value = value;
+        this.time_string = timeStamp;
+        this.gid = 0;
+    }
 
     @Override
     public DBObject getDBObject(ResultSet set) throws SQLException {

+ 21 - 5
src/main/java/cz/hsrs/db/util/ExportUtil.java

@@ -135,6 +135,16 @@ public class ExportUtil {
         return CSV;
     }
 
+    /**
+     * 
+     * @param sensorId
+     * @param groupId
+     * @param fromTime
+     * @param toTime
+     * @param nullable
+     * @return
+     * @throws SQLException
+     */
     public static String getObservationsBySensorByGroup(long sensorId, int groupId, LocalDateTime fromTime, LocalDateTime toTime, boolean nullable) throws SQLException {
         List<String> unitIds = UnitUtil.getUnitsBySensorIdByGroup(sensorId, groupId).stream().map(u -> String.valueOf(u.getUnitId())).collect(toList());
         String unitIdsStr = String.join(",", unitIds);
@@ -158,15 +168,21 @@ public class ExportUtil {
             throw new SQLException("unit_id does not contain only numbers.");
         }
 
-        String sqlPositionQuery = String.format("SELECT u_p.unit_id, ST_X(u_p.the_geom) AS lon, ST_Y(u_p.the_geom) AS lat FROM units_positions AS u_p\n" +
-                "JOIN units AS u ON u.unit_id = u_p.unit_id\n" +
-                "WHERE u_p.unit_id IN (%s) AND u.is_mobile = FALSE;", unitIds);
+        String sqlPositionQuery = String.format("SELECT u_p.unit_id, ST_X(u_p.the_geom) AS lon, ST_Y(u_p.the_geom) AS lat"
+        		+ " FROM units_positions AS u_p\n"
+        		+ " JOIN units AS u ON u.unit_id = u_p.unit_id\n"
+        		+ " WHERE u_p.unit_id IN (%s) AND u.is_mobile = FALSE;", unitIds);
 
         ResultSet unitRes = SQLExecutor.getInstance().executeQuery(sqlPositionQuery);
         Map<Long, Location> unitToPosition = parseUnitPosition(unitRes);
 
-        String sqlObsQuery = String.format("SELECT unit_id, time_stamp, observed_value FROM observations\n" +
-                "WHERE unit_id IN (%s) AND sensor_id = %d AND time_stamp >= '%s' AND time_stamp < '%s' ORDER BY time_stamp;",
+        String sqlObsQuery = String.format("SELECT unit_id, time_stamp, observed_value"
+        		+ " FROM observations\n"
+        		+ " WHERE unit_id IN (%s)"
+        		+ " AND sensor_id = %d"
+        		+ " AND time_stamp >= '%s'"
+        		+ " AND time_stamp < '%s'"
+        		+ " ORDER BY time_stamp;",
                 unitIds, sensorId, fromTime, toTime);
         ResultSet obsRes = SQLExecutor.getInstance().executeQuery(sqlObsQuery);
         Map<Long, Map<LocalDateTime, List<Double>>> unitToObs = parseUnitObservation(obsRes);

+ 109 - 0
src/main/java/cz/hsrs/db/util/SensorUtil.java

@@ -527,6 +527,7 @@ public class SensorUtil extends TrackUtil {
      * @return ResultSet object represents last observation for given unit-sensor pair
      * @throws SQLException
      */
+    /* !!! REWRITE !!! */
     @SuppressWarnings("unchecked")
     public List<ObservationValue> getSensorLastObservation(long unitId, long sensorId) throws SQLException {
         String query = "SELECT time_stamp, gid, observed_value"
@@ -540,11 +541,33 @@ public class SensorUtil extends TrackUtil {
     }
     
     /**
+     * 
+     * @param unitId
+     * @param sensorId
+     * @return
+     * @throws SQLException
+     */
+    public List<ObservationValue> getSensorLastObservationNew(long unitId, long sensorId) throws SQLException {
+    	String query = "SELECT last_value, last_obs FROM public.units_to_sensors"
+    			+ " WHERE unit_id="+unitId
+    			+ " AND sensor_id = "+sensorId+";";
+    	ResultSet res = stmt.executeQuery(query);
+    	List<ObservationValue> obsList = new LinkedList<ObservationValue>();
+    	if(res != null) {
+    		while (res.next()) {
+    			obsList.add(new ObservationValue(res.getDouble("last_value"), res.getString("last_obs")));	
+    		}
+    	}
+    	return obsList;
+    }
+    
+    /**
      * Method gets list of last observations from all connected sensors for given unit
      * @param unitId - identifier of unit
      * @return list of UnitSensorObservation objects represents last observations from all connected sensors to given unit
      * @throws SQLException
      */
+    /* !!! REWRITE !!! */
     @SuppressWarnings("unchecked")
     public List<UnitSensorObservation> getUnitSensorsLastObservations(long unitId) throws SQLException{
         String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
@@ -557,12 +580,38 @@ public class SensorUtil extends TrackUtil {
     }
     
     /**
+     * 
+     * @param unitId
+     * @return
+     * @throws SQLException
+     */
+    public List<UnitSensorObservation> getUnitSensorsLastObservationsNew(long unitId) throws SQLException{
+    	String query = "SELECT unit_id, sensor_id, last_value, last_obs"
+    			+ " FROM public.units_to_sensors"
+    			+ " WHERE unit_id="+unitId+";";
+    	ResultSet res = stmt.executeQuery(query);
+    	List<UnitSensorObservation> obsList = new LinkedList<UnitSensorObservation>();
+    	if(res != null) {
+    		while (res.next()) {
+    			obsList.add(new UnitSensorObservation(
+    					res.getString("last_obs"),
+    					res.getDouble("last_value"),
+    					res.getLong("sensor_id"),
+    					res.getLong("unit_id")
+    				));	
+    		}
+    	}
+    	return obsList;
+    }
+    
+    /**
      * Method gets list of last observations from all connected sensors to all units belonging to given group
      * @param groupName - name of group
      * @return list of UnitSensorObservation objects represents last observations from all connected sensors to all units
      * belonging to given group
      * @throws SQLException
      */
+    /* !!! REWRITE !!! */
     @SuppressWarnings("unchecked")
     public List<UnitSensorObservation> getUnitsSensorsLastObservations(String groupName) throws SQLException{
         String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
@@ -579,6 +628,34 @@ public class SensorUtil extends TrackUtil {
     }
 
     /**
+     * 
+     * @param groupName
+     * @return
+     * @throws SQLException
+     */
+    public List<UnitSensorObservation> getUnitsSensorsLastObservationsNew(String groupName) throws SQLException{
+    	String query = "SELECT unit_id, sensor_id, last_value, last_obs"
+    			+ " FROM public.units_to_sensors"
+    			+ " WHERE unit_id IN (SELECT unit_id"
+    				+ " FROM units_to_groups utg, groups g"
+    				+ " WHERE utg.group_id = g.id"
+    				+ " AND g.group_name = '"+groupName+"');";
+    	
+    	ResultSet res = stmt.executeQuery(query);
+    	List<UnitSensorObservation> obsList = new LinkedList<UnitSensorObservation>();
+    	if(res != null) {
+    		while (res.next()) {
+    			obsList.add(new UnitSensorObservation(
+    					res.getString("last_obs"),
+    					res.getDouble("last_value"),
+    					res.getLong("sensor_id"),
+    					res.getLong("unit_id")
+    				));	
+    		}
+    	}
+    	return obsList;
+    }
+    /**
      * Method gets list of last observations of given connected sensor of all units belonging to given group.
      * @param groupName - name of group
      * @param sensorId - identifier of sensor
@@ -586,6 +663,7 @@ public class SensorUtil extends TrackUtil {
      * belonging to given group
      * @throws SQLException
      */
+    /* !!! REWRITE !!! */
     @SuppressWarnings("unchecked")
     public List<UnitSensorObservation> getUnitsSensorsLastObservations(String groupName, long sensorId) throws SQLException{
         String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
@@ -601,4 +679,35 @@ public class SensorUtil extends TrackUtil {
         ResultSet res = stmt.executeQuery(query);
         return (List<UnitSensorObservation>) generateObjectList(new UnitSensorObservation(), res);
     }
+    
+    /**
+     * 
+     * @param groupName
+     * @param sensorId
+     * @return
+     * @throws SQLException
+     */
+    public List<UnitSensorObservation> getUnitsSensorsLastObservationsNew(String groupName, long sensorId) throws SQLException{
+    	String query = "SELECT unit_id, sensor_id, last_value, last_obs"
+    			+ " FROM public.units_to_sensors"
+    			+ " WHERE unit_id IN (SELECT unit_id"
+    				+ " FROM units_to_groups utg, groups g"
+    				+ " WHERE utg.group_id = g.id"
+    				+ " AND g.group_name = '"+groupName+"')"
+    			+ "AND sensor_id = "+sensorId+";";
+    	
+    	ResultSet res = stmt.executeQuery(query);
+    	List<UnitSensorObservation> obsList = new LinkedList<UnitSensorObservation>();
+    	if(res != null) {
+    		while (res.next()) {
+    			obsList.add(new UnitSensorObservation(
+    					res.getString("last_obs"),
+    					res.getDouble("last_value"),
+    					res.getLong("sensor_id"),
+    					res.getLong("unit_id")
+    				));	
+    		}
+    	}
+    	return obsList;
+    }
 }

+ 8 - 4
src/main/java/cz/hsrs/servlet/provider/SensorService.java

@@ -115,31 +115,35 @@ public class SensorService extends DBServlet {
                 }
             /* GetLastObservations */
             } else if(request.getParameter(ServiceParameters.OPERATION).equals(GET_LAST_OBSERVATIONS)){
+            	/* unit_id && sensor_id */
                 if(params.getGroup() == null && params.getUnitId() != 0 && params.getSensorId() != 0){
                     boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
                     if(isAffiliated){
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getSensorLastObservation(params.getUnitId(), params.getSensorId()));
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getSensorLastObservationNew(params.getUnitId(), params.getSensorId()));
                     } else{
                         throw new SQLException("Specified unit does not exist in any group of given user!");
                     }
+                /* unit_id */    
                 } else if(params.getGroup() == null && params.getUnitId() != 0 && params.getSensorId() == 0){
                     boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
                     if(isAffiliated){
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitSensorsLastObservations(params.getUnitId()));
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitSensorsLastObservationsNew(params.getUnitId()));
                     } else{
                         throw new SQLException("Specified unit does not exist in any group of given user!");
                     }
+                /* group */
                 } else if(params.getGroup() != null && params.getUnitId() == 0 && params.getSensorId() == 0){
                     boolean isAffiliated = db.groupUtil.checkGroupAffiliation2User(params.getUser(), params.getGroup());
                     if(isAffiliated){
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensorsLastObservations(params.getGroup()));
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensorsLastObservationsNew(params.getGroup()));
                     } else{
                         throw new SQLException("Specified unit does not exist in any group of given user!");
                     }
+                /* group && sensor_id */
                 } else if(params.getGroup() != null && params.getUnitId() == 0 && params.getSensorId() != 0){
                     boolean isAffiliated = db.groupUtil.checkGroupAffiliation2User(params.getUser(), params.getGroup());
                     if(isAffiliated){
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensorsLastObservations(params.getGroup(), params.getSensorId()));
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensorsLastObservationsNew(params.getGroup(), params.getSensorId()));
                     } else{
                         throw new SQLException("Specified unit does not exist in any group of given user!");
                     }