1 package net.sf.openrocket.gui.util;
3 import java.io.BufferedInputStream;
5 import java.io.FileInputStream;
6 import java.io.FilterInputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InterruptedIOException;
11 import javax.swing.SwingWorker;
13 import net.sf.openrocket.document.OpenRocketDocument;
14 import net.sf.openrocket.file.DatabaseMotorFinder;
15 import net.sf.openrocket.file.RocketLoader;
16 import net.sf.openrocket.logging.LogHelper;
17 import net.sf.openrocket.startup.Application;
18 import net.sf.openrocket.util.MathUtil;
22 * A SwingWorker thread that opens a rocket design file.
24 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
26 public class OpenFileWorker extends SwingWorker<OpenRocketDocument, Void> {
27 private static final LogHelper log = Application.getLogger();
29 private final File file;
30 private final InputStream stream;
31 private final RocketLoader loader;
33 public OpenFileWorker(File file, RocketLoader loader) {
40 public OpenFileWorker(InputStream stream, RocketLoader loader) {
46 public RocketLoader getRocketLoader() {
51 protected OpenRocketDocument doInBackground() throws Exception {
54 // Get the correct input stream
56 is = new FileInputStream(file);
61 // Buffer stream unless already buffered
62 if (!(is instanceof BufferedInputStream)) {
63 is = new BufferedInputStream(is);
66 // Encapsulate in a ProgressInputStream
67 is = new ProgressInputStream(is);
70 return loader.load(is, new DatabaseMotorFinder());
74 } catch (Exception e) {
75 Application.getExceptionHandler().handleErrorCondition("Error closing file", e);
83 private class ProgressInputStream extends FilterInputStream {
85 private final int size;
86 private int readBytes = 0;
87 private int progress = -1;
89 protected ProgressInputStream(InputStream in) {
94 } catch (IOException e) {
95 log.info("Exception while estimating available bytes!", e);
98 size = Math.max(s, 1);
104 public int read() throws IOException {
111 throw new InterruptedIOException("OpenFileWorker was cancelled");
117 public int read(byte[] b, int off, int len) throws IOException {
118 int n = in.read(b, off, len);
124 throw new InterruptedIOException("OpenFileWorker was cancelled");
130 public int read(byte[] b) throws IOException {
137 throw new InterruptedIOException("OpenFileWorker was cancelled");
143 public long skip(long n) throws IOException {
144 long nr = in.skip(n);
150 throw new InterruptedIOException("OpenFileWorker was cancelled");
156 public synchronized void reset() throws IOException {
158 readBytes = size - in.available();
161 throw new InterruptedIOException("OpenFileWorker was cancelled");
167 private void setProgress() {
168 int p = MathUtil.clamp(readBytes * 100 / size, 0, 100);
171 OpenFileWorker.this.setProgress(progress);