001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2022, 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.io.IOException;
022import java.io.InterruptedIOException;
023import java.io.Reader;
024import java.io.UncheckedIOException;
025import java.nio.Buffer;
026import java.nio.ByteBuffer;
027import java.nio.CharBuffer;
028import java.nio.charset.Charset;
029import java.nio.charset.CharsetDecoder;
030import java.nio.charset.StandardCharsets;
031import java.util.Objects;
032
033/**
034 * A {@link Reader} that provides the data from the {@link ManagedBuffer}s
035 * fed to it to a consumer. This class is intended to be used as a pipe 
036 * between two threads.  
037 */
038@SuppressWarnings("PMD.AvoidSynchronizedStatement")
039public class ManagedBufferReader extends Reader implements InputConsumer {
040
041    private boolean isEndOfFeed;
042    private boolean isOpen = true;
043    private ManagedBuffer<? extends Buffer> current;
044    private CharsetDecoder decoder;
045    private CharBuffer decoded;
046    private Charset charset = StandardCharsets.UTF_8;
047
048    /**
049     * Sets the charset to be used if {@link #feed(ManagedBuffer)}
050     * is invoked with `ManagedBuffer<ByteBuffer>`. Defaults to UTF-8. 
051     * Must be set before the first invocation of 
052     * {@link #feed(ManagedBuffer)}.  
053     *
054     * @param charset the charset
055     * @return the managed buffer reader
056     */
057    public ManagedBufferReader charset(Charset charset) {
058        if (decoder != null) {
059            throw new IllegalStateException("Charset cannot be changed.");
060        }
061        this.charset = charset;
062        return this;
063    }
064
065    /**
066     * Sets the charset to be used if {@link #feed(ManagedBuffer)}
067     * is invoked with `ManagedBuffer<ByteBuffer>`. Defaults to UTF-8. 
068     * Must be set before the first invocation of 
069     * {@link #feed(ManagedBuffer)}.  
070     *
071     * @param charset the charset
072     * @return the managed buffer reader
073     * @deprecated Use {@link #charset(Charset)} instead
074     */
075    @Deprecated
076    public ManagedBufferReader setCharset(Charset charset) {
077        return charset(charset);
078    }
079
080    /**
081     * Sets the charset to be used if {@link #feed(ManagedBuffer)}
082     * is invoked with `ManagedBuffer<ByteBuffer>` to the charset
083     * specified as system property `native.encoding`. If this
084     * property does not specify a valid charset, 
085     * {@link Charset#defaultCharset()} is used.
086     *  
087     * Must be invoked before the first invocation of 
088     * {@link #feed(ManagedBuffer)}.  
089     *
090     * @return the managed buffer reader
091     */
092    @SuppressWarnings({ "PMD.AvoidCatchingGenericException",
093        "PMD.EmptyCatchBlock" })
094    public ManagedBufferReader nativeCharset() {
095        Charset toSet = Charset.defaultCharset();
096        var toCheck = System.getProperty("native.encoding");
097        if (toCheck != null) {
098            try {
099                toSet = Charset.forName(toCheck);
100            } catch (Exception e) {
101                // If this fails, simply use default
102            }
103        }
104        charset(toSet);
105        return this;
106    }
107
108    /**
109     * Feed data to the reader. The call blocks while data from a previous
110     * invocation has not been fully read. The buffer passed as argument
111     * is locked (see {@link ManagedBuffer#lockBuffer()}) until all
112     * data has been read.
113     * 
114     * Calling this method with `null` as argument closes the feed.
115     * After consuming any data still available from a previous
116     * invocation, further calls to {@link #read} therefore return -1.
117     *
118     * @param buffer the buffer
119     * @throws IOException Signals that an I/O exception has occurred.
120     */
121    @Override
122    @SuppressWarnings({ "PMD.PreserveStackTrace" })
123    public <W extends Buffer> void feed(ManagedBuffer<W> buffer) {
124        synchronized (lock) {
125            if (buffer == null) {
126                isEndOfFeed = true;
127                notifyAll();
128                return;
129            }
130            if (!isOpen || isEndOfFeed) {
131                return;
132            }
133            while (current != null) {
134                try {
135                    lock.wait();
136                } catch (InterruptedException e) {
137                    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
138                    var exc = new InterruptedIOException(e.getMessage());
139                    exc.setStackTrace(e.getStackTrace());
140                    throw new UncheckedIOException(exc);
141                }
142            }
143            current = buffer;
144            buffer.lockBuffer();
145            lock.notifyAll();
146        }
147    }
148
149    /**
150     * {@inheritDoc}
151     * 
152     * Note that this is the {@link Reader}'s `close` method. In order
153     * to close the feed, call {@link #feed(ManagedBuffer)} with
154     * `null` as argument.
155     */
156    @Override
157    public void close() throws IOException {
158        synchronized (lock) {
159            isOpen = false;
160            if (current != null) {
161                current.unlockBuffer();
162                current = null;
163            }
164            lock.notifyAll();
165        }
166    }
167
168    @Override
169    @SuppressWarnings({ "PMD.PreserveStackTrace", "unchecked",
170        "PMD.CognitiveComplexity", "PMD.NcssCount" })
171    public int read(char[] cbuf, int off, int len) throws IOException {
172        Objects.checkFromIndexSize(off, len, cbuf.length);
173        synchronized (lock) {
174            while (isOpen && current == null && !isEndOfFeed) {
175                try {
176                    lock.wait();
177                } catch (InterruptedException e) {
178                    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
179                    var exc = new InterruptedIOException(e.getMessage());
180                    exc.setStackTrace(e.getStackTrace());
181                    throw exc;
182                }
183            }
184            if (!isOpen || isEndOfFeed && current == null) {
185                return -1;
186            }
187            CharBuffer input;
188            if (current.backingBuffer() instanceof CharBuffer) {
189                input = ((ManagedBuffer<CharBuffer>) current).backingBuffer();
190            } else {
191                if (decoder == null) {
192                    decoder = charset.newDecoder();
193                    decoded = CharBuffer.allocate(current.capacity());
194                }
195                var result = decoder.decode(
196                    ((ManagedBuffer<ByteBuffer>) current).backingBuffer(),
197                    decoded, isEndOfFeed);
198                assert !result.isOverflow();
199                decoded.flip();
200                input = decoded;
201            }
202            int transferred;
203            if (input.remaining() <= len) {
204                // Get all remaining.
205                transferred = input.remaining();
206                input.get(cbuf, off, transferred);
207                if (decoded != null) {
208                    decoded.clear();
209                }
210                current.unlockBuffer();
211                current = null;
212                lock.notifyAll();
213            } else {
214                // Get requested.
215                transferred = len;
216                input.get(cbuf, off, transferred);
217            }
218            return transferred;
219        }
220    }
221
222}