2 * Sonitus - FileSource.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sonitus.data.source;
20 import static com.google.common.base.Preconditions.checkNotNull;
22 import java.io.EOFException;
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.List;
30 import net.pterodactylus.sonitus.data.AbstractFilter;
31 import net.pterodactylus.sonitus.data.Controller;
32 import net.pterodactylus.sonitus.data.DataPacket;
33 import net.pterodactylus.sonitus.data.Filter;
34 import net.pterodactylus.sonitus.data.Metadata;
35 import net.pterodactylus.sonitus.io.IdentifyingInputStream;
37 import com.google.common.base.Optional;
40 * A {@link Filter} that reads a file from the local file system and does not
43 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45 public class FileSource extends AbstractFilter {
47 /** The path of the file. */
48 private final String path;
50 /** The input stream. */
51 private InputStream fileInputStream;
54 * Creates a new file source.
57 * The path of the file
58 * @throws java.io.IOException
59 * if the file can not be found, or an I/O error occurs
61 public FileSource(String path) throws IOException {
63 this.path = checkNotNull(path, "path must not be null");
64 fileInputStream = new FileInputStream(path);
66 /* identify file type. */
67 Optional<IdentifyingInputStream> identifyingInputStream = IdentifyingInputStream.create(new FileInputStream(path));
68 if (identifyingInputStream.isPresent()) {
69 metadataUpdated(identifyingInputStream.get().metadata());
72 metadataUpdated(new Metadata().name(path));
81 public List<Controller<?>> controllers() {
82 return Collections.emptyList();
86 public DataPacket get(int bufferSize) throws IOException {
87 byte[] buffer = new byte[bufferSize];
88 int read = fileInputStream.read(buffer);
90 throw new EOFException();
92 return new DataPacket(metadata(), Arrays.copyOf(buffer, read));
100 public String toString() {
101 return String.format("%s (%s)", path, metadata());