فهرست منبع

病虫害传感器转流

lchao 1 سال پیش
والد
کامیت
1e3c470f1a

+ 16 - 3
ruoyi-admin/pom.xml

@@ -16,6 +16,17 @@
     </description>
 
     <dependencies>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+            <version>4.5.10</version>
+        </dependency>
+
+        <dependency>
+            <groupId>commons-fileupload</groupId>
+            <artifactId>commons-fileupload</artifactId>
+            <version>1.3.1</version>
+        </dependency>
 
         <!-- SpringBoot集成thymeleaf模板 -->
         <dependency>
@@ -130,9 +141,11 @@
             <artifactId>rocketmq-spring-boot-starter</artifactId>
             <version>2.2.3</version>
         </dependency>
-
-
-
+        <dependency>
+            <groupId>commons-httpclient</groupId>
+            <artifactId>commons-httpclient</artifactId>
+            <version>3.1</version>
+        </dependency>
 
 
     </dependencies>

+ 85 - 6
ruoyi-admin/src/main/java/com/ruoyi/monitorInterface/inserctpests/service/impl/PlantDiseasesAndInsectPestsServiceImpl.java

@@ -4,15 +4,22 @@ import cn.hutool.http.HttpRequest;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.ruoyi.common.core.domain.AjaxResult;
+import com.ruoyi.common.utils.file.FileUtils;
 import com.ruoyi.framework.web.service.ConfigService;
 import com.ruoyi.monitorInterface.inserctpests.service.PlantDiseasesAndInsectPestsService;
 import com.ruoyi.monitorInterface.sennor.api.API;
+import com.ruoyi.util.FileLoadClient;
+import com.ruoyi.util.FileUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+import sun.net.www.http.HttpClient;
 
 import javax.annotation.Resource;
