source: josm/branch/0.5/src/org/openstreetmap/josm/io/ProgressInputStream.java

Last change on this file was 298, checked in by imi, 18 years ago
  • added license description to head of each source file
File size: 2.6 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.io;
3
4import java.io.IOException;
5import java.io.InputStream;
6import java.net.URLConnection;
7
8import org.openstreetmap.josm.gui.PleaseWaitDialog;
9
10/**
11 * Read from an other reader and increment an progress counter while on the way.
12 * @author Imi
13 */
14public class ProgressInputStream extends InputStream {
15
16 private final InputStream in;
17 private int readSoFar = 0;
18 private int lastDialogUpdate = 0;
19 private final URLConnection connection;
20 private PleaseWaitDialog pleaseWaitDlg;
21
22 public class OsmServerException extends IOException {
23 private OsmServerException(String e) {
24 super(e);
25 }
26 }
27
28 public ProgressInputStream(URLConnection con, PleaseWaitDialog pleaseWaitDlg) throws IOException, OsmServerException {
29 this.connection = con;
30
31 try {
32 this.in = con.getInputStream();
33 } catch (IOException e) {
34 if (con.getHeaderField("Error") != null)
35 throw new OsmServerException(con.getHeaderField("Error"));
36 throw e;
37 }
38
39 int contentLength = con.getContentLength();
40 this.pleaseWaitDlg = pleaseWaitDlg;
41 if (pleaseWaitDlg == null)
42 return;
43 if (contentLength > 0)
44 pleaseWaitDlg.progress.setMaximum(contentLength);
45 else
46 pleaseWaitDlg.progress.setMaximum(0);
47 pleaseWaitDlg.progress.setValue(0);
48 }
49
50 @Override public void close() throws IOException {
51 in.close();
52 }
53
54 @Override public int read(byte[] b, int off, int len) throws IOException {
55 int read = in.read(b, off, len);
56 if (read != -1)
57 advanceTicker(read);
58 return read;
59 }
60
61 @Override public int read() throws IOException {
62 int read = in.read();
63 if (read != -1)
64 advanceTicker(1);
65 return read;
66 }
67
68 /**
69 * Increase ticker (progress counter and displayed text) by the given amount.
70 * @param amount
71 */
72 private void advanceTicker(int amount) {
73 if (pleaseWaitDlg == null)
74 return;
75
76 if (pleaseWaitDlg.progress.getMaximum() == 0 && connection.getContentLength() != -1)
77 pleaseWaitDlg.progress.setMaximum(connection.getContentLength());
78
79 readSoFar += amount;
80
81 if (readSoFar / 1024 != lastDialogUpdate) {
82 lastDialogUpdate++;
83 String progStr = " "+readSoFar/1024+"/";
84 progStr += (pleaseWaitDlg.progress.getMaximum()==0) ? "??? KB" : (pleaseWaitDlg.progress.getMaximum()/1024)+" KB";
85 pleaseWaitDlg.progress.setValue(readSoFar);
86
87 String cur = pleaseWaitDlg.currentAction.getText();
88 int i = cur.indexOf(' ');
89 if (i != -1)
90 cur = cur.substring(0, i) + progStr;
91 else
92 cur += progStr;
93 pleaseWaitDlg.currentAction.setText(cur);
94 }
95 }
96}
Note: See TracBrowser for help on using the repository browser.