CRLFLineReader.java

  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. package org.apache.commons.net.io;

  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.Reader;

  21. import org.apache.commons.net.util.NetConstants;

  22. /**
  23.  * 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.
  24.  *
  25.  * @since 3.0
  26.  */
  27. public final class CRLFLineReader extends BufferedReader {
  28.     private static final char LF = '\n';
  29.     private static final char CR = '\r';

  30.     /**
  31.      * Creates a CRLFLineReader that wraps an existing Reader input source.
  32.      *
  33.      * @param reader The Reader input source.
  34.      */
  35.     public CRLFLineReader(final Reader reader) {
  36.         super(reader);
  37.     }

  38.     /**
  39.      * Read a line of text. A line is considered to be terminated by carriage return followed immediately by a linefeed. This contrasts with BufferedReader
  40.      * which also allows other combinations.
  41.      *
  42.      * @since 3.0
  43.      */
  44.     @Override
  45.     public String readLine() throws IOException {
  46.         final StringBuilder sb = new StringBuilder();
  47.         int intch;
  48.         boolean prevWasCR = false;
  49.         synchronized (lock) { // make thread-safe (hopefully!)
  50.             while ((intch = read()) != NetConstants.EOS) {
  51.                 if (prevWasCR && intch == LF) {
  52.                     return sb.substring(0, sb.length() - 1);
  53.                 }
  54.                 prevWasCR = intch == CR;
  55.                 sb.append((char) intch);
  56.             }
  57.         }
  58.         final String string = sb.toString();
  59.         if (string.isEmpty()) { // immediate EOF
  60.             return null;
  61.         }
  62.         return string;
  63.     }
  64. }