Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.remoteclient / src / main / java / org / gvsig / remoteclient / taskplanning / retrieving / URLRetrieveTask.java @ 40559

History | View | Annotate | Download (9.37 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
/*
25
 * Created on 01-oct-2005
26
 */
27
package org.gvsig.remoteclient.taskplanning.retrieving;
28

    
29
import java.io.BufferedOutputStream;
30
import java.io.DataOutputStream;
31
import java.io.File;
32
import java.io.FileOutputStream;
33
import java.io.IOException;
34
import java.io.InputStream;
35
import java.net.MalformedURLException;
36
import java.net.URL;
37
import java.util.Iterator;
38
import java.util.Vector;
39

    
40
import org.gvsig.remoteclient.taskplanning.IRunnableTask;
41

    
42
/**
43
 * Clase para bajar ficheros en un thread independiente.
44
 * La idea (y parte del c?digo) est? tomada de EarthFlicks
45
 * @author Luis W. Sevilla (sevilla_lui@gva.es)
46
 * @see http://today.java.net/lpt/a/212
47
 */
48
public class URLRetrieveTask  implements IRunnableTask {
49
        
50
        private boolean running, cancelled;
51
        private URLRequest request;
52
        private Vector listeners = new Vector();
53
        private RetrieveEvent event = new RetrieveEvent();
54
        private InputStream is;
55
        
56
        /**
57
         * 
58
         */
59
        public URLRetrieveTask(URLRequest request, RetrieveListener listener) {
60
                this.request = request;
61
                addRetrieveListener(listener);
62
                running = cancelled = false;
63
        }
64
        
65

    
66
        public void execute() {
67
                event.setType(RetrieveEvent.NOT_STARTED);
68
                fireEvent();
69
                cancelled = false;
70
                running= true;
71
                
72
                long t = System.currentTimeMillis();
73
                File f = new File(request.getFileName()+System.currentTimeMillis());
74
                while (f.exists()) {
75
                        t++;
76
                        f = new File(request.getFileName()+t);
77
                }
78
                URL url;
79
                try {
80
                        event.setType(RetrieveEvent.CONNECTING);
81
                        fireEvent();
82
                        url = request.getUrl();
83
                        request.setFileName(f.getAbsolutePath());
84
                        System.out.println("downloading '"+url+"' to: "+f.getAbsolutePath());
85
                        
86
                        DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)));
87
                        byte[] buffer = new byte[1024*256];
88
                        fireEvent();
89
                        is = url.openStream();
90
                        event.setType(RetrieveEvent.TRANSFERRING);
91
                        fireEvent();
92
                        if (!cancelled) {
93
                                long readed = 0;
94
                                for (int i = is.read(buffer); !cancelled && i>0; i = is.read(buffer)){
95
                                        dos.write(buffer, 0, i);
96
                                        readed += i;
97
                                }
98
                                
99
                                dos.close();
100
                        }
101
                        
102
                        if (cancelled) {
103
                                // Bad incomplete file, delete it.
104
                                System.out.println("download cancelled ("+url+")");
105
                                f.delete();
106
                        } else {
107
                                // register job in the cache
108
                                // TODO aix? deuria d'estar al principi per a poder capturar
109
                                // treballs que s'estan fent per? que encara no s'han acabat
110
                                synchronized (this) {
111
                                        RequestManager.getInstance().addDownloadedURLRequest(request, f.getAbsolutePath());
112
                                }
113
                        }
114
                        
115
                        running = false;
116
                        if (cancelled)
117
                                event.setType(RetrieveEvent.REQUEST_CANCELLED);
118
                        else
119
                                event.setType(RetrieveEvent.REQUEST_FINISHED);
120
                        
121
                } catch (MalformedURLException e) {
122
                        e.printStackTrace();
123
                        event.setType(RetrieveEvent.REQUEST_FAILED);
124
                } catch (IOException e) {
125
                        e.printStackTrace();
126
                        event.setType(RetrieveEvent.REQUEST_FAILED);
127
                }
128
                fireEvent();
129
        }
130

    
131
        private void fireEvent() {
132
                Iterator it = listeners.iterator();
133
                while (it.hasNext()) {
134
                        RetrieveListener listener = (RetrieveListener) it.next();
135
                        listener.transferEventReceived(event);                
136
                }
137
        }
138

    
139
        public void addRetrieveListener(RetrieveListener l) {
140
                if (l!=null)
141
                        listeners.add(l);
142
        }
143

    
144
        public void cancel() {
145
                cancelled = true;
146
                try {
147
                        if (is != null) {
148
                                is.close();
149
                                is = null;
150
                        }
151
                } catch (IOException e) {
152
                        e.printStackTrace();
153
                }
154
        }
155

    
156
        public boolean isRunning() {
157
                return running && !cancelled;
158
        }
159

    
160

    
161
        public URLRequest getRequest() {
162
                return request;
163
        }
164

    
165

    
166
        public Vector getListeners() {
167
                return listeners;
168
        }
169

    
170

    
171
        public long getTaskTimeout() {
172
                return 30*1000;
173
        }
