Statistics
| Revision:

svn-gvsig-desktop / branches / MULTITHREADING_DEVELOPMENT / libraries / libRemoteServices / src / org / gvsig / remoteClient / taskplanning / retrieving / URLRetrieveTask.java @ 5245

History | View | Annotate | Download (8.04 KB)

1
/*
2
 * Created on 01-oct-2005
3
 */
4
package org.gvsig.remoteClient.taskplanning.retrieving;
5

    
6
import java.io.BufferedOutputStream;
7
import java.io.DataOutputStream;
8
import java.io.File;
9
import java.io.FileOutputStream;
10
import java.io.IOException;
11
import java.io.InputStream;
12
import java.net.MalformedURLException;
13
import java.net.URL;
14
import java.util.Iterator;
15
import java.util.Vector;
16

    
17
import org.gvsig.remoteClient.taskplanning.IRunnableTask;
18

    
19
/**
20
 * Clase para bajar ficheros en un thread independiente.
21
 * La idea (y parte del c?digo) est? tomada de EarthFlicks
22
 * @author Luis W. Sevilla (sevilla_lui@gva.es)
23
 * @see http://today.java.net/lpt/a/212
24
 */
25
public class URLRetrieveTask  implements IRunnableTask {
26
        
27
        private boolean running, cancelled;
28
        private URLRequest request;
29
        private InputStream is;
30
        
31
        /**
32
         * 
33
         */
34
        public URLRetrieveTask(URLRequest request) {
35
                this.request = request;
36
                running = cancelled = false;
37
        }
38
        
39

    
40
        public void execute() {
41
                request.setStatus(RetrieveEvent.NOT_STARTED);
42
                cancelled = false;
43
                running= true;
44
                
45
                long t = System.currentTimeMillis();
46
                File f = new File(request.getFileName()+System.currentTimeMillis());
47
                while (f.exists()) {
48
                        t++;
49
                        f = new File(request.getFileName()+t);
50
                }
51
                URL url;
52
                try {
53
                        request.setStatus(RetrieveEvent.CONNECTING);
54
                        
55
                        url = request.getUrl();
56
                        request.setFileName(f.getAbsolutePath());
57
                        System.out.println("downloading '"+url+"' to: "+f.getAbsolutePath());
58
                        
59
                        DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)));
60
                        byte[] buffer = new byte[1024*256];
61
                        is = url.openStream();
62
                        request.setStatus(RetrieveEvent.TRANSFERRING);
63
                        if (!cancelled) {
64
                                long readed = 0;
65
                                for (int i = is.read(buffer); !cancelled && i>0; i = is.read(buffer)){
66
                                        dos.write(buffer, 0, i);
67
                                        readed += i;
68
                                }
69
                                
70
                                dos.close();
71
                        }
72
                        
73
                        if (cancelled) {
74
                                // Bad incomplete file, delete it.
75
                                System.out.println("download cancelled ("+url+")");
76
                                f.delete();
77
                        } else {
78
                                // register job in the cache
79
                                // TODO aix? deuria d'estar al principi per a poder capturar
80
                                // treballs que s'estan fent per? que encara no s'han acabat
81
//                                synchronized (this) {
82
//                                        RequestManager.getInstance().addDownloadedURLRequest(request);
83
//                                }
84
                        }
85
                        
86
                        running = false;
87
                        if (cancelled)
88
                                request.setStatus(RetrieveEvent.REQUEST_CANCELLED);
89
                        else
90
                                request.setStatus(RetrieveEvent.REQUEST_FINISHED);
91
                        
92
                } catch (MalformedURLException e) {
93
                        e.printStackTrace();
94
                        request.setStatus(RetrieveEvent.REQUEST_FAILED);
95
                } catch (IOException e) {
96
                        e.printStackTrace();
97
                        request.setStatus(RetrieveEvent.REQUEST_FAILED);
98
                }
99
        }
100

    
101
//        private void fireEvent() {
102
//                Iterator it = listeners.iterator();
103
//                while (it.hasNext()) {
104
//                        RetrieveListener listener = (RetrieveListener) it.next();
105
//                        listener.transferEventReceived(event);                
106
//                }
107
//        }
108

    
109
        public void cancel() {
110
                cancelled = true;
111
                try {
112
                        if (is != null) {
113
                                is.close();
114
                                is = null;
115
                        }
116
                } catch (IOException e) {
117
                        e.printStackTrace();
118
                }
119
        }
120

    
121
        public boolean isRunning() {
122
                return running && !cancelled;
123
        }
124

    
125

    
126
        public URLRequest getRequest() {
127
                return request;
128
        }
