Forráskód Böngészése

fix: 全局字符串 首尾空格

jackzhou 6 hónapja
szülő
commit
fd68fe5fbe

+ 53 - 102
snowy-plugin/snowy-plugin-coldchain/src/main/java/vip/xiaonuo/coldchain/core/bean/influxdb/SensorData.java

@@ -1,13 +1,5 @@
 package vip.xiaonuo.coldchain.core.bean.influxdb;
 
-/**
- * @author jackzhou
- * @version 1.0
- * @project jfcloud-coldchain
- * @description
- * @date 2024/11/12 14:02:51
- */
-
 import com.github.jfcloud.influxdb.model.JfcloudInFluxEntity;
 import com.influxdb.annotations.Column;
 import com.influxdb.annotations.Measurement;
@@ -15,7 +7,7 @@ import com.influxdb.query.FluxRecord;
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;
-import lombok.SneakyThrows;
+import lombok.extern.slf4j.Slf4j;
 import vip.xiaonuo.coldchain.core.config.JfcloudColdChainConstants;
 import vip.xiaonuo.coldchain.core.service.dataprocess.model.PowerEnum;
 
@@ -27,151 +19,110 @@ import java.util.Optional;
 @AllArgsConstructor
 @NoArgsConstructor
 @Measurement(name = JfcloudColdChainConstants.INFLUXDB_DEFAULT_MEASUREMENT_NAME)
