001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2023 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.io.util;
020
021import java.nio.Buffer;
022import java.nio.ByteBuffer;
023import java.nio.CharBuffer;
024import java.nio.charset.Charset;
025import java.nio.charset.CharsetDecoder;
026import java.nio.charset.StandardCharsets;
027import java.util.Queue;
028import java.util.concurrent.ConcurrentLinkedQueue;
029import java.util.function.Consumer;
030
031/**
032 * Collects character data from buffers and makes it available as
033 * complete lines.
034 * 
035 * Lines end with a LF which may optionally be followed by a CR.
036 * Neither character is part of the result returned by {@link #getLine()}.
037 * If no more input is expected and characters without trailing LF
038 * remain, these remaining character are returned as a line as well.   
039 */
040public class LineCollector implements InputConsumer {
041    private boolean isEof;
042    private CharsetDecoder decoder;
043    private Charset charset = StandardCharsets.UTF_8;
044    private CharBuffer pending;
045    private CharBuffer rest;
046    private boolean endedWithLF;
047    private final Queue<String> lines = new ConcurrentLinkedQueue<>();
048    private Consumer<String> consumer = lines::add;
049
050    /**
051     * Sets the charset to be used if {@link #feed(ManagedBuffer)}
052     * is invoked with `ManagedBuffer<ByteBuffer>`. Defaults to UTF-8. 
053     * Must be set before the first invocation of 
054     * {@link #feed(ManagedBuffer)}.  
055     *
056     * @param charset the charset
057     * @return the managed buffer reader
058     */
059    public LineCollector charset(Charset charset) {
060        if (decoder != null) {
061            throw new IllegalStateException("Charset cannot be changed.");
062        }
063        this.charset = charset;
064        return this;
065    }
066
067    /**
068     * Sets the charset to be used if {@link #feed(ManagedBuffer)}
069     * is invoked with `ManagedBuffer<ByteBuffer>` to the charset
070     * specified as system property `native.encoding`. If this
071     * property does not specify a valid charset, 
072     * {@link Charset#defaultCharset()} is used.
073     *  
074     * Must be invoked before the first invocation of 
075     * {@link #feed(ManagedBuffer)}.  
076     *
077     * @return the managed buffer reader
078     */
079    @SuppressWarnings({ "PMD.AvoidCatchingGenericException",
080        "PMD.EmptyCatchBlock" })
081    public LineCollector nativeCharset() {
082        Charset toSet = Charset.defaultCharset();
083        var toCheck = System.getProperty("native.encoding");
084        if (toCheck != null) {
085            try {
086                toSet = Charset.forName(toCheck);
087            } catch (Exception e) {
088                // If this fails, simply use default
089            }
090        }
091        charset(toSet);
092        return this;
093    }
094
095    /**
096     * Configures a consumer for lines. The consumer is invoked when
097     * a complete line has been detected. If a consumer is configured,
098     * {@link #getLine()} may not be used (always returns `null`).
099     *
100     * @param consumer the consumer
101     * @return the line collector
102     */
103    public LineCollector consumer(Consumer<String> consumer) {
104        this.consumer = consumer;
105        return this;
106    }
107
108    /**
109     * Feed data to the collector. 
110     * 
111     * Calling this method with `null` as argument closes the feed.
112     *
113     * @param buffer the buffer
114     */
115    public <W extends Buffer> void feed(W buffer) {
116        if (isEof) {
117            return;
118        }
119        if (buffer == null) {
120            isEof = true;
121        } else {
122            copyToPending(buffer);
123        }
124        extractLines();
125
126    }
127
128    /**
129     * Feed data to the collector. 
130     * 
131     * Calling this method with `null` as argument closes the feed.
132     *
133     * @param buffer the buffer
134     */
135    @Override
136    public <W extends Buffer> void feed(ManagedBuffer<W> buffer) {
137        if (buffer == null) {
138            feed((W) null);
139        } else {
140            feed(buffer.backingBuffer());
141        }
142    }
143
144    private <W extends Buffer> void copyToPending(W buffer) {
145        try {
146            buffer.mark();
147            if (pending == null) {
148                pending = CharBuffer.allocate(buffer.capacity());
149            }
150            if (buffer instanceof CharBuffer charBuf) {
151                if (pending.remaining() < charBuf.remaining()) {
152                    resizePending(charBuf);
153                }
154                pending.put(charBuf);
155                return;
156            }
157            if (decoder == null) {
158                decoder = charset.newDecoder();
159            }
160            while (true) {
161                var result
162                    = decoder.decode((ByteBuffer) buffer, pending, isEof);
163                if (!result.isOverflow()) {
164                    break;
165                }
166                // Need larger buffer
167                resizePending(buffer);
168            }
169        } finally {
170            buffer.reset();
171        }
172    }
173
174    private void resizePending(Buffer toAppend) {
175        var old = pending;
176        pending = CharBuffer.allocate(old.capacity() + toAppend.capacity());
177        old.flip();
178        pending.put(old);
179    }
180
181    @SuppressWarnings({ "PMD.CognitiveComplexity", "PMD.NcssCount",
182        "PMD.AvoidLiteralsInIfCondition", "PMD.AvoidReassigningLoopVariables",
183        "PMD.AvoidBranchingStatementAsLastInLoop", "PMD.CyclomaticComplexity",
184        "PMD.AvoidInstantiatingObjectsInLoops" })
185    private void extractLines() {
186        pending.flip();
187        if (!pending.hasRemaining()) {
188            pending.clear();
189            return;
190        }
191        if (endedWithLF && pending.get(pending.position()) == '\r') {
192            pending.get();
193        }
194        int end = pending.limit();
195        endedWithLF = false;
196        while (pending.hasRemaining()) {
197            int start = pending.position();
198            for (int pos = start; pos < end;) {
199                if (pending.get(pos) != '\n') {
200                    pos += 1;
201                    continue;
202                }
203                consumer
204                    .accept(new String(pending.array(), start, pos - start));
205                pos += 1;
206                endedWithLF = pos >= end;
207                if (pos < end && pending.get(pos) == '\r') {
208                    pos += 1;
209                }
210                pending.position(pos);
211                break;
212            }
213            if (pending.position() == start) {
214                // No LF found
215                break;
216            }
217        }
218        if (!pending.hasRemaining()) {
219            // Last input was or ended with complete line
220            pending.clear();
221            return;
222        }
223        // Incomplete line
224        if (isEof) {
225            consumer.accept(new String(pending.array(), pending.position(),
226                pending.remaining()));
227            return;
228        }
229        if (pending.position() == 0) {
230            // Nothing consumed, continue to write into pending
231            var limit = pending.limit();
232            pending.clear();
233            pending.position(limit);
234            return;
235        }
236        // Transfer remaining to beginning of pending
237        if (rest == null || rest.capacity() < pending.remaining()) {
238            rest = CharBuffer.allocate(pending.capacity());
239        }
240        rest.put(pending);
241        rest.flip();
242        pending.clear();
243        pending.put(rest);
244        rest.clear();
245    }
246
247    /**
248     * Checks if more input may become available.
249     *
250     * @return true, if successful
251     */
252    public boolean eof() {
253        return isEof;
254    }
255
256    /**
257     * Gets the next line.
258     *
259     * @return the line
260     */
261    public String getLine() {
262        return lines.poll();
263    }
264}