001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.IOException;
007import java.io.InputStream;
008import java.util.Optional;
009
010import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
011import org.openstreetmap.josm.gui.progress.ProgressMonitor;
012import org.openstreetmap.josm.tools.CheckParameterUtil;
013
014/**
015 * Read from an other reader and increment an progress counter while on the way.
016 * @author Imi
017 */
018public class ProgressInputStream extends InputStream {
019
020    private final StreamProgressUpdater updater;
021    private final InputStream in;
022
023    /**
024     * Constructs a new {@code ProgressInputStream}.
025     *
026     * @param in the stream to monitor. Must not be null
027     * @param size the total size which will be sent
028     * @param progressMonitor the monitor to report to
029     * @since 9172
030     */
031    public ProgressInputStream(InputStream in, long size, ProgressMonitor progressMonitor) {
032        CheckParameterUtil.ensureParameterNotNull(in, "in");
033        this.updater = new StreamProgressUpdater(size,
034                Optional.ofNullable(progressMonitor).orElse(NullProgressMonitor.INSTANCE), tr("Downloading data..."));
035        this.in = in;
036    }
037
038    @Override
039    public void close() throws IOException {
040        try {
041            in.close();
042        } finally {
043            updater.finishTask();
044        }
045    }
046
047    @Override
048    public int read(byte[] b, int off, int len) throws IOException {
049        int read = in.read(b, off, len);
050        if (read != -1) {
051            updater.advanceTicker(read);
052        } else {
053            updater.finishTask();
054        }
055        return read;
056    }
057
058    @Override
059    public int read() throws IOException {
060        int read = in.read();
061        if (read != -1) {
062            updater.advanceTicker(1);
063        } else {
064            updater.finishTask();
065        }
066        return read;
067    }
068}