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  import org.apache.commons.net.util.NetConstants;
25  
26  /**
27   * CRLFLineReader implements a readLine() method that requires exactly CRLF to terminate an input line. 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      private static final char LF = '\n';
33      private static final char CR = '\r';
34  
35      /**
36       * Creates a CRLFLineReader that wraps an existing Reader input source.
37       *
38       * @param reader The Reader input source.
39       */
40      public CRLFLineReader(final Reader reader) {
41          super(reader);
42      }
43  
44      /**
45       * Read a line of text. A line is considered to be terminated by carriage return followed immediately by a linefeed. This contrasts with BufferedReader
46       * which also allows other combinations.
47       *
48       * @since 3.0
49       */
50      @Override
51      public String readLine() throws IOException {
52          final StringBuilder sb = new StringBuilder();
53          int intch;
54          boolean prevWasCR = false;
55          synchronized (lock) { // make thread-safe (hopefully!)
56              while ((intch = read()) != NetConstants.EOS) {
57                  if (prevWasCR && intch == LF) {
58                      return sb.substring(0, sb.length() - 1);
59                  }
60                  prevWasCR = intch == CR;
61                  sb.append((char) intch);
62              }
63          }
64          final String string = sb.toString();
65          if (string.isEmpty()) { // immediate EOF
66              return null;
67          }
68          return string;
69      }
70  }