    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.net.io;
    019
    020import java.io.BufferedReader;
    021import java.io.IOException;
    022import java.io.Reader;
    023
    024import org.apache.commons.net.util.NetConstants;
    025
    026/**
    027 * 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.
    028 *
    029 * @since 3.0
    030 */
    031public final class CRLFLineReader extends BufferedReader {
    032    private static final char LF = '\n';
    033    private static final char CR = '\r';
    034
    035    /**
    036     * Creates a CRLFLineReader that wraps an existing Reader input source.
    037     *
    038     * @param reader The Reader input source.
    039     */
    040    public CRLFLineReader(final Reader reader) {
    041        super(reader);
    042    }
    043
    044    /**
    045     * Reads a line of text. A line is considered to be terminated by carriage return followed immediately by a linefeed. This contrasts with BufferedReader
    046     * which also allows other combinations.
    047     *
    048     * @since 3.0
    049     */
    050    @Override
    051    public String readLine() throws IOException {
    052        final StringBuilder sb = new StringBuilder();
    053        int intch;
    054        boolean prevWasCR = false;
    055        synchronized (lock) { // make thread-safe (hopefully!)
    056            while ((intch = read()) != NetConstants.EOS) {
    057                if (prevWasCR && intch == LF) {
    058                    return sb.substring(0, sb.length() - 1);
    059                }
    060                prevWasCR = intch == CR;
    061                sb.append((char) intch);
    062            }
    063        }
    064        final String string = sb.toString();
    065        if (string.isEmpty()) { // immediate EOF
    066            return null;
    067        }
    068        return string;
    069    }
    070}