2016-03-22 13 views
1

私はOutlookのExchange ServerからメールをダウンロードするJavaコードを使用しています。 私が直面している問題は:インターネット接続がダウンしている場合、プログラムの実行が停止します。Javaでのインターネット接続を確認する

接続が利用可能になるまで、インターネット接続を確認するコードにします。インターネットが接続されていないと、実行を止めたくありません。

インターネット接続をチェックするためのソリューションはありませんが、スタックオーバーフローがありますが、それらのソリューションを使用すると、しばらくしてからstackoverflowエラーが発生します。

private static void checkNetConnectivity() 
{ 
    Socket sock = new Socket(); 
    InetSocketAddress addr = new InetSocketAddress("www.google.com",80); 
    try{ 
     sock.connect(addr,3000); 
     System.out.println("connected"); 
    }catch(Exception e){ 
     System.out.println("not connected"); 
    } 


} 

私は次の関数からメソッドを呼び出しています:

javax.mail.MessagingException::へのルートを

public static void downloadEmails(String protocol, String host, String port, String username, String password) 
{ 
    Properties props = new Properties(); 
    Folder inbox = null; 

    MimeBodyPart bp = null; 
    String mail_subject = null, mail_body = null; 
    int i; 


    props.setProperty("mail.store.protocol", "imaps"); 
    //props.put("mail.pop3.host", host); 
    //props.put("mail.pop3.port", port); 
    //props.put("mail.pop3.starttls.enable", "true"); 
    try 
    { 
     do 
     { 
      checkNetConnectivity(); 
     Session session = Session.getInstance(props); 
     //session.setDebug(true); 
     Store store = session.getStore(protocol); 
     store.connect(host, username, password); 


     inbox = store.getFolder("INBOX"); 
     inbox.open(Folder.READ_WRITE);// READ_WRITE mode is compulsory if you want to set the SEEN flag. 


      cnt = 0; 
      Flags seen = new Flags(Flags.Flag.SEEN); 
      FlagTerm unseenFlagTerm = new FlagTerm(seen, false); 
      Message msg[] = inbox.search(unseenFlagTerm); 
      System.out.println("No of unseen messages : " + msg.length); 
      if (msg.length > 0) 
      { 
       for (i = 0; i < msg.length; i++) 
       { 
        System.out.println("Serial No :" + i); 
        Address[] in = msg[i].getFrom(); 
        for (Address address : in) 
        { 
         System.out.println("FROM:" + address.toString()); 
         //String mail_address = address.toString(); 
        } 
        System.out.println("SENT DATE: " + msg[i].getSentDate()); 
        System.out.println("SUBJECT: " + msg[i].getSubject()); 
        mail_subject = msg[i].getSubject(); 
        Date date = msg[i].getSentDate(); 
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 
        String mail_sent_date = df.format(date); 
        System.out.println("Sent date = "+ mail_sent_date); 


        String str1[] = mail_subject.split("\\|"); 
        int sub_delimiter_count = str1.length - 1; //count of delimiter for validating email subject 


        if (str1[0].equals("1001") && sub_delimiter_count == 3) 
        { 

         System.out.println("Subject line valid."); 

         Object content = msg[i].getContent(); 

         if (content instanceof String) 
         { 
          String body = (String) content; 
          mail_body = body; 

          boolean isValid = new ReadMail().ValidateMail(mail_body); 

          if(isValid) 
          { 
           System.out.println("Email body in proper format."); 
          } 
          else 
          { 
           System.out.println("Email not in proper format.\nIgnoring..."); 
           continue; 
          } 
         } 
         else if (content instanceof Multipart) 
         { 
          System.out.println("This is MultiPart"); 
          MimeMultipart mp = (MimeMultipart) msg[i].getContent(); 
          bp = (MimeBodyPart) mp.getBodyPart(0); 
          InputStream partInput = bp.getInputStream(); 
          mail_body = new Scanner(partInput, "UTF-8").useDelimiter("\\A").next(); 
         } 
         System.out.println("hhhh"); 
         ReadEmail(mail_subject, mail_body, mail_sent_date); 


        } 
        else 
        { 
         System.out.println("Subect not in required format.\nIgnoring..."); 
        } 
        msg[i].setFlag(Flags.Flag.SEEN, true); // for this to work INBOX or any FOLDER has to opened in READ_WRITE mode. 
       } 
      } else { 
       Date date = new Date(); 
       System.out.println("No new messages. Last checked: "+date.toString()); 
      } 

     try { 
      Thread.sleep(2000);     //1000 milliseconds is one second. 
     } catch(InterruptedException ex) { 
      Thread.currentThread().interrupt(); 
     } 
     store.close(); 
     }while(true); 

    }catch(Exception e) 
    { 
     e.printStackTrace(); 
     //downloadEmails(protocol,host,port,username,password); 
    } 

} 

