gao.qiang 8 месяцев назад
Родитель
Сommit
390b0fcb1f
2 измененных файлов с 254 добавлено и 102 удалено
  1. 5 1
      hazard-admin/pom.xml
  2. 249 101
      hazard-admin/src/main/java/com/ozs/web/core/util/CameraUtil.java

+ 5 - 1
hazard-admin/pom.xml

@@ -107,7 +107,11 @@
                 </exclusion>
             </exclusions>
         </dependency>
-
+            <dependency>
+                <groupId>com.jcraft</groupId>
+                <artifactId>jsch</artifactId>
+                <version>0.1.55</version> <!-- 根据当前最新版本选择合适的版本号 -->
+            </dependency>
         <dependency>
             <groupId>cn.hutool</groupId>
             <artifactId>hutool-all</artifactId>

+ 249 - 101
hazard-admin/src/main/java/com/ozs/web/core/util/CameraUtil.java

@@ -1,9 +1,57 @@
 package com.ozs.web.core.util;
 
 
-import com.alibaba.fastjson2.JSON;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.nio.charset.StandardCharsets;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.time.*;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+
 import com.alibaba.fastjson2.JSONArray;
 import com.alibaba.fastjson2.JSONObject;
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.jcraft.jsch.Channel;
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
+import com.ozs.common.utils.HttpClientUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.stereotype.Component;
+import org.springframework.util.ObjectUtils;
+
+import com.alibaba.fastjson2.JSON;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@@ -1150,119 +1198,219 @@ ffmpeg -i "concat:1.ts|2.ts" -c copy output.mp4
     }
 
 
