2012-09-27 68 views
0

我有一個使用Core Java和Spring 2.5的框架,它在unix環境中調用一些sftp腳本將文件上傳到目標服務器。截至目前,它只支持每次調用一次文件上傳。我負責增強框架,以支持多個文件上傳。但是,如果多個文件被刪除,如果由於某種原因,腳本在刪除較少數量的文件後失敗,那麼下一次調用程序應該只嘗試刪除剩餘的文件(作爲添加的功能而不是重試所有文件)。例如。假設在第一次調用時,程序應該是sftp 5個文件,並且在刪除2個文件後失敗,那麼應該有一個選項,以便在下一次調用時僅剩下3個文件。作爲一個可能的解決方案,我有多個選項,比如更新一些緩存條目或更新數據庫表,但這不被允許作爲解決方案(並且我沒有花太多時間爭論到目前爲止)。我可以考慮另一種解決方案 - 寫入文件,成功分離的文件的名稱,並繼續處理剩餘的文件。然而,這似乎是一種更粗糙的解決方案,我正在考慮一個更好的解決方案,它應該足夠通用。你能否就這種情況請一些更好的設計建議?請注意,目標服務器不會將任何信息發送回源服務器以執行所有此sftp。通過調用shell腳本來上傳多個文件

問候, Ramakant

回答

0

你試過提高它包含沒有SFTP correcty文件例外嗎?

的異常類可以是這個樣子:

import java.io.File; 

public class SFTPBulkFailedTransportException extends RuntimeException { 

    public SFTPBulkFailedTransportException(File[] untransmittedFiles){ 
     setUntransmittedFiles(untransmittedFiles); 
    } 

    public File[] getUntransmittedFiles() { 
     return this.untransmittedFiles; 
    } 

    private void setUntransmittedFiles(File[] untransmittedFiles) throws IllegalArgumentException { 
     this.untransmittedFiles = untransmittedFiles; 
    } 

    private File[] untransmittedFiles; 

} 

如果拋出該異常的所有尚未傳送的文件,您可以訪問他們,如果你捕獲這個異常。這種異常會在批量傳輸文件的方法中拋出。

如果你把它放在一起:

import java.util.ArrayList; 
import java.util.List; 

File[] filesToSend; // all files to send 

while(filesToSend.length != 0){ 

     try{ 
      sendbulk(filesToSend); 
     }catch(SFTPBulkFailedTransportException exception){ 
      // assign failed files to filesToSend 
      // because of the while loop, sendbulk is invoked again 
      filesToSend = exception.getUntransmittedFiles(); 
    } 
} 


public void sendbulk(File[] filesToSend) throws SFTPBulkFailedTransportException{ 

    List<File> unsuccesfullFiles = new ArrayList<File>(); 

    for(File file : filesToSend){ 
     try{ 
      sendSingle(file); 
     }catch(IllegalArgumentException exception){ 
      unsuccesfullFiles.add(file); 
     } 
    } 

    if(!unsuccesfullFiles.isEmpty()){ 
     throw new SFTPBulkFailedTransportException((File[]) unsuccesfullFiles.toArray()); 
    } 
} 

public void sendSingle(File file) throws IllegalArgumentException{ 
    // I am not sure if this is the right way to execute a command for your situation, but 
    // you can probably check the exit status of the sftp command (0 means successful) 
    String command = "REPLACE WITH SFTP COMMAND"; 
    Process child = Runtime.getRuntime().exec(command); 

    // if sftp failed, throw exception 
    if(child.exitValue() != 0){ 
     throw new IllegalArgumentException("ENTER REASON OF FAILURE HERE"); 
    } 
} 

我希望這有助於。

+0

但我怎麼知道哪些文件在第一次運行中沒有成功傳輸。如果我理解正確,上面的代碼會報告那些沒有被竊取的文件,但是當我第二次重新激活程序時,我只想從第一次運行中傳輸不成功的文件。 – user1588737

+1

至於沒有發送的文件,你會從異常中獲得它們。我會更新我的答案,以說明如何完成。但我不知道如何看看sftp是否工作,您如何爲單個文件調用它? –

+0

我通過程序調用一個shell腳本。有些東西像「sftp 」。根據框架,程序的工作方式是 - 多次調用相同的腳本,但每次都使用不同的文件。如果文件已成功傳輸,腳本的返回狀態將爲0。我試圖瞭解如何知道在第二次運行時再次傳輸哪些文件(因此我正在考慮將信息存儲在某處 - 數據庫/緩存/文件等) – user1588737