Explorar o código

取服务器文件,服务器连接对象封装

zhouger hai 7 meses
pai
achega
affc2babed

+ 91 - 22
src/main/java/sys/sc/formplugin/TestPlugin.java

@@ -1,5 +1,7 @@
 package sys.sc.formplugin;
 
+import com.jcraft.jsch.*;
+import com.tongtech.jms.ra.core.Options;
 import kd.bos.base.utils.msg.BaseMessage;
 import kd.bos.base.utils.msg.OrgMessage;
 import kd.bos.dataentity.entity.CloneUtils;
@@ -24,9 +26,11 @@ import kd.bos.servicehelper.operation.OperationServiceHelper;
 import kd.bos.servicehelper.operation.SaveServiceHelper;
 import kd.epm.eb.common.model.DynamicInfoCollection;
 import kd.imc.bdm.common.constant.BotpCallBackLogConstant;
+import sys.sc.opplugin.utils.SftpClient;
 
 
 import java.io.*;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
@@ -39,6 +43,35 @@ import java.util.*;
 
 public class TestPlugin  extends AbstractListPlugin {
 
+    public static String host="192.168.10.69";//服务器ip地址
+    public static String username="root";//用户名
+    public static int port = 22;//端口号
+    public static String password="Kd@86262007";//用户密码
+
+
+
+//    public InputStream fileInputStream(String remoteFilePath) throws JSchException, SftpException {
+////        String remoteFilePath = "/home/kingdee/cosmic/nginx-appstatic/store/appstatic/20240908/zzry.dat";  // 上传到远程服务器的路径
+//        JSch jsch = new JSch();
+//        Session session ;
+//
+//        // 1. 设置会话
+//        session = jsch.getSession(username, host, port);
+//        session.setPassword(password);
+//        // 2. 配置 SSH 设置
+//        Properties config = new Properties();
+//        config.put("StrictHostKeyChecking", "no");  // 跳过主机密钥检查
+//        session.setConfig(config);
+//        // 3. 连接到远程服务器
+//        session.connect();
+//        // 4. 打开 SFTP 通道
+//        Channel channel = session.openChannel("sftp");
+//        channel.connect();
+//        ChannelSftp sftpChannel = (ChannelSftp) channel;
+//        InputStream inputStream = sftpChannel.get(remoteFilePath);
+//        return inputStream;
+//    }
+
     //根据接口配置信息获取组织人员,拼接服务器文件路径url,参数为urlcode接口配置信息编码
     public String getFileUrl(String urlcode) throws IOException {
         //组织人员接口配置信息获取
@@ -63,18 +96,7 @@ public class TestPlugin  extends AbstractListPlugin {
             nckd_url="/home/kingdee/cosmic/nginx-appstatic/store/appstatic/";
         }
         //文件完整路径
-        String realPath = nckd_url+datestr+"/"+nckd_filename;
-        File file=new File(realPath);
-        //文件不存在则生成文件
-        if (!file.exists()) {
-            File parentDir = file.getParentFile();
-            if (parentDir != null && !parentDir.exists()) {
-                parentDir.mkdirs();
-            }
-            file.createNewFile();
-            this.getView().showMessage(nckd_url+datestr+"路径下成功生成文件"+nckd_filename);
-        }
-
+        String realPath = nckd_url+datestr+File.separator+nckd_filename;
         return realPath;
     }
 
@@ -279,7 +301,6 @@ public class TestPlugin  extends AbstractListPlugin {
                 return;
             }
             String msg="";
-            // 人员类型写死的
             for (DynamicObject personData : personDataArray) {
                 //获取id
                 String id=personData.getString("id");
@@ -664,12 +685,14 @@ public class TestPlugin  extends AbstractListPlugin {
             List<String> selector = Arrays.asList(
                     "number", "name"
             );
-            //文件路径
-//            String fileurl="D:/hmhh.dat";
             //行名行号表标识
             String bd_bebank="bd_bebank";
             try {
+                //文件路径
                 String fileurl = getFileUrl("hmhhurl");
+                //获取服务器连接
+                SftpClient sftpClient=new SftpClient(host,username,password,port);
+                sftpClient.connect();
                 //基础资料
                 DynamicObjectType dynamicObjectType = EntityMetadataCache.getDataEntityType(bd_bebank);
                 //国家基础资料(中国)
@@ -681,15 +704,14 @@ public class TestPlugin  extends AbstractListPlugin {
                 DynamicObject[] existingData = BusinessDataServiceHelper
                         .load(dynamicObjectType.getName(), String.join(",", selector)+",enable,nckd_datasource", null);
                 //查找文件更新的数据
-
-
                 Map<String, DynamicObject> existingDataMap = new HashMap<>();
                 for (DynamicObject obj : existingData) {
                     //单据号
                     existingDataMap.put(obj.getString(selector.get(0)), obj);
                 }
                 Set<String> processeddubilidSet = new HashSet<>();
-                try (BufferedReader reader = new BufferedReader(new FileReader(fileurl))) {
+                //读取服务器文件并写入
+                try (BufferedReader reader = new BufferedReader(new InputStreamReader(sftpClient.fileInputStream(fileurl)))) {
                     String line;
                     while ((line = reader.readLine()) != null) {
                         //去掉换行符|$|
@@ -744,6 +766,8 @@ public class TestPlugin  extends AbstractListPlugin {
                         }
                     }
                 }
+                //关闭连接
+                sftpClient.disconnect();
                 //获取自动添加的数据
                 DynamicObject[] autoData = BusinessDataServiceHelper
                         .load(dynamicObjectType.getName()
@@ -759,8 +783,6 @@ public class TestPlugin  extends AbstractListPlugin {
 
                 }
                 SaveServiceHelper.save(autoData);
-
-
                 //查找更新数据
                 for (Map.Entry<String, DynamicObject> entry : existingDataMap.entrySet()) {
                     String dubil_id = entry.getKey();
@@ -770,8 +792,6 @@ public class TestPlugin  extends AbstractListPlugin {
                         updatedataList.add(data);
                     }
                 }
-
-
                 //新增数据不为空则更新到数据库中
                 if (!createdataList.isEmpty()) {
                     SaveServiceHelper.save(dynamicObjectType, createdataList.toArray(new DynamicObject[0]));
@@ -784,9 +804,58 @@ public class TestPlugin  extends AbstractListPlugin {
             } catch (IOException ex) {
                 ex.printStackTrace();
                 this.getView().showMessage("读取文件时发生错误:" + ex.getMessage());
+            } catch (Exception ex) {
+                throw new RuntimeException(ex);
             }
         }
 
+
+        //获取linux服务器连接
+        if ("connect".equals(e.getOperateKey()))
+        {
+            try {
+                FileCreat();
+            } catch (JSchException ex) {
+                throw new RuntimeException(ex);
+            } catch (IOException ex) {
+                throw new RuntimeException(ex);
+            } catch (Exception ex) {
+                throw new RuntimeException(ex);
+            }
+        }
+
+    }
+
+
+    //连接服务器操作文件类
+    public void FileCreat() throws Exception {
+        SftpClient sftpClient=new SftpClient(host,username,password,port);
+        //连接服务器
+        sftpClient.connect();
+        String remoteFilePath = "/home/kingdee/cosmic/nginx-appstatic/store/appstatic/20240908/zzry.dat";  // 上传到远程服务器的路径
+        BufferedReader reader = new BufferedReader(new InputStreamReader(sftpClient.fileInputStream(remoteFilePath)));
+        reader.readLine();
+        // 5. 上传文件到远程服务器
+        File file=new File(remoteFilePath);
+        FileInputStream fis = new FileInputStream(file);
+        if (!file.exists())
+        {
+            File parentDir = file.getParentFile();
+            ///没有路径就创建文件夹
+            if (parentDir != null && !parentDir.exists()) {
+                parentDir.mkdirs();
+            }
+            //创建文件
+            file.createNewFile();
+            //上传到linux服务器
+            sftpClient.getSftpChannel().put(fis,remoteFilePath);
+            this.getView().showMessage("成功生成文件");
+        }else {
+            this.getView().showMessage("已存在文件");
+        }
+        // 6. 关闭流和连接
+        fis.close();
+        sftpClient.disconnect();
     }
 }
 

+ 20 - 7
src/main/java/sys/sc/formplugin/UpdateDataDailyTask.java

@@ -17,10 +17,9 @@ import kd.bos.schedule.executor.AbstractTask;
 import kd.bos.sec.user.utils.UserOperationUtils;
 import kd.bos.servicehelper.BusinessDataServiceHelper;
 import kd.bos.servicehelper.operation.SaveServiceHelper;
+import sys.sc.opplugin.utils.SftpClient;
 
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
+import java.io.*;
 import java.text.SimpleDateFormat;
 import java.util.*;
 
@@ -32,6 +31,11 @@ import java.util.*;
 public class UpdateDataDailyTask extends AbstractTask {
 
     private static final Log log = LogFactory.getLog(UpdateDataDailyTask.class);
+    public static String host="192.168.10.69";//服务器ip地址
+    public static String username="root";//用户名
+    public static int port = 22;//端口号
+    public static String password="Kd@86262007";//用户密码
+
 
     @Override
     public MessageHandler getMessageHandle() {
@@ -44,8 +48,17 @@ public class UpdateDataDailyTask extends AbstractTask {
         log.info(mes+requestContext);
         //文件路径
         String path=getFileUrl("organduserurl");
-        //读取文件更新基础资料
-        updatebasicdata(path);
+        //获取连接对象
+        SftpClient sftpClient=new SftpClient(host,username,password,port);
+        try {
+            sftpClient.connect();
+            //读取文件更新基础资料
+            updatebasicdata(sftpClient.fileInputStream(path));
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+        //关闭连接
+        sftpClient.disconnect();
         //更新组织
         log.info("----------------更新组织中---------------------");
         updateorg();
@@ -54,7 +67,7 @@ public class UpdateDataDailyTask extends AbstractTask {
         updateperson();
     }
     //读取文件更新基础资料
-    public void updatebasicdata(String filePath)
+    public void updatebasicdata(InputStream inputStream)
     {
         //读取文件写入基础资料中
         try {
@@ -75,7 +88,7 @@ public class UpdateDataDailyTask extends AbstractTask {
                 existingDataMap.put(obj.getString("nckd_employeeid"), obj);
             }
             Set<String> processedGonghaoSet = new HashSet<>();
-            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
+            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                 String line;
                 while ((line = reader.readLine()) != null) {
                     //去掉换行符|$|

+ 74 - 0
src/main/java/sys/sc/opplugin/utils/SftpClient.java

@@ -0,0 +1,74 @@
+package sys.sc.opplugin.utils;
+
+/**
+ * @author cjz
+ * @date 2024/9/9 17:05
+ * @description:连接服务器获取sftp,工具类
+ */
+import com.jcraft.jsch.ChannelSftp;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.Session;
+import com.jcraft.jsch.SftpException;
+
+import java.io.FileOutputStream;
+import java.io.InputStream;
+
+public class SftpClient {
+    private String host;
+    private String usernmae;
+    private String password;
+    private int port;
+    private Session session;
+    private ChannelSftp sftpChannel;
+
+    public SftpClient(String host, String user, String password,int port) {
+        this.host = host;
+        this.usernmae = user;
+        this.password = password;
+        this.port=port;
+    }
+
+    // 连接到 SFTP 服务器
+    public void connect() throws Exception {
+        JSch jsch = new JSch();
+        session = jsch.getSession(usernmae, host, port);
+        session.setPassword(password);
+        session.setConfig("StrictHostKeyChecking", "no");
+        session.connect();
+        sftpChannel = (ChannelSftp) session.openChannel("sftp");
+        sftpChannel.connect();
+    }
+    //根据服务器路径读取文件,返回文件流
+    public InputStream fileInputStream(String remoteFilePath) throws SftpException {
+        InputStream inputStream = sftpChannel.get(remoteFilePath);
+        return inputStream;
+    }
+
+    // 下载文件
+//    public void downloadFile(String remoteFilePath, String localFilePath) throws Exception {
+//        try (InputStream inputStream = sftpChannel.get(remoteFilePath);
+//             FileOutputStream outputStream = new FileOutputStream(localFilePath)) {
+//
+//            byte[] buffer = new byte[1024];
+//            int bytesRead;
+//            while ((bytesRead = inputStream.read(buffer)) != -1) {
+//                outputStream.write(buffer, 0, bytesRead);
+//            }
+//        }
+//    }
+
+    // 断开连接
+    public void disconnect() {
+        if (sftpChannel != null && sftpChannel.isConnected()) {
+            sftpChannel.disconnect();
+        }
+        if (session != null && session.isConnected()) {
+            session.disconnect();
+        }
+    }
+
+
+    public ChannelSftp getSftpChannel() {
+        return sftpChannel;
+    }
+}