Browse Source

minio图片删除测试

gao.qiang 10 months ago
parent
commit
fdfb183f9f
2 changed files with 181 additions and 52 deletions
  1. 5 1
      hazard-admin/pom.xml
  2. 176 51
      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>

+ 176 - 51
hazard-admin/src/main/java/com/ozs/web/core/util/CameraUtil.java

@@ -6,15 +6,18 @@ 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.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
+import java.time.LocalDate;
 import java.time.ZonedDateTime;
+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;
@@ -26,22 +29,22 @@ 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.jcraft.jsch.Channel;
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
 import io.minio.ListObjectsArgs;
 import io.minio.MinioClient;
 import io.minio.RemoveObjectArgs;
 import io.minio.Result;
-import io.minio.errors.ErrorResponseException;
-import io.minio.errors.InsufficientDataException;
-import io.minio.errors.InternalException;
-import io.minio.errors.InvalidResponseException;
-import io.minio.errors.MinioException;
-import io.minio.errors.ServerException;
-import io.minio.errors.XmlParserException;
 import io.minio.messages.Item;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -51,8 +54,6 @@ import org.springframework.stereotype.Component;
 import org.springframework.util.ObjectUtils;
 
 import com.alibaba.fastjson2.JSON;
-import com.alibaba.fastjson2.JSONArray;
-import com.alibaba.fastjson2.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.ozs.common.config.BaseConfig;
@@ -1076,8 +1077,8 @@ ffmpeg -i "concat:1.ts|2.ts" -c copy output.mp4
         for (Result<Item> result : results) {
             Item item = result.get();
             ZonedDateTime itemLastModified = item.lastModified();
-             log.info("删除的时间:"+deleteTime);
-            log.info("文件夹的时间:"+itemLastModified);
+            log.info("删除的时间:" + deleteTime);
+            log.info("文件夹的时间:" + itemLastModified);
             if (itemLastModified.isBefore(deleteTime)) {
                 // 删除文件或文件夹
                 minioClient.removeObject(RemoveObjectArgs.builder()
@@ -1088,51 +1089,175 @@ ffmpeg -i "concat:1.ts|2.ts" -c copy output.mp4
             }
         }
     }
-    
-   
+
 
     public void test(Integer number) {
         removePrice(number);
     }
 
     public static void main(String[] args) {
+        String host = "124.70.58.209"; // 远程主机
+        String user = "root"; // SSH用户名
+        String password = "y06ak@ql95K50"; // SSH密码
 
-//            // 创建一个集合
-//            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));
-        // 视频拼接
-        String streamPath = "42010001541320000023/42010001541320000023";
-        String date = "2024-03-11";
-        String param = "{\n" +
-                "    \"streamPath\":\"" + streamPath + "\",\n" +
-                "    \"date\":\"" + date + "\"\n" +
-                "}";
-
-        String jsonStr = HttpUtils.sendPost("http://124.70.58.209:9080" + "/recordpro/api/query/records", param);
-        JSONObject jsonObj = JSON.parseObject(jsonStr);
-        JSONArray resultArray = jsonObj.getJSONArray("result");
-        JSONObject resultObj = resultArray.getJSONObject(0);
-        String path = resultObj.getString("Path");
-        System.out.println("Path: " + path);
+        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/tools/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);
+                    
+                }
+                channel2.disconnect();
+                commandOutput.setLength(commandOutput.length()-1);
+            }
+            channel.disconnect();
+            session.disconnect();
+        } catch (JSchException | java.io.IOException e) {
+            System.out.println(e);
+        }
+    }
+    
+    public static long getDate(String text,String two){
+
+        // 使用空格分割字符串
+        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());
+
+                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;
+            }
+        }
+        return 0;
+    }
+
+    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;
 
+        // 使用DateTimeFormatter解析日期
+        return LocalDate.parse(fullDateStr, DateTimeFormatter.ofPattern("MM dd yyyy"));
     }
 }