129
}
130

    
131

    
132
//static private String makeSuffix(String contentType) {
133
//        contentType = contentType.toLowerCase();
134
//    if (contentType.indexOf("png") >= 0)
135
//        return ".png";
136
//
137
//    if (contentType.indexOf("xml") >= 0)
138
//        return ".xml";
139
//
140
//    if (contentType.indexOf("gif") >= 0)
141
//        return ".gif";
142
//
143
//    if (contentType.indexOf("tif") >= 0)
144
//        return ".tif";
145
//
146
//    if (contentType.indexOf("jpg") >= 0
147
//        || contentType.indexOf("jpeg") >= 0)
148
//        return ".jpg";
149
//
150
//    if (contentType.indexOf("html") >= 0)
151
//        return ".html";
152
//
153
//    return "";
154
//}
155
///**
156
// * 
157
// */
158
//private void end() {
159
//}
160
//
161
///**
162
// * 
163
// */
164
//private void inThreadEnd() {
165
//}
166
//
167
///**
168
// * 
169
// */
170
//private void update() {
171
//}
172
//
173
///**
174
// * 
175
// */
176
//private void begin() {
177
//}
178

    
179
//public void start() {
180
//// this.reset();
181
//this.thread = new Thread(this);
182
//this.thread.start();
183
//}
184

    
185
/* (non-Javadoc)
186
* @see java.lang.Runnable#run()
187
* /
188
public void run() {
189
try {
190
        URL url = request.getUrl();
191
        this.status = Status.CONNECTING;
192
        this.begin();
193
        
194
    {
195
        // Retrieve the contents.
196
        int numBytesRead = 0;
197
//        System.out.println("File being retrieved. " + this.getUrl().toString());
198
        java.net.URLConnection connection = url.openConnection();
199
        connection.setAllowUserInteraction(true);
200
        java.io.InputStream incoming = connection.getInputStream();
201
        this.contentLength = connection.getContentLength();
202
        this.contentType = connection.getContentType();
203

204
        java.io.File destFile = java.io.File.createTempFile("Cq_", makeSuffix(this.contentType));
205
        destFile.deleteOnExit(); // It's copied later if it's to be persisted.
206
        this.destination = destFile.getPath();
207
        java.io.FileOutputStream outgoing = new java.io.FileOutputStream(destFile);
208

209
        this.status = Status.RETRIEVING;
210

211
        byte[] buffer = new byte[4096];
212

213
        try {
214
            while (!Thread.currentThread().isInterrupted() && numBytesRead >= 0) {
215
                numBytesRead = incoming.read(buffer);
216
                if (numBytesRead > 0) {
217
                    this.bytesRead += numBytesRead;
218
                    outgoing.write(buffer, 0, numBytesRead);
219
                    this.update();
220
                }
221
            }
222
        } finally {
223
            if (incoming != null)
224
                try {incoming.close();} catch (java.io.IOException e) {}; // TODO: log it maybe
225
            if (outgoing != null)
226
                try {outgoing.close();} catch (java.io.IOException e) {}; // TODO: log it maybe
227
        }
228
        this.status = Status.POSTPROCESSING;
229
    }
230
} catch (Exception e) {
231
    this.status = Status.ERROR;
232
    this.error = e;
233
    e.printStackTrace();
234
} finally {
235
    if (Thread.currentThread().isInterrupted())
236
        this.status = Status.INTERRUPTED;
237
    this.update();
238
    this.inThreadEnd();
239
    if (this.status == Status.POSTPROCESSING)
240
        this.status = Status.DONE;
241
    this.end();
242
}
243
}*/
244

    
245
//File tempDirectory = new File(tempDirectoryPath);
246
//if (!tempDirectory.exists())
247
//tempDirectory.mkdir();
248
//
249
//f = new File(tempDirectoryPath+"/"+name+System.currentTimeMillis());
250
//if (cancelled)
251
//throw new TaskCancelledException(); 
252
//addDownloadedURL(url, f.getAbsolutePath());
253
//try {
254
//URL url = request.getUrl();
255
//System.out.println(url);
256
//this.status = Status.CONNECTING;
257
//this.begin();
258
//
259
//{
260
//// Retrieve the contents.
261
//int numBytesRead = 0;
262
////System.out.println("File being retrieved. " + this.getUrl().toString());
263
//java.net.URLConnection connection = url.openConnection();
264
//connection.setAllowUserInteraction(true);
265
//java.io.InputStream incoming = connection.getInputStream();
266
//this.contentLength = connection.getContentLength();
267
//this.contentType = connection.getContentType();
268
//
269
//java.io.File destFile = java.io.File.createTempFile("Cq_", makeSuffix(this.contentType));
270
//System.out.println(destFile.getAbsolutePath());
271
////destFile.deleteOnExit(); // It's copied later if it's to be persisted.
272
//this.destination = destFile.getPath();
273
//java.io.FileOutputStream outgoing = new java.io.FileOutputStream(destFile);
274
//
275
//this.status = Status.RETRIEVING;
276
//
277
//byte[] buffer = new byte[4096];
278
//
279
//try {
280
//while (!Thread.currentThread().isInterrupted() && numBytesRead >= 0) {
281
//numBytesRead = incoming.read(buffer);
282
//if (numBytesRead > 0) {
283
//this.bytesRead += numBytesRead;
284
//outgoing.write(buffer, 0, numBytesRead);
285
//this.update();
286
//}
287
//}
288
//} finally {
289
//if (incoming != null)
290
//try {incoming.close();} catch (java.io.IOException e) {}; // TODO: log it maybe
291
//if (outgoing != null)
292
//try {outgoing.close();} catch (java.io.IOException e) {}; // TODO: log it maybe
293
//}
294
//this.status = Status.POSTPROCESSING;
295
//}
296
//} catch (Exception e) {
297
//this.status = Status.ERROR;
298
//this.error = e;
299
//e.printStackTrace();
300
//} finally {
301
//if (Thread.currentThread().isInterrupted())
302
//this.status = Status.INTERRUPTED;
303
//this.update();
304
//this.inThreadEnd();
305
//if (this.status == Status.POSTPROCESSING)
306
//this.status = Status.DONE;
307
//this.end();
308
//}
309