174
}
175

    
176

    
177
//static private String makeSuffix(String contentType) {
178
//        contentType = contentType.toLowerCase();
179
//    if (contentType.indexOf("png") >= 0)
180
//        return ".png";
181
//
182
//    if (contentType.indexOf("xml") >= 0)
183
//        return ".xml";
184
//
185
//    if (contentType.indexOf("gif") >= 0)
186
//        return ".gif";
187
//
188
//    if (contentType.indexOf("tif") >= 0)
189
//        return ".tif";
190
//
191
//    if (contentType.indexOf("jpg") >= 0
192
//        || contentType.indexOf("jpeg") >= 0)
193
//        return ".jpg";
194
//
195
//    if (contentType.indexOf("html") >= 0)
196
//        return ".html";
197
//
198
//    return "";
199
//}
200
///**
201
// * 
202
// */
203
//private void end() {
204
//}
205
//
206
///**
207
// * 
208
// */
209
//private void inThreadEnd() {
210
//}
211
//
212
///**
213
// * 
214
// */
215
//private void update() {
216
//}
217
//
218
///**
219
// * 
220
// */
221
//private void begin() {
222
//}
223

    
224
//public void start() {
225
//// this.reset();
226
//this.thread = new Thread(this);
227
//this.thread.start();
228
//}
229

    
230
/* (non-Javadoc)
231
* @see java.lang.Runnable#run()
232
* /
233
public void run() {
234
try {
235
        URL url = request.getUrl();
236
        this.status = Status.CONNECTING;
237
        this.begin();
238
        
239
    {
240
        // Retrieve the contents.
241
        int numBytesRead = 0;
242
//        System.out.println("File being retrieved. " + this.getUrl().toString());
243
        java.net.URLConnection connection = url.openConnection();
244
        connection.setAllowUserInteraction(true);
245
        java.io.InputStream incoming = connection.getInputStream();
246
        this.contentLength = connection.getContentLength();
247
        this.contentType = connection.getContentType();
248

249
        java.io.File destFile = java.io.File.createTempFile("Cq_", makeSuffix(this.contentType));
250
        destFile.deleteOnExit(); // It's copied later if it's to be persisted.
251
        this.destination = destFile.getPath();
252
        java.io.FileOutputStream outgoing = new java.io.FileOutputStream(destFile);
253

254
        this.status = Status.RETRIEVING;
255

256
        byte[] buffer = new byte[4096];
257

258
        try {
259
            while (!Thread.currentThread().isInterrupted() && numBytesRead >= 0) {
260
                numBytesRead = incoming.read(buffer);
261
                if (numBytesRead > 0) {
262
                    this.bytesRead += numBytesRead;
263
                    outgoing.write(buffer, 0, numBytesRead);
264
                    this.update();
265
                }
266
            }
267
        } finally {
268
            if (incoming != null)
269
                try {incoming.close();} catch (java.io.IOException e) {}; // TODO: log it maybe
270
            if (outgoing != null)
271
                try {outgoing.close();} catch (java.io.IOException e) {}; // TODO: log it maybe
272
        }
273
        this.status = Status.POSTPROCESSING;
274
    }
275
} catch (Exception e) {
276
    this.status = Status.ERROR;
277
    this.error = e;
278
    e.printStackTrace();
279
} finally {
280
    if (Thread.currentThread().isInterrupted())
281
        this.status = Status.INTERRUPTED;
282
    this.update();
283
    this.inThreadEnd();
284
    if (this.status == Status.POSTPROCESSING)
285
        this.status = Status.DONE;
286
    this.end();
287
}
288
}*/
289

    
290
//File tempDirectory = new File(tempDirectoryPath);
291
//if (!tempDirectory.exists())
292
//tempDirectory.mkdir();
293
//
294
//f = new File(tempDirectoryPath+"/"+name+System.currentTimeMillis());
295
//if (cancelled)
296
//throw new TaskCancelledException(); 
297
//addDownloadedURL(url, f.getAbsolutePath());
298
//try {
299
//URL url = request.getUrl();
300
//System.out.println(url);
301
//this.status = Status.CONNECTING;
302
//this.begin();
303
//
304
//{
305
//// Retrieve the contents.
306
//int numBytesRead = 0;
307
////System.out.println("File being retrieved. " + this.getUrl().toString());
308
//java.net.URLConnection connection = url.openConnection();
309
//connection.setAllowUserInteraction(true);
310
//java.io.InputStream incoming = connection.getInputStream();
311
//this.contentLength = connection.getContentLength();
312
//this.contentType = connection.getContentType();
313
//
314
//java.io.File destFile = java.io.File.createTempFile("Cq_", makeSuffix(this.contentType));
315
//System.out.println(destFile.getAbsolutePath());
316
////destFile.deleteOnExit(); // It's copied later if it's to be persisted.
317
//this.destination = destFile.getPath();
318
//java.io.FileOutputStream outgoing = new java.io.FileOutputStream(destFile);
319
//
320
//this.status = Status.RETRIEVING;
321
//
322
//byte[] buffer = new byte[4096];
323
//
324
//try {
325
//while (!Thread.currentThread().isInterrupted() && numBytesRead >= 0) {
326
//numBytesRead = incoming.read(buffer);
327
//if (numBytesRead > 0) {
328
//this.bytesRead += numBytesRead;
329
//outgoing.write(buffer, 0, numBytesRead);
330
//this.update();
331
//}
332
//}
333
//} finally {
334
//if (incoming != null)
335
//try {incoming.close();} catch (java.io.IOException e) {}; // TODO: log it maybe
336
//if (outgoing != null)
337
//try {outgoing.close();} catch (java.io.IOException e) {}; // TODO: log it maybe
338
//}
339
//this.status = Status.POSTPROCESSING;
340
//}
341
//} catch (Exception e) {
342
//this.status = Status.ERROR;
343
//this.error = e;
344
//e.printStackTrace();
345
//} finally {
346
//if (Thread.currentThread().isInterrupted())
347
//this.status = Status.INTERRUPTED;
348
//this.update();
349
//this.inThreadEnd();
350
//if (this.status == Status.POSTPROCESSING)
351
//this.status = Status.DONE;
352
//this.end();
353
//}
354