Revision 47820

View differences:

trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.compat/org.gvsig.compat.se/src/main/java/org/gvsig/compat/se/net/downloader/se/SEDownloaderTask.java
1 1
package org.gvsig.compat.se.net.downloader.se;
2 2

  
3
import java.io.BufferedOutputStream;
4
import java.io.DataInputStream;
5
import java.io.DataOutputStream;
6 3
import java.io.File;
7
import java.io.FileOutputStream;
8 4
import java.io.OutputStreamWriter;
9 5
import java.net.HttpURLConnection;
10 6
import java.net.URL;
11
import java.security.KeyManagementException;
12
import java.security.NoSuchAlgorithmException;
13
import java.util.prefs.Preferences;
14
import javax.net.ssl.HttpsURLConnection;
15
import javax.net.ssl.SSLContext;
16
import javax.net.ssl.TrustManager;
17
import javax.net.ssl.X509TrustManager;
18 7
import org.gvsig.compat.se.net.downloader.Downloader;
19
import org.slf4j.Logger;
20
import org.slf4j.LoggerFactory;
21 8

  
22
final class SEDownloaderTask implements Runnable {
9
@SuppressWarnings("UseSpecificCatch")
10
final class SEDownloaderTask 
11
        extends AbstractSEDownloaderTask
12
        implements Runnable {
23 13

  
24
    private URL url = null;
25
    private File dstFile = null;
26
    private Object groupID = null;
27
    private String data = null;
28
    private Downloader downloader = null;
29
    private static Logger LOG = LoggerFactory.getLogger(SEDownloaderTask.class);
30
    private int maxbytes = -1;
31

  
32 14
    public SEDownloaderTask(Downloader downloader, URL url, String data, File dstFile, Object groupID) {
33
        this.url = url;
34
        this.data = data;
35
        this.dstFile = dstFile;
36
        this.groupID = groupID;
37
        this.downloader = downloader;
38
        downloader.setDownloadException(null);
15
        super(downloader, url, data, dstFile, groupID);
39 16
    }
40 17

  
41
    public void setMaxbytes(int maxbytes) {
42
        this.maxbytes = maxbytes;
43
    }
44

  
45
    public int getMaxbytes() {
46
        return maxbytes;
47
    }
48

  
49
    
18
    @Override
50 19
    public void run() {
51
        LOG.info("downloading '" + url.toString() + "' to: " + dstFile.getAbsolutePath());
20
        LOGGER.info("downloading '" + url.toString() + "' to: " + dstFile.getAbsolutePath());
52 21
        if (data != null) {
53
            LOG.info("using POST, request = " + data);
22
            LOGGER.info("using POST, request = " + data);
54 23
        }
55
        // getting timeout from preferences in milliseconds.
56
        Preferences prefs = Preferences.userRoot().node("gvsig.downloader");
57
        // by default 1 minute (60000 milliseconds.
58
        int timeout = prefs.getInt("timeout", 60000);
24
        int timeout = this.getTimeout();
59 25

  
60
        DataOutputStream dos;
61 26
        try {
62
            DataInputStream is;
63 27
            OutputStreamWriter os = null;
64 28
            HttpURLConnection connection = null;
29

  
65 30
            //If the used protocol is HTTPS
66 31
            if (url.getProtocol().equals("https")) {
67 32
                disableHttsValidation();
......
70 35
            connection.setUseCaches(false);
71 36
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (gvSIG) like Gecko");
72 37
            connection.setConnectTimeout(timeout);
38
            
73 39
            //If it uses a HTTP POST
74 40
            if (data != null) {
75 41
                connection.setRequestProperty("SOAPAction", "post");
......
80 46
                os.write(data);
81 47
                os.flush();
82 48
            }
83
            is = new DataInputStream(connection.getInputStream());
49
            download(connection.getInputStream());
84 50

  
85
            dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dstFile)));
86
            byte[] buffer = new byte[1024 * 4];
87

  
88
            long readed = 0;
89
            for (int i = is.read(buffer); !downloader.getCanceled(groupID) && i > 0; i = is.read(buffer)) {
90
                dos.write(buffer, 0, i);
91
                readed += i;
92
                if( maxbytes>0 && readed>maxbytes ) {
93
                    break;
94
                }
95

  
96
            }
97 51
            if (os != null) {
98 52
                os.close();
99 53
            }
100
            dos.close();
101
            is.close();
102
            is = null;
103
            dos = null;
104
            if (downloader.getCanceled(groupID)) {
105
                LOG.info("[RemoteServices] '" + url + "' CANCELED.");
106
                dstFile.delete();
107
                dstFile = null;
108
            } else {
109
                downloader.addDownloadedURL(url, dstFile.getAbsolutePath());
110
            }
54
            
55
            postdownload();
56

  
111 57
        } catch (Exception e) {
112
            LOG.info("Error downloading", e);
113
            downloader.setDownloadException(e);
58
            exception(e);
114 59
        }
115 60
    }
116 61

  
117
    /**
118
     * This method disables the Https certificate validation.
119
     *
120
     * @throws KeyManagementException
121
     * @throws NoSuchAlgorithmException
122
     */
123
    private void disableHttsValidation() throws KeyManagementException, NoSuchAlgorithmException {
124
        // Create a trust manager that does not validate certificate chains
125
        TrustManager[] trustAllCerts = new TrustManager[]{
126
            new X509TrustManager() {
127
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
128
                    return null;
129
                }
130

  
131
                public void checkClientTrusted(
132
                        java.security.cert.X509Certificate[] certs, String authType) {
133
                }
134

  
135
                public void checkServerTrusted(
136
                        java.security.cert.X509Certificate[] certs, String authType) {
137
                }
138
            }
139
        };