-    public void removePrice(){
-        try {
-            // 创建MinioClient对象
-            MinioClient minioClient = MinioClient.builder()
-                    .endpoint(endpoint)
-                    .credentials(accessKey, secretKey)
-                    .build();
+//    public void removePrice(Integer number) {
+//        try {
+//            // 创建MinioClient对象
+//            MinioClient minioClient = MinioClient.builder()
+//                    .endpoint(endpoint)
+//                    .credentials(accessKey, secretKey)
+//                    .build();
+//
+//            // 指定要删除文件的桶名和目录名
+//            String bucketName = this.bucketName;
+//            String prefix = "/camera_picture/normal/";
+//
+//            // 指定要删除的时间点(此处为当前时间之前的时间)
+//            ZonedDateTime deleteTime = ZonedDateTime.now().minusDays(number); // 删除30天前的文件
+//
+//            // 删除指定目录下的所有文件和文件夹
+//            deleteObjectsAndEmptyDirectoriesRecursively(minioClient, bucketName, prefix, deleteTime);
+//        } catch (Exception e) {
+//            System.out.println("Error occurred: " + e);
+//        }
+//    }
+//
+//    private static void deleteObjectsAndEmptyDirectoriesRecursively(MinioClient minioClient, String bucketName, String prefix, ZonedDateTime deleteTime) throws Exception {
+//        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder()
+//                .bucket(bucketName)
+//                .prefix(prefix)
+//                .recursive(true)
+//                .build());
+//
+//        for (Result<Item> result : results) {
+//            Item item = result.get();
+//            ZonedDateTime itemLastModified = item.lastModified();
+//            log.info("删除的时间:" + deleteTime);
+//            log.info("文件夹的时间:" + itemLastModified);
+//            if (itemLastModified.isBefore(deleteTime)) {
+//                // 删除文件或文件夹
+//                minioClient.removeObject(RemoveObjectArgs.builder()
+//                        .bucket(bucketName)
+//                        .object(item.objectName())
+//                        .build());
+//                log.info("删除文件或文件夹: " + item.objectName());
+//            }
+//        }
+//    }
+
+
+    public void test(Integer number) {
+        removePrice();
+    }
 
-            // 指定要删除文件的桶名和目录名
-            String bucketName = this.bucketName;
-            String prefix = "camera_picture/normal/";
+    public void removePrice() {
+        String host = "10.161.12.52"; // 远程主机
+        String user = "root"; // SSH用户名
+        String password = "iTi*21116"; // SSH密码
 
-            // 指定要删除的时间点(此处为当前时间之前的时间)
-            ZonedDateTime deleteTime = ZonedDateTime.now().minusDays(90); // 删除90天前的文件
+        try {
+            JSch jsch = new JSch();
+            Session session = jsch.getSession(user, host, 22); // 默认SSH端口号是22
+            session.setConfig("StrictHostKeyChecking", "no"); // 不进行主机密钥检查
+            session.setPassword(password);
+            session.connect();
+
+            String remoteDir = "/data/minio/data/picbucket/camera_picture/normal/"; // 要查看的远程目录
+
+            Channel channel = session.openChannel("exec");
+            ((ChannelExec) channel).setCommand("ls " + remoteDir); // 在远程服务器上执行第一次`ls`命令
+            InputStream in = channel.getInputStream();
+            channel.connect();
+            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+            String line;
+            //第一次命令输出
+            while ((line = reader.readLine()) != null) {
+                StringBuilder commandOutput = new StringBuilder(); // 存储命令输出
+                commandOutput.append(remoteDir);
+                System.out.println(line);
+                commandOutput.append(line);
+
+                // 执行第二次命令输出
+                Channel channel2 = session.openChannel("exec");
+                ((ChannelExec) channel2).setCommand("ls " + commandOutput.toString()); // 在远程服务器上执行第二次`ls`命令
+                InputStream in2 = channel2.getInputStream();
+                channel2.connect();
+
+                BufferedReader reader2 = new BufferedReader(new InputStreamReader(in2));
+                while ((line = reader2.readLine()) != null) {
+                    System.out.println(line); // 输出第二次`ls -l`的结果
+                    commandOutput.append("/" + line);
+
+                    // 执行第三次命令输出
+                    Channel channel3 = session.openChannel("exec");
+                    ((ChannelExec) channel3).setCommand("ls " + commandOutput.toString()); // 在远程服务器上执行第三次`ls`命令
+                    InputStream in3 = channel3.getInputStream();
+                    channel3.connect();
+
+                    BufferedReader reader3 = new BufferedReader(new InputStreamReader(in3));
+                    while ((line = reader3.readLine()) != null) {
+                        System.out.println(line); // 输出第三次`ls -l`的结果
+                        commandOutput.append("/" + line);
+
+                        // 执行第四次命令输出
+                        Channel channel4 = session.openChannel("exec");
+                        ((ChannelExec) channel4).setCommand("ls " + commandOutput.toString()); // 在远程服务器上执行第四次`ls`命令
+                        InputStream in4 = channel4.getInputStream();
+                        channel4.connect();
+
+                        BufferedReader reader4 = new BufferedReader(new InputStreamReader(in4));
+                        while ((line = reader4.readLine()) != null) {
+                            System.out.println(line); // 输出第四次`ls -l`的结果
+                            commandOutput.append("/" + line);
+                            // 执行第五次命令输出
+                            Channel channel5 = session.openChannel("exec");
+                            ((ChannelExec) channel5).setCommand("ls -l " + commandOutput.toString()); // 在远程服务器上执行第五次`ls`命令
+                            InputStream in5 = channel5.getInputStream();
+                            channel5.connect();
+
+                            BufferedReader reader5 = new BufferedReader(new InputStreamReader(in5));
+                            while ((line = reader5.readLine()) != null) {
+                                System.out.println(line);// 输出第五次`ls -l`的结果
+                                Pattern pattern = Pattern.compile("\\S+$"); // 匹配最后一个非空白字符之后的内容,即文件名
+                                Matcher matcher = pattern.matcher(line);
+                                if (matcher.find()) {
+                                    long date = getDate(line, matcher.group());
+                                    System.out.println(matcher.group());
+                                    if ((int) date <= -7) {
+                                        //执行删除
+                                        System.out.println("执行删除:" + date);
+                                        Channel channel6 = session.openChannel("exec");
+                                        System.out.println("参数" + commandOutput + "/" + matcher.group());
+                                        ((ChannelExec) channel6).setCommand("rm -rf " + commandOutput + "/" + matcher.group());
+                                        InputStream in6 = channel6.getInputStream();
+                                        channel6.connect();
+                                    }
+                                }
+                            }
+                            channel5.disconnect();
+                            commandOutput.setLength(commandOutput.length() - 1);
+                        }
+                        channel4.disconnect();
+                        commandOutput.setLength(commandOutput.length() - 1);
+                    }
+                    channel3.disconnect();
+                    commandOutput.setLength(commandOutput.length() - 1);
 
-            // 递归删除指定目录下的所有文件和空目录
-            deleteObjectsAndEmptyDirectoriesRecursively(minioClient, bucketName, prefix, deleteTime);
-        } catch (Exception e) {
-            System.out.println("Error occurred: " + e);
+                }
+                channel2.disconnect();
+                commandOutput.setLength(commandOutput.length() - 1);
+            }
+            channel.disconnect();
+            session.disconnect();
+        } catch (JSchException | java.io.IOException e) {
+            System.out.println(e);
         }
     }
 
-    private static void deleteObjectsAndEmptyDirectoriesRecursively(MinioClient minioClient, String bucketName, String prefix, ZonedDateTime deleteTime) throws Exception{
-//        log.info("----bucketName----"+bucketName);
-//        log.info("----prefix----"+prefix);
-//        log.info("----deleteTime----"+deleteTime);
-        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder()
-                .bucket(bucketName)
-                .prefix(prefix)
-                .recursive(true)
-                .build());
-
-        boolean hasFiles = false;
-//        log.info("----results----"+results);
-        for (Result<Item> result : results) {
-            Item item = result.get();
-
-            // 如果是文件且在指定时间之前,则删除文件
-//            log.info("----item.lastModified()----"+item.lastModified());
-//            log.info("----NoDeleted----"+item.objectName());
-            if (!item.isDir() && item.lastModified().isBefore(deleteTime)) {
-                minioClient.removeObject(RemoveObjectArgs.builder()
-                        .bucket(bucketName)
-                        .object(item.objectName())
-                        .build());
-                log.info("Deleted: " + item.objectName());
-                hasFiles = true;
-            }
-
-            // 如果是目录,则递归删除目录下的文件和空目录
-            if (item.isDir()) {
-                deleteObjectsAndEmptyDirectoriesRecursively(minioClient, bucketName, item.objectName(), deleteTime);
-            }
-        }
+    public static long getDate(String text, String two) {
 
-        // 如果目录下没有文件且不是根目录,则删除该目录
-        if (!hasFiles && !prefix.isEmpty()) {
-            minioClient.removeObject(RemoveObjectArgs.builder()
-                    .bucket(bucketName)
-                    .object(prefix)
-                    .build());
-            log.info("Deleted directory: " + prefix);
-        }
-    }
+        // 使用空格分割字符串
+        String[] parts = text.split(" ");
 
+        for (int i = 0; i < parts.length - 2; i++) {
+            // 检查当前部分和下一个部分是否符合Linux系统时间的格式
+            if (parts[i].matches("[A-Z][a-z]{2}")) {
+                String linuxTime = parts[i] + " " + two;
+                System.out.println("Linux系统时间: " + linuxTime);
+                // 指定一个默认的年份
+                String year = String.valueOf(LocalDate.now().getYear());
 
-    public void test() {
-        try {
-            // Initialize Minio client
-            MinioClient minioClient = MinioClient.builder()
-                    .endpoint(endpoint)
-                    .credentials(accessKey, secretKey)
-                    .build();
-
-            // Bucket name
-            String bucketName = this.bucketName;
-            String prefix = "camera_picture/normal/";
-            // List all objects in the bucket
-            Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(true).build());
-            log.info("-------获取minio所有图片--------"+results);
-            for (Result<Item> result : results) {
-                Item item = result.get();
-                log.info("----item.lastModified()----"+item.lastModified());
-                log.info(item.objectName());
+                try {
+                    // 解析日期字符串并转换为LocalDate对象
+                    LocalDate date = parseDate(linuxTime, year);
+                    System.out.println("Converted date: " + date);
+                    // 当前时间
+                    // 计算日期之间的天数差异
+                    LocalDate currentDate = LocalDate.now();
+                    long daysDiff = ChronoUnit.DAYS.between(currentDate, date);
+                    System.out.println("Days difference with current date: " + daysDiff);
+                    return daysDiff;
+                } catch (DateTimeParseException e) {
+                    System.out.println("Error parsing date: " + e.getMessage());
+                }
+                break;
             }
-        } catch (Exception e) {
-            log.error("Error occurred: " + e);
         }
+        return 0;
     }
 
-    public static void main(String[] args) {
+    private static LocalDate parseDate(String dateStr, String defaultYear) {
+        // 创建一个月份缩写到数字的映射
+        Map<String, String> monthMap = new HashMap<>();
+        monthMap.put("Jan", "01");
+        monthMap.put("Feb", "02");
+        monthMap.put("Mar", "03");
+        monthMap.put("Apr", "04");
+        monthMap.put("May", "05");
+        monthMap.put("Jun", "06");
+        monthMap.put("Jul", "07");
+        monthMap.put("Aug", "08");
+        monthMap.put("Sep", "09");
+        monthMap.put("Oct", "10");
+        monthMap.put("Nov", "11");
+        monthMap.put("Dec", "12");
+
+        // 将月份缩写替换为数字
+        String[] dateParts = dateStr.split(" ");
+        String month = monthMap.get(dateParts[0]);
+        String day = dateParts[1];
+        int num = Integer.parseInt(day);
+        if (num >= 1 && num <= 9) {
+            day = "0" + day;
+        }
+        String fullDateStr = month + " " + day + " " + defaultYear;
 
-//            // 创建一个集合
-//            ArrayList<String> one = new ArrayList<>();
-//            one.add("a");
-//            one.add("b");
-//            one.add("c");
-//            System.out.println("ArrayList 1: " + one);
-//
-//            // 创建另一个集合
-//            ArrayList<String> other = new ArrayList<>();
-//            other.add("a");
-//            other.add("b");
-//            System.out.println("ArrayList 2: " + other);
-//
-//
-//        List<String> ones = one.stream().filter(o -> !other.contains(o)).collect(Collectors.toList());
-//            System.out.println("ArrayList 1: " + one + " ; isRetainAll:" + ones);
-        long dades = System.currentTimeMillis();
-        System.out.println(new Date(dades));
-        long time2 = dades - 60000L;
-        System.out.println(dades);
-        System.out.println(time2);
-        System.out.println(new Date(time2));
+        // 使用DateTimeFormatter解析日期
+        return LocalDate.parse(fullDateStr, DateTimeFormatter.ofPattern("MM dd yyyy"));
     }
 }