-import javax.swing.plaf.nimbus.State;
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
 
 @Service
 public class PlantDiseasesAndInsectPestsServiceImpl implements PlantDiseasesAndInsectPestsService {
@@ -25,7 +32,19 @@ public class PlantDiseasesAndInsectPestsServiceImpl implements PlantDiseasesAndI
     private String secretKey;
     private String userName;
 
+    private static String INSECT_PESTS_URL = "";
+    // TODO 部署需修改成线上地址
+    private static String FILE_URL = "";
+
     public AjaxResult plantDiseasesAndInsectPestsMessageReceiver(String deviceNumber) {
+        if (FILE_URL.equals("")){
+            FILE_URL = configService.getKey("onest_file_url");
+        }
+        if (INSECT_PESTS_URL.equals("")){
+            INSECT_PESTS_URL = configService.getKey("insectPestsUrl");
+        }
+        System.out.println(INSECT_PESTS_URL);
+        System.out.println(FILE_URL);
         secretKey = configService.getKey("insectToken");
         userName = configService.getKey("insectName");
         //先请求
@@ -42,8 +61,19 @@ public class PlantDiseasesAndInsectPestsServiceImpl implements PlantDiseasesAndI
         String res;
         try {
             object = JSONObject.parseObject(result);
+            String oldTaggingImgUrl = object.getJSONObject("data").getString("oldTaggingImgUrl");
+            String taggingImgUrl = object.getJSONObject("data").getString("taggingImgUrl");
+
+            JSONObject img = img(oldTaggingImgUrl);
+            object.getJSONObject("data").put("oldTaggingImgUrl", img.getJSONObject("data").getString("url"));
+            JSONObject img2 = img(taggingImgUrl);
+            object.getJSONObject("data").put("taggingImgUrl", img2.getJSONObject("data").getString("url"));
 
-            if (object.get("state") != null  &&  object.getString("state").equals("success")){
+            System.out.println("--------------------------内网地址-----------------------------");
+            System.out.println("oldTaggingImgUrl:" + img.getJSONObject("data").getString("url"));
+            System.out.println("taggingImgUrl:" + img2.getJSONObject("data").getString("url"));
+            System.out.println("-------------------------------------------------------------");
+            if (object.get("state") != null && object.getString("state").equals("success")) {
                 res = HttpRequest.post(configService.getKey("centerMonitorURL") + "device/saveInsectPestsDeviceData")
                         .header("Content-Type", "application/json")
                         .body(object.toJSONString())
@@ -59,10 +89,59 @@ public class PlantDiseasesAndInsectPestsServiceImpl implements PlantDiseasesAndI
         }
     }
 
+    private JSONObject img(String oldTggingImgUrl) {
+        String fileload = "";
+        try {
+            //定义一个URL对象
+            URL url = new URL(INSECT_PESTS_URL + oldTggingImgUrl);
+            //打开连接
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            //设置请求方式为"GET"
+            conn.setRequestMethod("GET");
+            //超时响应时间为10秒
+            conn.setConnectTimeout(10 * 1000);
+            //通过输入流获取图片数据
+            InputStream inStream = conn.getInputStream();
+            //得到图片的二进制数据,以二进制封装得到数据,具有通用性
+            byte[] data = readInputStream(inStream);
+            //new一个文件对象用来保存图片,默认保存当前工程根目录
+            File imageFile = new File("InputStreamInfo.jpg");
+            //创建输出流
+            FileOutputStream outStream = new FileOutputStream(imageFile);
+            //写入数据
+            outStream.write(data);
+            //关闭输出流
+            outStream.close();
+            fileload = FileLoadClient.fileload(FILE_URL, imageFile);
+
+        } catch (Exception e) {
+
+        }
+        JSONObject parseObject = JSONObject.parseObject(fileload);
+        return parseObject;
+    }
+
+    private static byte[] readInputStream(InputStream inStream) throws Exception {
+        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+        //创建一个Buffer字符串
+        byte[] buffer = new byte[6024];
+        //每次读取的字符串长度,如果为-1,代表全部读取完毕
+        int len = 0;
+        //使用一个输入流从buffer里把数据读取出来
+        while ((len = inStream.read(buffer)) != -1) {
+            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
+            outStream.write(buffer, 0, len);
+        }
+        //关闭输入流
+        inStream.close();
+        //把outStream里的数据写入内存
+        return outStream.toByteArray();
+    }
+
     @Override
     public JSONArray getDevideCodeMapByType(String types) {
         //先请求
-        StringBuffer URI = new StringBuffer(configService.getKey("centerMonitorURL")+ "device/getDevideCodeMapByTypes");
+        StringBuffer URI = new StringBuffer(configService.getKey("centerMonitorURL") + "device/getDevideCodeMapByTypes");
         URI.append("?types=").append(types);
         String result = HttpRequest.get(URI.toString())
                 .header("Content-Type", "application/json")
@@ -71,12 +150,12 @@ public class PlantDiseasesAndInsectPestsServiceImpl implements PlantDiseasesAndI
         JSONObject object;
         try {
             object = JSONObject.parseObject(result);
-            if(object.getInteger("code") == 200){
+            if (object.getInteger("code") == 200) {
                 return object.getJSONArray("data");
             }
-        }catch(Exception e){
+        } catch (Exception e) {
             e.printStackTrace();
-            log.error("服务端数据校验失败! data ===> {} , result ===> {}",result, e.getMessage());
+            log.error("服务端数据校验失败! data ===> {} , result ===> {}", result, e.getMessage());
         }
         return new JSONArray();
     }

+ 76 - 0
ruoyi-admin/src/main/java/com/ruoyi/util/FileLoadClient.java

@@ -0,0 +1,76 @@
+package com.ruoyi.util;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.multipart.FilePart;
+import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
+import org.apache.commons.httpclient.methods.multipart.Part;
+
+public class FileLoadClient {
+
+	private static final int TIMEOUT = 5000;
+
+	public static void main(String[] args) {
+		fileload("http://localhost:8080/uploadFile", new File("D:\\google-collections\\1.0\\google-collections-1.0.jar"));
+	}
+
+	public static String fileload(String url, File file) {
+		String body = "{}";
+
+		if (url == null || url.equals("")) {
+			return "illegal";
+		}
+		if (!file.exists()) {
+			return "file not exist";
+		}
+
+		PostMethod postMethod = new PostMethod(url);
+		BufferedReader br = null;
+		try {
+			// FilePart:用来上传文件的类,file即要上传的文件
+			FilePart fp = new FilePart("file", file);
+			Part[] parts = {fp};
+
+			// 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
+			MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
+			postMethod.setRequestEntity(mre);
+
+			HttpClient client = new HttpClient();
+			// 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间
+			client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
+			int status = client.executeMethod(postMethod);
+			if (status == HttpStatus.SC_OK) {
+				InputStream inputStream = postMethod.getResponseBodyAsStream();
+				br = new BufferedReader(new InputStreamReader(inputStream));
+				StringBuffer stringBuffer = new StringBuffer();
+				String str = "";
+				while ((str = br.readLine()) != null) {
+					stringBuffer.append(str);
+				}
+				body = stringBuffer.toString();
+			} else {
+				body = "fail";
+			}
+		} catch (Exception e) {
+//            。。。
+		} finally {
+			if (br != null)
+				try {
+					br.close();
+				} catch (IOException e) {
+//					。。。
+				}
+			// 释放连接
+			postMethod.releaseConnection();
+		}
+		return body;
+	}
+}
+

+ 75 - 0
ruoyi-admin/src/main/java/com/ruoyi/util/FileUtil.java

@@ -0,0 +1,75 @@
+package com.ruoyi.util;
+
+import com.ruoyi.common.utils.uuid.UUID;
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileItemFactory;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.springframework.http.MediaType;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.commons.CommonsMultipartFile;
+
+import java.io.*;
+
+/**
+ * @author zx
+ * @date 2020/9/7
+ */
+public class FileUtil {
+
+
+    /**
+     * 获取封装得MultipartFile
+     *
+     * @param inputStream inputStream
+     * @param fileName    fileName
+     * @return MultipartFile
+     */
+    public static MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
+        FileItem fileItem = createFileItem(inputStream, fileName);
+        //CommonsMultipartFile是feign对multipartFile的封装,但是要FileItem类对象
+        return new CommonsMultipartFile(fileItem);
+    }
+
+
+    /**
+     * FileItem类对象创建
+     *
+     * @param inputStream inputStream
+     * @param fileName    fileName
+     * @return FileItem
+     */
+    public static FileItem createFileItem(InputStream inputStream, String fileName) {
+        FileItemFactory factory = new DiskFileItemFactory(16, null);
+        String textFieldName = "file";
+        FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
+        int bytesRead = 0;
+        byte[] buffer = new byte[8192];
+        OutputStream os = null;
+        //使用输出流输出输入流的字节
+        try {
+            os = item.getOutputStream();
+            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
+                os.write(buffer, 0, bytesRead);
+            }
+            inputStream.close();
+        } catch (IOException e) {
+            throw new IllegalArgumentException("文件上传失败");
+        } finally {
+            if (os != null) {
+                try {
+                    os.close();
+                } catch (IOException e) {
+
+                }
+            }
+            if (inputStream != null) {
+                try {
+                    inputStream.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+
+        return item;
+    }
+}

+ 1 - 1
ruoyi-admin/src/main/resources/application.yml

@@ -24,7 +24,7 @@ ruoyi:
 # 开发环境配置(视频会议配置)
 server:
   # 服务器的HTTP端口,默认为80
-  port: 15002
+  port: 81
 #  ssl:
 #    key-store: classpath:keystore.jks
 #    key-store-password: 123456