140

  
141
        // Install the all-trusting trust manager
142
        SSLContext sc = SSLContext.getInstance("SSL");
143
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
144
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
145
    }
146 62
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.compat/org.gvsig.compat.se/src/main/java/org/gvsig/compat/se/net/downloader/se/AbstractSEDownloaderTask.java
1
package org.gvsig.compat.se.net.downloader.se;
2

  
3
import java.io.BufferedOutputStream;
4
import java.io.DataInputStream;
5
import java.io.DataOutputStream;
6
import java.io.File;
7
import java.io.FileOutputStream;
8
import java.io.IOException;
9
import java.io.InputStream;
10
import java.io.OutputStreamWriter;
11
import java.net.HttpURLConnection;
12
import java.net.URL;
13
import java.security.KeyManagementException;
14
import java.security.NoSuchAlgorithmException;
15
import java.util.prefs.Preferences;
16
import javax.net.ssl.HttpsURLConnection;
17
import javax.net.ssl.SSLContext;
18
import javax.net.ssl.TrustManager;
19
import javax.net.ssl.X509TrustManager;
20
import org.apache.commons.io.IOUtils;
21
import org.gvsig.compat.se.net.downloader.Downloader;
22
import org.slf4j.Logger;
23
import org.slf4j.LoggerFactory;
24

  
25
@SuppressWarnings("UseSpecificCatch")
26
public abstract class AbstractSEDownloaderTask implements Runnable {
27

  
28
    protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractSEDownloaderTask.class);
29

  
30
    protected final URL url;
31
    protected final File dstFile;
32
    protected final Object groupID;
33
    protected final String data;
34
    protected final Downloader downloader;
35
    
36
    private int maxbytes;
37

  
38
    public AbstractSEDownloaderTask(Downloader downloader, URL url, String data, File dstFile, Object groupID) {
39
        this.url = url;
40
        this.data = data;
41
        this.dstFile = dstFile;
42
        this.groupID = groupID;
43
        this.downloader = downloader;
44
        this.maxbytes = -1;
45
        downloader.setDownloadException(null);
46
    }
47

  
48
    public void setMaxbytes(int maxbytes) {
49
        this.maxbytes = maxbytes;
50
    }
51

  
52
    public int getMaxbytes() {
53
        return maxbytes;
54
    }
55

  
56
    protected void download(InputStream is) throws IOException {
57
        DataOutputStream dos = null;
58
        DataInputStream dis = null;
59
        FileOutputStream fos = null;
60
        BufferedOutputStream bos = null;
61
        try {
62
            fos = new FileOutputStream(dstFile);
63
            if( is != null ) {
64
                bos = new BufferedOutputStream(fos);
65
                dos = new DataOutputStream(bos);
66

  
67
                dis = new DataInputStream(is);
68
                byte[] buffer = new byte[1024 * 4];
69
                long readed = 0;
70
                for (int i = dis.read(buffer); !isCanceled() && i > 0; i = dis.read(buffer)) {
71
                    dos.write(buffer, 0, i);
72
                    readed += i;
73
                    if( maxbytes>0 && readed>maxbytes ) {
74
                        break;
75
                    }
76
                }
77
            }
78
        } finally {
79
            IOUtils.closeQuietly(dos);
80
            IOUtils.closeQuietly(bos);
81
            IOUtils.closeQuietly(fos);
82
            IOUtils.closeQuietly(dis);
83
        }
84
    }
85
    
86
    protected boolean isCanceled() {
87
        return downloader.getCanceled(groupID);
88
    }
89
    
90
    protected int getTimeout() {
91
        // getting timeout from preferences in milliseconds.
92
        Preferences prefs = Preferences.userRoot().node("gvsig.downloader");
93
        // by default 1 minute (60000 milliseconds.
94
        int timeout = prefs.getInt("timeout", 60000);
95
        
96
        return timeout;
97
    }
98

  
99
    protected void postdownload() {
100
        if (isCanceled()) {
101
            LOGGER.info("[Downloader] '" + url + "' CANCELED.");
102
            dstFile.delete();
103
//            dstFile = null;
104
        } else {
105
            downloader.addDownloadedURL(url, dstFile.getAbsolutePath());
106
        }
107
    }
108

  
109
    protected void exception(Exception e) {
110
        LOGGER.info("Error downloading", e);
111
        downloader.setDownloadException(e);
112
    }
113
    
114
    /**
115
     * This method disables the Https certificate validation.
116
     *
117
     * @throws KeyManagementException
118
     * @throws NoSuchAlgorithmException
119
     */
120
    protected void disableHttsValidation() throws KeyManagementException, NoSuchAlgorithmException {
121
        // Create a trust manager that does not validate certificate chains
122
        TrustManager[] trustAllCerts = new TrustManager[]{
123
            new X509TrustManager() {
124
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
125
                    return null;
126
                }
127

  
128
                public void checkClientTrusted(
129
                        java.security.cert.X509Certificate[] certs, String authType) {
130
                }
131

  
132
                public void checkServerTrusted(
133
                        java.security.cert.X509Certificate[] certs, String authType) {
134
                }
135
            }
136
        };
137

  
138
        // Install the all-trusting trust manager
139
        SSLContext sc = SSLContext.getInstance("SSL");
140
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
141
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
142
    }
143
}

Also available in: Unified diff