001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2016-2018 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;
020
021import java.io.IOException;
022import java.nio.ByteBuffer;
023import java.nio.channels.AsynchronousCloseException;
024import java.nio.channels.AsynchronousFileChannel;
025import java.nio.channels.ClosedChannelException;
026import java.nio.channels.CompletionHandler;
027import java.nio.channels.SeekableByteChannel;
028import java.nio.file.Files;
029import java.nio.file.OpenOption;
030import java.nio.file.Path;
031import java.nio.file.StandardOpenOption;
032import java.util.Arrays;
033import java.util.Collections;
034import java.util.Map;
035import java.util.WeakHashMap;
036import java.util.stream.Collectors;
037import org.jgrapes.core.Channel;
038import org.jgrapes.core.Component;
039import org.jgrapes.core.Components;
040import org.jgrapes.core.Event;
041import org.jgrapes.core.annotation.Handler;
042import org.jgrapes.core.events.Stop;
043import org.jgrapes.io.events.Close;
044import org.jgrapes.io.events.Closed;
045import org.jgrapes.io.events.FileOpened;
046import org.jgrapes.io.events.IOError;
047import org.jgrapes.io.events.Input;
048import org.jgrapes.io.events.OpenFile;
049import org.jgrapes.io.events.Opening;
050import org.jgrapes.io.events.Output;
051import org.jgrapes.io.events.SaveInput;
052import org.jgrapes.io.events.SaveOutput;
053import org.jgrapes.io.events.StreamFile;
054import org.jgrapes.io.util.ManagedBuffer;
055import org.jgrapes.io.util.ManagedBufferPool;
056
057/**
058 * A component that reads from or writes to a file.
059 */
060@SuppressWarnings({ "PMD.CouplingBetweenObjects",
061    "PMD.AvoidSynchronizedStatement" })
062public class FileStorage extends Component {
063
064    private int bufferSize;
065
066    private final Map<Channel, Writer> inputWriters = Collections
067        .synchronizedMap(new WeakHashMap<>());
068    private final Map<Channel, Writer> outputWriters = Collections
069        .synchronizedMap(new WeakHashMap<>());
070
071    /**
072     * Create a new instance using the given size for the read buffers.
073     * 
074     * @param channel the component's channel. Used for sending {@link Output}
075     * events and receiving {@link Input} events 
076     * @param bufferSize the size of the buffers used for reading
077     */
078    public FileStorage(Channel channel, int bufferSize) {
079        super(channel);
080        this.bufferSize = bufferSize;
081    }
082
083    /**
084     * Create a new instance using the default buffer size of 8192.
085     * 
086     * @param channel the component's channel. Used for sending {@link Output}
087     * events and receiving {@link Input} events 
088     */
089    public FileStorage(Channel channel) {
090        this(channel, 8192);
091    }
092
093    /**
094     * Opens a file for reading using the properties of the event and streams
095     * its content as a sequence of {@link Output} events with the 
096     * end of record flag set in the last event. All generated events are 
097     * considered responses to this event and therefore fired using the event 
098     * processor from the event's I/O subchannel.
099     * 
100     * @param event the event
101     * @throws InterruptedException if the execution was interrupted
102     */
103    @Handler
104    @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops" })
105    public void onStreamFile(StreamFile event)
106            throws InterruptedException {
107        if (Arrays.asList(event.options())
108            .contains(StandardOpenOption.WRITE)) {
109            throw new IllegalArgumentException(
110                "Cannot stream file opened for writing.");
111        }
112        for (IOSubchannel channel : event.channels(IOSubchannel.class)) {
113            if (inputWriters.containsKey(channel)) {
114                channel.respond(new IOError(event,
115                    new IllegalStateException("File is already open.")));
116            } else {
117                new FileStreamer(event, channel);
118            }
119        }
120    }
121
122    /**
123     * A file streamer.
124     */
125    private final class FileStreamer {
126
127        private final IOSubchannel channel;
128        private final Path path;
129        @SuppressWarnings("PMD.ImmutableField")
130        private AsynchronousFileChannel ioChannel;
131        private ManagedBufferPool<ManagedBuffer<ByteBuffer>,
132                ByteBuffer> ioBuffers;
133        private long offset;
134        private final CompletionHandler<Integer,
135                ManagedBuffer<ByteBuffer>> readCompletionHandler
136                    = new ReadCompletionHandler();
137
138        private FileStreamer(StreamFile event, IOSubchannel channel)
139                throws InterruptedException {
140            this.channel = channel;
141            path = event.path();
142            offset = 0;
143            try {
144                try {
145                    ioChannel = AsynchronousFileChannel
146                        .open(event.path(), event.options());
147                } catch (UnsupportedOperationException e) {
148                    runReaderThread(event);
149                    return;
150                }
151            } catch (IOException e) {
152                channel.respond(new IOError(event, e));
153                return;
154            }
155            registerAsGenerator();
156            // Reading from file
157            ioBuffers = new ManagedBufferPool<>(ManagedBuffer::new,
158                () -> {
159                    return ByteBuffer.allocateDirect(bufferSize);
160                }, 2);
161            ManagedBuffer<ByteBuffer> buffer = ioBuffers.acquire();
162            // (1) Opening, (2) FileOpened, (3) Output events
163            channel.respond(Event
164                .onCompletion(new Opening<OpenFile>().setResult(event), e -> {
165                    channel.respond(new FileOpened(event));
166                    // Start reading.
167                    synchronized (ioChannel) {
168                        ioChannel.read(buffer.backingBuffer(), offset, buffer,
169                            readCompletionHandler);
170                    }
171                }));
172        }
173
174        /**
175         * The read completion handler.
176         */
177        private final class ReadCompletionHandler implements
178                CompletionHandler<Integer, ManagedBuffer<ByteBuffer>> {
179            @Override
180            @SuppressWarnings("PMD.EmptyCatchBlock")
181            public void completed(Integer result,
182                    ManagedBuffer<ByteBuffer> buffer) {
183                if (result >= 0) {
184                    offset += result;
185                    boolean eof = true;
186                    try {
187                        eof = offset == ioChannel.size();
188                    } catch (IOException e1) {
189                        // Handled like true
190                    }
191                    channel.respond(Output.fromSink(buffer, eof));
192                    if (!eof) {
193                        try {
194                            ManagedBuffer<ByteBuffer> nextBuffer
195                                = ioBuffers.acquire();
196                            nextBuffer.clear();
197                            synchronized (ioChannel) {
198                                ioChannel.read(nextBuffer.backingBuffer(),
199                                    offset,
200                                    nextBuffer, readCompletionHandler);
201                            }
202                        } catch (InterruptedException e) {
203                            // Results in empty buffer
204                        }
205                        return;
206                    }
207                }
208                IOException ioExc = null;
209                try {
210                    ioChannel.close();
211                } catch (ClosedChannelException e) {
212                    // Can be ignored
213                } catch (IOException e) {
214                    ioExc = e;
215                }
216                channel.respond(new Closed<>(ioExc));
217                unregisterAsGenerator();
218            }
219
220            @Override
221            public void failed(Throwable exc,
222                    ManagedBuffer<ByteBuffer> context) {
223                channel.respond(new Closed<>(exc));
224                unregisterAsGenerator();
225            }
226        }
227
228        /**
229         * Stream file that doesn't support asynchronous I/O.
230         * 
231         * @param event
232         * @throws IOException
233         */
234        private void runReaderThread(StreamFile event)
235                throws IOException {
236            ioBuffers = new ManagedBufferPool<>(ManagedBuffer::new,
237                () -> {
238                    return ByteBuffer.allocateDirect(bufferSize);
239                }, 2);
240            @SuppressWarnings("PMD.CloseResource")
241            final SeekableByteChannel ioChannel
242                = Files.newByteChannel(event.path(), event.options());
243            activeEventPipeline().executorService().submit(new Runnable() {
244                @Override
245                @SuppressWarnings("PMD.EmptyCatchBlock")
246                public void run() {
247                    // Reading from file
248                    IOException ioExc = null;
249                    try {
250                        long size = ioChannel.size();
251                        while (ioChannel.position() < size) {
252                            ManagedBuffer<ByteBuffer> buffer
253                                = ioBuffers.acquire();
254                            buffer.fillFromChannel(ioChannel);
255                            channel.respond(Output.fromSink(buffer,
256                                ioChannel.position() == size));
257                        }
258                        ioChannel.close();
259                    } catch (InterruptedException e) {
260                        return;
261                    } catch (ClosedChannelException e) {
262                        // Can be ignored
263                    } catch (IOException e) {
264                        ioExc = e;
265                    }
266                    channel.respond(new Closed<>(ioExc));
267                }
268            });
269        }
270
271        /*
272         * (non-Javadoc)
273         * 
274         * @see java.lang.Object#toString()
275         */
276        @Override
277        public String toString() {
278            StringBuilder builder = new StringBuilder(50);
279            builder.append("FileStreamer [");
280            if (channel != null) {
281                builder.append("channel=").append(Channel.toString(channel))
282                    .append(", ");
283            }
284            if (path != null) {
285                builder.append("path=").append(path).append(", ");
286            }
287            builder.append("offset=")
288                .append(offset)
289                .append(']');
290            return builder.toString();
291        }
292
293    }
294
295    /**
296     * Opens a file for writing using the properties of the event. All data from
297     * subsequent {@link Input} events is written to the file.
298     * The end of record flag is ignored.
299     * 
300     * @param event the event
301     * @throws InterruptedException if the execution was interrupted
302     */
303    @Handler
304    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
305    public void onSaveInput(SaveInput event) throws InterruptedException {
306        if (!Arrays.asList(event.options())
307            .contains(StandardOpenOption.WRITE)) {
308            throw new IllegalArgumentException(
309                "File must be opened for writing.");
310        }
311        for (IOSubchannel channel : event.channels(IOSubchannel.class)) {
312            if (inputWriters.containsKey(channel)) {
313                channel.respond(new IOError(event,
314                    new IllegalStateException("File is already open.")));
315            } else {
316                new Writer(event, channel);
317            }
318        }
319    }
320
321    /**
322     * Handle input by writing it to the file, if a channel exists.
323     *
324     * @param event the event
325     * @param channel the channel
326     */
327    @Handler
328    public void onInput(Input<ByteBuffer> event, Channel channel) {
329        Writer writer = inputWriters.get(channel);
330        if (writer != null) {
331            writer.write(event.buffer());
332        }
333    }
334
335    /**
336     * Opens a file for writing using the properties of the event. All data from
337     * subsequent {@link Output} events is written to the file. 
338     * The end of record flag is ignored.
339     * 
340     * @param event the event
341     * @throws InterruptedException if the execution was interrupted
342     */
343    @Handler
344    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
345    public void onSaveOutput(SaveOutput event) throws InterruptedException {
346        if (!Arrays.asList(event.options())
347            .contains(StandardOpenOption.WRITE)) {
348            throw new IllegalArgumentException(
349                "File must be opened for writing.");
350        }
351        for (IOSubchannel channel : event.channels(IOSubchannel.class)) {
352            if (outputWriters.containsKey(channel)) {
353                channel.respond(new IOError(event,
354                    new IllegalStateException("File is already open.")));
355            } else {
356                new Writer(event, channel);
357            }
358        }
359    }
360
361    /**
362     * Handle {@link Output} events by writing them to the file, if
363     * a channel exists.
364     *
365     * @param event the event
366     * @param channel the channel
367     */
368    @Handler
369    public void onOutput(Output<ByteBuffer> event, Channel channel) {
370        Writer writer = outputWriters.get(channel);
371        if (writer != null) {
372            writer.write(event.buffer());
373        }
374    }
375
376    /**
377     * Handle close by closing the file associated with the channel.
378     *
379     * @param event the event
380     * @param channel the channel
381     * @throws InterruptedException the interrupted exception
382     */
383    @Handler
384    public void onClose(Close event, Channel channel)
385            throws InterruptedException {
386        Writer writer = inputWriters.get(channel);
387        if (writer != null) {
388            writer.close(event);
389        }
390        writer = outputWriters.get(channel);
391        if (writer != null) {
392            writer.close(event);
393        }
394    }
395
396    /**
397     * Handle stop by closing all files.
398     *
399     * @param event the event
400     * @throws InterruptedException the interrupted exception
401     */
402    @Handler(priority = -1000)
403    public void onStop(Stop event) throws InterruptedException {
404        while (!inputWriters.isEmpty()) {
405            Writer handler = inputWriters.entrySet().iterator().next()
406                .getValue();
407            handler.close(event);
408        }
409        while (!outputWriters.isEmpty()) {
410            Writer handler = outputWriters.entrySet().iterator().next()
411                .getValue();
412            handler.close(event);
413        }
414    }
415
416    /**
417     * A writer.
418     */
419    @SuppressWarnings("PMD.PublicMemberInNonPublicType")
420    private class Writer {
421
422        private final IOSubchannel channel;
423        private Path path;
424        private AsynchronousFileChannel ioChannel;
425        private long offset;
426        private final CompletionHandler<Integer,
427                WriteContext> writeCompletionHandler
428                    = new WriteCompletionHandler();
429        private int outstandingAsyncs;
430
431        /**
432         * The write context needs to be finer grained than the general file
433         * connection context because an asynchronous write may be only
434         * partially successful, i.e. not all data provided by the write event
435         * may successfully be written in one asynchronous write invocation.
436         */
437        private class WriteContext {
438            public final ManagedBuffer<ByteBuffer>.ByteBufferView reader;
439            public final long pos;
440
441            /**
442             * Instantiates a new write context.
443             *
444             * @param reader the reader
445             * @param pos the pos
446             */
447            public WriteContext(
448                    ManagedBuffer<ByteBuffer>.ByteBufferView reader, long pos) {
449                this.reader = reader;
450                this.pos = pos;
451            }
452        }
453
454        /**
455         * Instantiates a new writer.
456         *
457         * @param event the event
458         * @param channel the channel
459         * @throws InterruptedException the interrupted exception
460         */
461        public Writer(SaveInput event, IOSubchannel channel)
462                throws InterruptedException {
463            this(event, event.path(), event.options(), channel);
464            inputWriters.put(channel, this);
465            channel.respond(new FileOpened(event));
466        }
467
468        /**
469         * Instantiates a new writer.
470         *
471         * @param event the event
472         * @param channel the channel
473         * @throws InterruptedException the interrupted exception
474         */
475        public Writer(SaveOutput event, IOSubchannel channel)
476                throws InterruptedException {
477            this(event, event.path(), event.options(), channel);
478            outputWriters.put(channel, this);
479            channel.respond(new FileOpened(event));
480        }
481
482        private Writer(Event<?> event, Path path, OpenOption[] options,
483                IOSubchannel channel) throws InterruptedException {
484            this.channel = channel;
485            this.path = path;
486            offset = 0;
487            try {
488                ioChannel = AsynchronousFileChannel.open(path, options);
489            } catch (IOException e) {
490                channel.respond(new IOError(event, e));
491            }
492        }
493
494        /**
495         * Write the buffer.
496         *
497         * @param buffer the buffer
498         */
499        public void write(ManagedBuffer<ByteBuffer> buffer) {
500            int written = buffer.remaining();
501            if (written == 0) {
502                return;
503            }
504            buffer.lockBuffer();
505            synchronized (ioChannel) {
506                if (outstandingAsyncs == 0) {
507                    registerAsGenerator();
508                }
509                outstandingAsyncs += 1;
510                ManagedBuffer<ByteBuffer>.ByteBufferView reader
511                    = buffer.newByteBufferView();
512                ioChannel.write(reader.get(), offset,
513                    new WriteContext(reader, offset),
514                    writeCompletionHandler);
515            }
516            offset += written;
517        }
518
519        /**
520         * A write completion handler.
521         */
522        private final class WriteCompletionHandler
523                implements CompletionHandler<Integer, WriteContext> {
524
525            @Override
526            public void completed(Integer result, WriteContext context) {
527                ManagedBuffer<ByteBuffer>.ByteBufferView reader
528                    = context.reader;
529                if (reader.get().hasRemaining()) {
530                    ioChannel.write(reader.get(),
531                        context.pos + reader.get().position(),
532                        context, writeCompletionHandler);
533                    return;
534                }
535                reader.managedBuffer().unlockBuffer();
536                handled();
537            }
538
539            @Override
540            public void failed(Throwable exc, WriteContext context) {
541                try {
542                    if (!(exc instanceof AsynchronousCloseException)) {
543                        channel.respond(new IOError(null, exc));
544                    }
545                } finally {
546                    handled();
547                }
548            }
549
550            @SuppressWarnings("PMD.AssignmentInOperand")
551            private void handled() {
552                synchronized (ioChannel) {
553                    if (--outstandingAsyncs == 0) {
554                        unregisterAsGenerator();
555                        ioChannel.notifyAll();
556                    }
557                }
558            }
559        }
560
561        /**
562         * Close.
563         *
564         * @param event the event
565         * @throws InterruptedException the interrupted exception
566         */
567        @SuppressWarnings({ "PMD.EmptyCatchBlock" })
568        public void close(Event<?> event)
569                throws InterruptedException {
570            IOException ioExc = null;
571            try {
572                synchronized (ioChannel) {
573                    while (outstandingAsyncs > 0) {
574                        ioChannel.wait();
575                    }
576                    ioChannel.close();
577                }
578            } catch (ClosedChannelException e) {
579                // Can be ignored
580            } catch (IOException e) {
581                ioExc = e;
582            }
583            channel.respond(new Closed<>(ioExc));
584            inputWriters.remove(channel);
585            outputWriters.remove(channel);
586        }
587
588        /*
589         * (non-Javadoc)
590         * 
591         * @see java.lang.Object#toString()
592         */
593        @Override
594        public String toString() {
595            StringBuilder builder = new StringBuilder(50);
596            builder.append("FileConnection [");
597            if (channel != null) {
598                builder.append("channel=")
599                    .append(Channel.toString(channel))
600                    .append(", ");
601            }
602            if (path != null) {
603                builder.append("path=")
604                    .append(path)
605                    .append(", ");
606            }
607            builder.append("offset=")
608                .append(offset)
609                .append(']');
610            return builder.toString();
611        }
612
613    }
614
615    /*
616     * (non-Javadoc)
617     * 
618     * @see java.lang.Object#toString()
619     */
620    @Override
621    public String toString() {
622        StringBuilder builder = new StringBuilder();
623        builder.append(Components.objectName(this))
624            .append(" [");
625        if (inputWriters != null) {
626            builder.append(inputWriters.values().stream().map(
627                Components::objectName).collect(Collectors.toList()));
628        }
629        builder.append(']');
630        return builder.toString();
631    }
632}