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 private final boolean finishOnClose; 022 023 /** 024 * Constructs a new {@code ProgressOutputStream}. 025 * 026 * @param out the stream to monitor 027 * @param size the total size which will be sent 028 * @param progressMonitor the monitor to report to 029 * @param finishOnClose whether to call {@link ProgressMonitor#finishTask} when this stream is closed 030 * @since 10302 031 */ 032 public ProgressOutputStream(OutputStream out, long size, ProgressMonitor progressMonitor, boolean finishOnClose) { 033 this.updater = new StreamProgressUpdater(size, 034 progressMonitor != null ? progressMonitor : NullProgressMonitor.INSTANCE, tr("Uploading data ...")); 035 this.out = out; 036 this.finishOnClose = finishOnClose; 037 } 038 039 @Override 040 public void write(byte[] b, int off, int len) throws IOException { 041 out.write(b, off, len); 042 updater.advanceTicker(len); 043 } 044 045 @Override 046 public void write(int b) throws IOException { 047 out.write(b); 048 updater.advanceTicker(1); 049 } 050 051 @Override 052 public void close() throws IOException { 053 try { 054 out.close(); 055 } finally { 056 if (finishOnClose) { 057 updater.finishTask(); 058 } 059 } 060 } 061}