View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.net.io;
19  
20  import java.io.BufferedReader;
21  import java.io.IOException;
22  import java.io.Reader;
23  
24  /**
25   * CRLFLineReader implements a readLine() method that requires
26   * exactly CRLF to terminate an input line.
27   * This is required for IMAP, which allows bare CR and LF.
28   *
29   * @since 3.0
30   */
31  public final class CRLFLineReader extends BufferedReader
32  {
33      private static final char LF = '\n';
34      private static final char CR = '\r';
35  
36      /**
37       * Creates a CRLFLineReader that wraps an existing Reader
38       * input source.
39       * @param reader  The Reader input source.
40       */
41      public CRLFLineReader(Reader reader)
42      {
43          super(reader);
44      }
45  
46      /**
47       * Read a line of text.
48       * A line is considered to be terminated by carriage return followed immediately by a linefeed.
49       * This contrasts with BufferedReader which also allows other combinations.
50       * @since 3.0
51       */
52      @Override
53      public String readLine() throws IOException {
54          StringBuilder sb = new StringBuilder();
55          int intch;
56          boolean prevWasCR = false;
57          synchronized(lock) { // make thread-safe (hopefully!)
58              while((intch = read()) != -1)
59              {
60                  if (prevWasCR && intch == LF) {
61                      return sb.substring(0, sb.length()-1);
62                  }
63                  if (intch == CR) {
64                      prevWasCR = true;
65                  } else {
66                      prevWasCR = false;
67                  }
68                  sb.append((char) intch);
69              }
70          }
71          String string = sb.toString();
72          if (string.length() == 0) { // immediate EOF
73              return null;
74          }
75          return string;
76      }
77  }