View Javadoc
1   /*
2    * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
3    * Copyright (C) 2010  Mickael Guessant
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18   */
19  package davmail.exchange;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.PushbackInputStream;
24  
25  /**
26   * Replace double dot lines with single dot in input stream.
27   * A line with a single dot means end of stream
28   */
29  public class DoubleDotInputStream extends PushbackInputStream {
30      final int[] buffer = new int[4];
31      int index = -1;
32  
33      public DoubleDotInputStream(InputStream in) {
34          super(in, 4);
35      }
36  
37      /**
38       * Push current byte to buffer and read next byte.
39       *
40       * @return next byte
41       * @throws IOException on error
42       */
43      protected int readNextByte() throws IOException {
44          int b = super.read();
45          buffer[++index] = b;
46          return b;
47      }
48  
49      @Override
50      public int read() throws IOException {
51          int b = super.read();
52          if (b == '\r') {
53              // \r\n
54              if (readNextByte() == '\n') {
55                  // \r\n.
56                  if (readNextByte() == '.') {
57                      // \r\n.\r
58                      if (readNextByte() == '\r') {
59                          // \r\n.\r\n
60                          if (readNextByte() == '\n') {
61                              // end of stream
62                              index = -1;
63                              b = -1;
64                          }
65                          // \r\n..
66                      } else if (buffer[index] == '.') {
67                          // replace double dot
68                          index--;
69                      }
70                  }
71              }
72              // push back characters
73              if (index >= 0) {
74                  while (index >= 0) {
75                      unread(buffer[index--]);
76                  }
77              }
78          }
79          return b;
80      }
81  
82  }