2016-10-26 52 views
-1

單擊下載按鈕可從SAN位置獲取PDF。但由於XYZ原因,有時文檔在SAN中不可用。我需要實施輪詢機制,以便點擊下載每5秒鐘後在SAN位置搜索文檔5次,並返回第5行的迭代。在搜索成功的日誌中。每5秒後進行5次Java輪詢

package abc.documentdownload; 

import abc.util.Email; 

import java.io.BufferedOutputStream; 
import java.io.IOException; 

import java.io.PrintWriter; 
import java.io.StringWriter; 
import java.io.Writer; 

import javax.servlet.*; 
import javax.servlet.http.*; 

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 

public class DownloadDocServlet extends HttpServlet { 
    private static final Log log = LogFactory.getLog(DownloadDocServlet.class); 
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252"; 

    public void init(ServletConfig config) throws ServletException { 
     super.init(config); 
    } 

    public void doGet(HttpServletRequest request, 
         HttpServletResponse response) throws ServletException, 
                  IOException { 
     doPost(request, response); 
    } 

    public void doPost(HttpServletRequest request, 
         HttpServletResponse response) throws ServletException, 
                  IOException { 
     response.setContentType(CONTENT_TYPE); 
     DownloadDocDAO DownloadInstance = new DownloadDocDAO(); 
     String downloadType = request.getParameter("downloadType"); 
     String pNumber = request.getParameter("PNumber"); 
     BufferedOutputStream output = null; 
     String strFileName = pNumber + ".pdf"; 
     if(downloadType != null && downloadType.equalsIgnoreCase("download")){ 
      try{ 
       byte[] content=DownloadInstance.getP(pNumber);     
       log.info("COnverting content into PDF in EmailServlet"); 
       System.out.println("COnverting content into PDF in EmailServlet"); 
       response.setContentType("application/pdf"); 
       response.setHeader("Content-Disposition","attachment; filename=\"" + strFileName + "\""); 
       response.setHeader("Cache-Control","no-cache"); 
       response.setHeader("Cache-Control","no-store"); 
       response.setHeader("Pragma","no-cache"); 
       response.setDateHeader("Expires", 0); 
       output = new BufferedOutputStream(response.getOutputStream()); 
       output.write(content); 
       output.flush();        
       output.close();     

      } 
      catch (Exception ex) { 
       ex.printStackTrace(); 
       log.error("Error in DownloadDocServlet ", ex); 
       /* Using the below block to trigger the email whenever there is a error*/ 
       Writer result = new StringWriter(); 
       PrintWriter printWriter = new PrintWriter(result); 
       ex.printStackTrace(printWriter); 
       Email emailSend = new Email();         
       int strEmailConfirm = emailSend.sendEmail("Exception in DownloadDocServlet of documentdownload package for pno :"+pNumber,"<B>Please find Exception Details for the DownloadDocServlet of documentdownload package</b><br><br>"+result.toString()); 
       log.info("strEmailConfirm in DownloadDocServlet"+strEmailConfirm); // if value is 1 , mail will be trigger is successful 
      } 
     }   
    } 


} 
+2

這很好 - 任何問題? –

+0

@ScaryWombat - 我不知道如何使用定時器/輪詢機制。如果你可以幫助代碼 –

+0

簡單的循環與5秒的睡眠怎麼樣 –

回答

1

你需要的是某種計時器。以下是如何使用TimerTasks的示例。

首先Timer

Timer downloadTimer = new Timer(); 

,直到你安排TimerTask它沒有做任何事情:

TimerTask downloadTask = new TimerTask() { 
    @Override 
    public void run() { 
     //try to download here 
    }; 
} 

現在你需要安排任務:

downloadTimer.schedule(downloadTask,1000,5000); 

這告訴你的downloadTimer你想要scheduledownloadTask要在1秒內首次執行(1000 milliseconds),然後每5秒執行一次(5000 milliseconds)。

但是除非你停止任務,一旦你成功下載或任務被執行5次,將連續運行:

private int count; 
public void run() { 
    if(count++==5){ 
     downloadTimer.cancel(); // will stop the timer 
     downloadTimer.purge(); // will remove all canceled tasks from the timer 
     return; // makes sure the task will not be executed to the end 
    } 
    // try to download here 
    // if download successful cancel and purge as well 
}; 

這應該做的伎倆,但我不能說,如果這是最好的解決您的問題。

+0

Thnx @gamedroids,但你可以幫助解釋爲什麼定時器是特殊的。正如上面所說的scarywombat,不會有一個簡單的循環與睡眠一樣。 while(content!= null || counter <5) {content = policyDownloadInstance.getPolicy(policyNumber); counter ++; if(content == null) { log ----} Thread.sleep(5000); } –

+0

'Thread.sleep'不妨是個不錯的選擇。這取決於你的情況,如果你將「睡眠」的線程保留在任何資源上並因此阻塞其他線程。也許[這篇文章](http://stackoverflow.com/q/17826651/896249)可以闡明它,並幫助你決定什麼是最好的。您還應該考慮,如果最好讓「調用者」每5秒重試一次或「servlet」。請注意,當servlet花費太長時間來響應時,調用者可能會遇到超時。 – GameDroids

+0

謝謝,我使用睡眠,它運作良好..我怎麼能添加一個等待加載程序到我的代碼,直到線程睡覺? –

0

線程睡眠效果很好,我

for(int i=0;i<5;i++) 
       { 
        content=getPDAO.getPFromEb(strPN); 
         DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss"); 
         Date dateobj = new Date(); 
        if(content==null) 

        { 
         Thread.sleep(5000); 
         } 
        else { 
         content=getPDAO.getPFromEb(strPN); 
         break; 
        } 
       } 
0

您也可以通過使用awaitility做到這一點。請檢查this link如何使用