+@Slf4j
 public class SensorData extends JfcloudInFluxEntity {
-    /**
-     * 温度字段
-     */
     @Column(name = "temperature")
-    private double temperature;
-    /**
-     * 湿度字段
-     */
+    private Float temperature;
+
     @Column(name = "humidity")
-    private double humidity;
+    private Float humidity;
 
-    /**
-     * 二氧化碳浓度字段
-     */
     @Column(name = "co2")
     private Float co2;
 
-
-    /**
-     * 电池剩余电量
-     */
     @Column(name = "battery", tag = true)
     private Float battery;
 
-
-    /**
-     * 插电状态0:插电  1: 不插电
-     */
     @Column(name = "plugInStatus", tag = true)
     private String plugInStatus = PowerEnum.AC.getCode();
 
-
-    /**
-     * 位置标签
-     */
     @Column(name = "location", tag = true)
     private String location;
-    /**
-     * 经度字段
-     */
+
     @Column(name = "longitude", tag = true)
     private Double lng;
 
-    /**
-     * 纬度字段
-     */
     @Column(name = "latitude", tag = true)
     private Double lat;
 
-    /**
-     * 设备ID标签
-     */
     @Column(name = "device_id", tag = true)
     private String deviceId;
 
-    /**
-     * 路数,默认路数1
-     */
     @Column(name = "roads", tag = true)
     private Integer roads = 1;
 
-    /**
-     * 采集设备型号
-     */
     @Column(name = "model_name", tag = true)
     private String modelName;
 
-    @SneakyThrows
     public static SensorData mapToSensorData(FluxRecord record) {
         SensorData sensorData = new SensorData();
-        // Safely extract values and handle nulls
-        sensorData.setDeviceId(Optional.ofNullable(record.getValueByKey("device_id")).map(Object::toString).orElse(null));
-        sensorData.setRoads(getIntegerValue(record, "roads"));
-        sensorData.setTemperature(getDoubleValue(record, "temperature"));
-        sensorData.setHumidity(getDoubleValue(record, "humidity"));
-        sensorData.setCo2(getFloatValue(record, "co2"));
-        sensorData.setBattery(getFloatValue(record, "battery"));
-        sensorData.setPlugInStatus(Optional.ofNullable(record.getValueByKey("plugInStatus")).map(Object::toString).orElse(null));
-        sensorData.setLocation(Optional.ofNullable(record.getValueByKey("location")).map(Object::toString).orElse(null));
-        sensorData.setLng(getDoubleValue(record, "longitude"));
-        sensorData.setLat(getDoubleValue(record, "latitude"));
-        Instant time = record.getTime();
-        if (time != null) {
-            // 将 LocalDateTime 转换为 ZonedDateTime,附带时区信息
-            ZoneOffset offset = ZoneOffset.UTC;  // 或者使用 ZoneId.systemDefault() 获取系统时区
-            sensorData.setTime(time.atOffset(offset).toInstant());
+        try {
+            sensorData.setDeviceId(getStringValue(record, "device_id"));
+            sensorData.setRoads(getIntegerValue(record, "roads"));
+            sensorData.setTemperature(getFloatValue(record, "temperature"));
+            sensorData.setHumidity(getFloatValue(record, "humidity"));
+            sensorData.setCo2(getFloatValue(record, "co2"));
+            sensorData.setBattery(getFloatValue(record, "battery"));
+            sensorData.setPlugInStatus(getStringValue(record, "plugInStatus"));
+            sensorData.setLocation(getStringValue(record, "location"));
+            sensorData.setLng(getDoubleValue(record, "longitude"));
+            sensorData.setLat(getDoubleValue(record, "latitude"));
+            sensorData.setTime(getInstantValue(record));
+
+        } catch (Exception e) {
+            log.error("Error mapping FluxRecord to SensorData", e);
         }
         return sensorData;
     }
 
-    // Helper method to safely extract Integer values
+    private static String getStringValue(FluxRecord record, String key) {
+        return Optional.ofNullable(record.getValueByKey(key))
+                .map(Object::toString)
+                .orElse(null);
+    }
+
     private static Integer getIntegerValue(FluxRecord record, String key) {
-        return Optional.ofNullable(record.getValueByKey(key))  // Step 1: Get value by key (might be null)
-                .filter(value -> value instanceof Integer)  // Step 2: Ensure the value is an instance of Integer
-                .map(value -> (Integer) value)  // Step 3: Safely cast to Integer
-                .orElseGet(() -> {
-                    // If not an Integer, try to parse it as a String (fallback mechanism)
-                    Object value = record.getValueByKey(key);
-                    if (value instanceof String) {
-                        try {
-                            return Integer.valueOf((String) value);  // Try to parse String to Integer
-                        } catch (NumberFormatException e) {
-                            // If parsing fails, return null
-                            return null;
-                        }
+        return Optional.ofNullable(record.getValueByKey(key))
+                .map(value -> {
+                    try {
+                        return (value instanceof Integer) ? (Integer) value :
+                                (value instanceof String) ? Integer.valueOf((String) value) : null;
+                    } catch (NumberFormatException e) {
+                        return null;
                     }
-                    return null;  // Return null if not a String or Integer
-                });
+                })
+                .orElse(null);
     }
 
-
     private static Double getDoubleValue(FluxRecord record, String key) {
         return Optional.ofNullable(record.getValueByKey(key))
                 .map(value -> {
-                    if (value instanceof Double) {
-                        return (Double) value;  // 直接返回 Double 类型
-                    } else if (value instanceof String) {
-                        try {
-                            return Double.valueOf((String) value);  // 尝试将 String 转换为 Double
-                        } catch (NumberFormatException e) {
-                            return null;  // 如果转换失败,返回 0.0 或其他默认值
-                        }
+                    try {
+                        return (value instanceof Double) ? (Double) value :
+                                (value instanceof String) ? Double.valueOf((String) value) : null;
+                    } catch (NumberFormatException e) {
+                        return null;
                     }
-                    return null;  // 返回默认值,如果值既不是 Double 也不是 String
                 })
-                .orElse(null);  // 如果没有值,返回 0.0
+                .orElse(null);
     }
 
-
     private static Float getFloatValue(FluxRecord record, String key) {
         return Optional.ofNullable(record.getValueByKey(key))
                 .map(value -> {
-                    if (value instanceof Float) {
-                        return (Float) value;  // 直接返回 Double 类型
-                    } else if (value instanceof String) {
-                        try {
-                            return Float.valueOf((String) value);
-                        } catch (NumberFormatException e) {
-                            return null;  // 如果转换失败,返回 0.0 或其他默认值
-                        }
+                    try {
+                        return (value instanceof Float) ? (Float) value :
+                                (value instanceof String) ? Float.valueOf((String) value) : null;
+                    } catch (NumberFormatException e) {
+                        return null;
                     }
-                    return null;  // 返回默认值,如果值既不是 Double 也不是 String
                 })
-                .orElse(null);  // 如果没有值,返回 0.0
+                .orElse(null);
     }
 
+    private static Instant getInstantValue(FluxRecord record) {
+        return Optional.ofNullable(record.getTime())
+                .map(time -> time.atOffset(ZoneOffset.UTC).toInstant())
+                .orElse(null);
+    }
 }

+ 2 - 2
snowy-plugin/snowy-plugin-coldchain/src/main/java/vip/xiaonuo/coldchain/modular/app/param/AppDeviceData.java

@@ -25,12 +25,12 @@ public class AppDeviceData extends MonitorTargetRegion {
     @Schema(description = "设备温度 (℃)")
     @JsonSerialize(using = DoubleNullToDashSerializer.class)  // 使用自定义序列化器
     @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "#.00")
-    private Double temperature;  // 温度
+    private Float temperature;  // 温度
 
     @Schema(description = "设备湿度 (%)")
     @JsonSerialize(using = DoubleNullToDashSerializer.class)  // 使用自定义序列化器
     @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "#.00")
-    private Double humidity;  // 湿度
+    private Float humidity;  // 湿度
 
     @Schema(description = "二氧化碳浓度 (ppm)")
     @JsonSerialize(using = FloatNullToDashSerializer.class)  // 使用自定义序列化器

+ 44 - 0
snowy-web-app/src/main/java/vip/xiaonuo/core/config/GlobalTrimAdvice.java

@@ -0,0 +1,44 @@
+package vip.xiaonuo.core.config;
+
+/**
+ * @author jackzhou
+ * @version 1.0
+ * @project jfcloud-coldchain
+ * @description
+ * @date 2024/11/25 10:25:14
+ */
+import lombok.SneakyThrows;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ModelAttribute;
+
+import java.lang.reflect.Field;
+
+/**
+ * 全局去掉请求参数中 String 类型字段的前后空格
+ */
+@ControllerAdvice
+@Component
+public class GlobalTrimAdvice {
+
+    @ModelAttribute
+    @SneakyThrows
+    public void trimStrings(Object model) {
+        // 获取当前model的所有字段
+        Field[] fields = model.getClass().getDeclaredFields();
+        for (Field field : fields) {
+            // 如果字段是String类型
+            if (field.getType().equals(String.class)) {
+                try {
+                    field.setAccessible(true); // 设置字段可访问
+                    String value = (String) field.get(model);
+                    // 去除前后空格
+                    if (value != null) {
+                        field.set(model, value.trim());
+                    }
+                } catch (IllegalAccessException e) {
+                }
+            }
+        }
+    }
+}