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.OutputStream;
008
009import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
010import org.openstreetmap.josm.gui.progress.ProgressMonitor;
011
012/**
013 * An {@link OutputStream} which reports progress to the {@link ProgressMonitor}.
014 *
015 * @since 9185
016 */
017public class ProgressOutputStream extends OutputStream {
018
019    private final StreamProgressUpdater updater;
020    private final OutputStream out;
021
022    /**
023     * Constructs a new {@code ProgressOutputStream}.
024     *
025     * @param out the stream to monitor
026     * @param size the total size which will be sent
027     * @param progressMonitor the monitor to report to
028     */
029    public ProgressOutputStream(OutputStream out, long size, ProgressMonitor progressMonitor) {
030        if (progressMonitor == null) {
031            progressMonitor = NullProgressMonitor.INSTANCE;
032        }
033        this.updater = new StreamProgressUpdater(size, progressMonitor, tr("Uploading data ..."));
034        this.out = out;
035    }
036
037    @Override
038    public void write(byte[] b, int off, int len) throws IOException {
039        out.write(b, off, len);
040        updater.advanceTicker(len);
041    }
042
043    @Override
044    public void write(int b) throws IOException {
045        out.write(b);
046        updater.advanceTicker(1);
047    }
048
049    @Override
050    public void close() throws IOException {
051        try {
052            out.close();
053        } finally {
054            updater.finishTask();
055        }
056    }
057}