1 | package org.openstreetmap.josm.io;
|
---|
2 |
|
---|
3 | import java.io.IOException;
|
---|
4 | import java.io.InputStreamReader;
|
---|
5 | import java.io.Reader;
|
---|
6 | import java.net.URLConnection;
|
---|
7 |
|
---|
8 | import javax.swing.BoundedRangeModel;
|
---|
9 | import javax.swing.JLabel;
|
---|
10 |
|
---|
11 | /**
|
---|
12 | * Read from an other reader and increment an progress counter while on the way.
|
---|
13 | * @author Imi
|
---|
14 | */
|
---|
15 | public class ProgressReader extends Reader {
|
---|
16 |
|
---|
17 | private final Reader in;
|
---|
18 | private final BoundedRangeModel progress;
|
---|
19 | private final JLabel currentAction;
|
---|
20 | private int readSoFar = 0;
|
---|
21 |
|
---|
22 | public ProgressReader(URLConnection con, BoundedRangeModel progress, JLabel currentAction) throws IOException {
|
---|
23 | this.in = new InputStreamReader(con.getInputStream());
|
---|
24 | this.progress = progress;
|
---|
25 | this.currentAction = currentAction;
|
---|
26 | int contentLength = con.getContentLength();
|
---|
27 | if (contentLength > 0)
|
---|
28 | progress.setMaximum(contentLength);
|
---|
29 | else
|
---|
30 | progress.setMaximum(0);
|
---|
31 | progress.setValue(0);
|
---|
32 | }
|
---|
33 |
|
---|
34 | @Override public void close() throws IOException {
|
---|
35 | in.close();
|
---|
36 | }
|
---|
37 |
|
---|
38 | @Override public int read(char[] cbuf, int off, int len) throws IOException {
|
---|
39 | int read = in.read(cbuf, off, len);
|
---|
40 | readSoFar += read;
|
---|
41 |
|
---|
42 | String progStr = " ("+readSoFar+"/";
|
---|
43 | if (progress.getMaximum() == 0)
|
---|
44 | progStr += "???)";
|
---|
45 | else
|
---|
46 | progStr += progress.getMaximum()+")";
|
---|
47 |
|
---|
48 | String cur = currentAction.getText();
|
---|
49 | int i = cur.indexOf(' ');
|
---|
50 | if (i != -1)
|
---|
51 | cur = cur.substring(0, i) + progStr;
|
---|
52 | else
|
---|
53 | cur += progStr;
|
---|
54 | currentAction.setText(cur);
|
---|
55 | progress.setValue(readSoFar);
|
---|
56 | return read;
|
---|
57 | }
|
---|
58 |
|
---|
59 | }
|
---|