| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package com.carrotsearch.procfork; |
| 8 |
|
| 9 |
import java.io.FileNotFoundException; |
| 10 |
import java.io.IOException; |
| 11 |
import java.io.InputStream; |
| 12 |
import java.io.RandomAccessFile; |
| 13 |
import java.nio.file.Path; |
| 14 |
import java.util.function.Supplier; |
| 15 |
|
| 16 |
|
| 17 |
public class TailInputStream extends InputStream { |
| 18 |
|
| 19 |
private static final long TAIL_CHECK_DELAY = 250; |
| 20 |
|
| 21 |
private final RandomAccessFile raf; |
| 22 |
private volatile boolean closed; |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
private final Supplier<Boolean> noMoreInput; |
| 29 |
|
| 30 |
public TailInputStream(Path file, Supplier<Boolean> noMoreInput) throws FileNotFoundException { |
| 31 |
this.raf = new RandomAccessFile(file.toFile(), "r"); |
| 32 |
this.noMoreInput = noMoreInput; |
| 33 |
} |
| 34 |
|
| 35 |
@Override |
| 36 |
public int read() throws IOException { |
| 37 |
if (closed) return -1; |
| 38 |
|
| 39 |
try { |
| 40 |
int c; |
| 41 |
while ((c = raf.read()) == -1) { |
| 42 |
if (noMoreInput.get()) { |
| 43 |
return -1; |
| 44 |
} |
| 45 |
try { |
| 46 |
Thread.sleep(TAIL_CHECK_DELAY); |
| 47 |
} catch (InterruptedException e) { |
| 48 |
throw new IOException(e); |
| 49 |
} |
| 50 |
} |
| 51 |
return c; |
| 52 |
} catch (IOException e) { |
| 53 |
if (closed) return -1; |
| 54 |
else throw e; |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
@Override |
| 59 |
public int read(byte[] b, int off, int len) throws IOException { |
| 60 |
if (closed) return -1; |
| 61 |
|
| 62 |
if (b == null) { |
| 63 |
throw new NullPointerException(); |
| 64 |
} else if (off < 0 || len < 0 || len > b.length - off) { |
| 65 |
throw new IndexOutOfBoundsException(); |
| 66 |
} else if (len == 0) { |
| 67 |
return 0; |
| 68 |
} |
| 69 |
|
| 70 |
try { |
| 71 |
int rafRead = raf.read(b, off, len); |
| 72 |
if (rafRead == -1) { |
| 73 |
|
| 74 |
do { |
| 75 |
if (noMoreInput.get()) { |
| 76 |
return -1; |
| 77 |
} |
| 78 |
|
| 79 |
try { |
| 80 |
Thread.sleep(TAIL_CHECK_DELAY); |
| 81 |
} catch (InterruptedException e) { |
| 82 |
throw new IOException(e); |
| 83 |
} |
| 84 |
} while ((rafRead = raf.read(b, off, len)) == -1); |
| 85 |
} |
| 86 |
return rafRead; |
| 87 |
} catch (IOException e) { |
| 88 |
if (closed) return -1; |
| 89 |
else throw e; |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
@Override |
| 94 |
public int read(byte[] b) throws IOException { |
| 95 |
return read(b, 0, b.length); |
| 96 |
} |
| 97 |
|
| 98 |
@Override |
| 99 |
public boolean markSupported() { |
| 100 |
return false; |
| 101 |
} |
| 102 |
|
| 103 |
@Override |
| 104 |
public void close() throws IOException { |
| 105 |
closed = true; |
| 106 |
this.raf.close(); |
| 107 |
} |
| 108 |
} |