これはインターネットが切断しまったときに私が得た例外でしたホスト:connect;ネストされた 例外は次のとおりです。java.net.NoRouteToHostException:ホストへのルート: setDebug:JavaMailのバージョン1.4.7 DEBUG は com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)DEBUGで接続します。 を返すgetProvider()を返す。を返す。 IMAPS: mail.imap.statuscachetimeout:1000 DEBUG IMAPS: mail.imap.appendbuffersize:-1 DEBUG IMAPS:mail.imap.minidletime:10 DEBUG IMAPS:ホスト "outlook.office365.com"、ポートに接続しようとしています 993、isSSL true

でreadmail.ReadMail.downloadEmails(ReadMail.java:200)で javax.mail.Service.connect(Service.java:176)でjavax.mail.Service.connect(Service.java:295)で

readmail.ReadMail.main(ReadMail.java:323)原因: java.net.NoRouteToHostException:ホストへのルートがありません: に接続します。java.net.DualStackPlainSocketImpl.connect0(ネイティブメソッド) java.net.DualStackPlainSocketImpl.socketConnect java.net.PlainSoで java.net.AbstractPlainSocketImpl.connect(不明なソース)で java.net.AbstractPlainSocketImpl.connectToAddress(不明なソース)で java.net.AbstractPlainSocketImpl.doConnect(不明なソース)で(不明なソース)のjava.net.SocketSmart.connect(不明なソース) の でのjava.net.Socket.connect(不明なソース)の でのcketImpl.connect(不明なソース)。 com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237) at com.sun.mail.iap.Protocol。(Protocol(socketFetcher.java:321) ) (IMAPStore.java:685) com.sun.mail.imap.protocol.IMAPProtocol。(IMAPProtocol.java:115) at com.sun.mail.imap.IMAPStore.newIMAPProtocol sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636) ... 4 more

ご協力いただければ幸いです。

+1

ショー... – epoch

+2

'StackOverflowError'が制御されていない再帰呼び出しで発生する可能性が最も高いので、参照するためのコードを分析しますそのようなことが起こる可能性があります –

+0

「プログラムの実行が停止しました」とはどういう意味ですか?あなたのアプリケーションはクラッシュしますか?もしそうなら、どのような例外がありますか? – Alex

答えて

0

OPのリクエストに従います。 Sargeフレームワークによるリトライの監督。

私はそれを監督できるように、あなたの接続ロジックをMailServiceクラスに外部化しました。

public class MailService { 


public Store connect(String protocol, String host, String username, String password) throws MessagingException{ 

    Properties props = new Properties(); 
    props.setProperty("mail.store.protocol", "imap"); 
    //props.put("mail.pop3.host", host); 
    //props.put("mail.pop3.port", port); 
    //props.put("mail.pop3.starttls.enable", "true"); 

    Session session = Session.getInstance(props); 
    //session.setDebug(true); 
    Store store = session.getStore(protocol); 

    store.connect(host, username, password); 

    return store; 
} 

}

それから私はMailServiceを使用してSargeためPlanを作成するためにあなたのdownloadEmailsの実装を変更しました。

public static void downloadEmails(String protocol, String host, String port, String username, String password) { 

    Plan failurePlan = new Plan() { 
     public Directive apply(Throwable failure) { 
      if (failure instanceof MessagingException) { 
       // if we failed due to ConnectException, then retry five times over a minute. 
       if (((MessagingException) failure).getCause() instanceof ConnectException) { 
        return Directive.Retry(5, Duration.mins(1)); 
       } 
      } 
      return Directive.Escalate; 
     } 

    }; 

    Sarge sarge = new Sarge(); 

    Folder inbox = null; 
    MimeBodyPart bp = null; 
    String mail_subject = null, mail_body = null; 
    int i; 


    try { 

     MailService supervisedMailService = sarge.supervised(MailService.class, failurePlan); 

     do { 

      Store store = supervisedMailService.connect(protocol, host, username, password); 

      inbox = store.getFolder("INBOX"); 
      inbox.open(Folder.READ_WRITE); 

// ... yada yada yada ... your code 

この例では、ConnectExceptionsがスローされたときに1分に5回再試行します。必要に応じて、計画に他の失敗/再試行のケースを追加します。

編集

私たちはあなたを助けるソリューションと私のポンポン

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>org.hall</groupId> 
    <artifactId>sarge</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <name>SargeExample</name> 
    <description>SargeExample</description> 
    <dependencies> 
    <dependency> 
     <groupId>javax.mail</groupId> 
     <artifactId>mail</artifactId> 
     <version>1.4.7</version> 
    </dependency> 
    <dependency> 
     <groupId>net.jodah</groupId> 
     <artifactId>sarge</artifactId> 
     <version>0.3.1</version> 
    </dependency> 
    </dependencies> 
</project> 
+0

私はコードを変更しましたが、コードを実行することができません。sargeに必要な設定はありますか?私はそれに新しいので、私は何をすべきか考えていない。お元気ですか? –

+0

私はMaven pomを追加しました。 Mavenはコンパイルと実行に必要な依存関係をダウンロードします。 MavenやGradleを使用していない場合は、その使い方の基本的な理解を深めることをお勧めします。 – MarkOfHall