1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.io;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.io.IOException;
|
---|
7 | import java.io.InputStream;
|
---|
8 | import java.util.Optional;
|
---|
9 |
|
---|
10 | import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
|
---|
11 | import org.openstreetmap.josm.gui.progress.ProgressMonitor;
|
---|
12 | import org.openstreetmap.josm.tools.CheckParameterUtil;
|
---|
13 |
|
---|
14 | /**
|
---|
15 | * Read from an other reader and increment an progress counter while on the way.
|
---|
16 | * @author Imi
|
---|
17 | */
|
---|
18 | public class ProgressInputStream extends InputStream {
|
---|
19 |
|
---|
20 | private final StreamProgressUpdater updater;
|
---|
21 | private final InputStream in;
|
---|
22 |
|
---|
23 | /**
|
---|
24 | * Constructs a new {@code ProgressInputStream}.
|
---|
25 | *
|
---|
26 | * @param in the stream to monitor. Must not be null
|
---|
27 | * @param size the total size which will be sent
|
---|
28 | * @param progressMonitor the monitor to report to
|
---|
29 | * @since 9172
|
---|
30 | */
|
---|
31 | public ProgressInputStream(InputStream in, long size, ProgressMonitor progressMonitor) {
|
---|
32 | CheckParameterUtil.ensureParameterNotNull(in, "in");
|
---|
33 | this.updater = new StreamProgressUpdater(size,
|
---|
34 | Optional.ofNullable(progressMonitor).orElse(NullProgressMonitor.INSTANCE), tr("Downloading data..."));
|
---|
35 | this.in = in;
|
---|
36 | }
|
---|
37 |
|
---|
38 | @Override
|
---|
39 | public void close() throws IOException {
|
---|
40 | try {
|
---|
41 | in.close();
|
---|
42 | } finally {
|
---|
43 | updater.finishTask();
|
---|
44 | }
|
---|
45 | }
|
---|
46 |
|
---|
47 | @Override
|
---|
48 | public int read(byte[] b, int off, int len) throws IOException {
|
---|
49 | int read = in.read(b, off, len);
|
---|
50 | if (read != -1) {
|
---|
51 | updater.advanceTicker(read);
|
---|
52 | } else {
|
---|
53 | updater.finishTask();
|
---|
54 | }
|
---|
55 | return read;
|
---|
56 | }
|
---|
57 |
|
---|
58 | @Override
|
---|
59 | public int read() throws IOException {
|
---|
60 | int read = in.read();
|
---|
61 | if (read != -1) {
|
---|
62 | updater.advanceTicker(1);
|
---|
63 | } else {
|
---|
64 | updater.finishTask();
|
---|
65 | }
|
---|
66 | return read;
|
---|
67 | }
|
---|
68 | }
|
---|