Statistics
| Revision:

gvsig-raster / org.gvsig.raster.wmts / trunk / org.gvsig.raster.wmts / org.gvsig.raster.wmts.ogc / org.gvsig.raster.wmts.ogc.impl / src / main / java / org / gvsig / raster / wmts / ogc / impl / request / WMTSRequest.java @ 1811

History | View | Annotate | Download (11.3 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
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 2
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
 */
22

    
23
/*
24
 * AUTHORS (In addition to CIT):
25
 * 2009 Iver T.I.  {{Task}}
26
 */
27

    
28
/**
29
 * This class sends a WMS request and returns the
30
 * reply in a local File. It tries if the server
31
 * supports both HTTP Get and Post requests.
32
 * @author Jorge Piera LLodr? (jorge.piera@iver.es)
33
 */
34
package org.gvsig.raster.wmts.ogc.impl.request;
35

    
36
import java.io.BufferedOutputStream;
37
import java.io.DataInputStream;
38
import java.io.DataOutputStream;
39
import java.io.File;
40
import java.io.FileOutputStream;
41
import java.io.IOException;
42
import java.net.ConnectException;
43
import java.net.HttpURLConnection;
44
import java.net.MalformedURLException;
45
import java.net.SocketTimeoutException;
46
import java.net.URL;
47
import java.net.UnknownHostException;
48
import java.security.KeyManagementException;
49
import java.security.NoSuchAlgorithmException;
50
import java.util.prefs.Preferences;
51

    
52
import javax.net.ssl.HttpsURLConnection;
53
import javax.net.ssl.SSLContext;
54
import javax.net.ssl.TrustManager;
55
import javax.net.ssl.X509TrustManager;
56

    
57
import org.gvsig.compat.CompatLocator;
58
import org.gvsig.compat.lang.StringUtils;
59
import org.gvsig.compat.net.ICancellable;
60
import org.gvsig.raster.wmts.ogc.impl.Tags;
61
import org.gvsig.raster.wmts.ogc.impl.Utilities;
62
import org.gvsig.raster.wmts.ogc.impl.base.WMTSProtocolHandler;
63
import org.gvsig.raster.wmts.ogc.impl.base.WMTSStatusImpl;
64

    
65
/**
66
 * Base class for a WMTS request
67
 * @author Nacho Brodin (nachobrodin@gmail.com)
68
 */
69
public abstract class WMTSRequest {
70
        protected static final StringUtils stringUtils = CompatLocator.getStringUtils();
71
        protected WMTSStatusImpl status = null;
72
        protected WMTSProtocolHandler protocolHandler = null;
73
        protected boolean isDeleted = false;
74
        protected static final String XMLTAG_STARTCHARACTER = "<";
75
        protected static final String XMLTAG_FINISHCHARACTER = "</";
76
        protected static final String XMLTAG_ENDCHARACTER = ">";
77
        
78
        public WMTSRequest(WMTSStatusImpl status,
79
                        WMTSProtocolHandler protocolHandler) {
80
                this.status = status;
81
                this.protocolHandler = protocolHandler;
82
        }
83
        
84
        protected abstract String getHttpGetRequest(String onlineResource);
85

    
86
        protected abstract String getHttpPostRequest(String onlineResource);
87

    
88
        protected abstract String getTempFilePrefix();
89

    
90
        protected abstract String getOperationName();
91
        
92
        /**
93
         * @return the URL used in the HTTP get operation
94
         * @throws MalformedURLException
95
         */
96
        public URL getURL() throws MalformedURLException{
97
                String onlineResource = protocolHandler.getServiceInformation().getOnlineResource(getOperationName(), Tags.PROTOCOL_GET);
98
                if (onlineResource != null){
99
                        String symbol = getSymbol(onlineResource);
100
                        onlineResource = onlineResource + symbol;
101
                        return new URL(getHttpGetRequest(onlineResource));
102
                }
103
                
104
                //If the online resource doesn't exist, it tries with the server URL and GET
105
                onlineResource = protocolHandler.getHost();
106
                String symbol = getSymbol(onlineResource);
107
                onlineResource = onlineResource + symbol;
108
                return new URL(getHttpGetRequest(onlineResource));
109
        }
110

    
111
        protected String getSchemaLocation() {
112
                return null;
113
        }
114
        
115
        /**
116
     * Gets the part of the OGC request that share GetMap and GetFeatureInfo
117
     * @return String request
118
     */
119
        protected String getPartialQuery(WMTSStatusImpl status) {
120
        StringBuffer req = new StringBuffer();
121
        req.append("Layer=" + status.getLayer())
122
        .append("&Style=" + status.getStyle())
123
        .append("&Format=" + status.getFormat())
124
        .append("&TileMatrixSet=" + status.getTileMatrixSet())
125
        .append("&TileMatrix=" + status.getTileMatrix())
126
        .append("&TileRow=" + status. getTileRow())
127
        .append("&TileCol=" + status.getTileCol());
128
        return req.toString();
129
    }
130
        
131
        /**
132
         * Send a request to the server.
133
         * @return
134
         * The server reply
135
         * @throws IOException 
136
         * @throws UnknownHostException 
137
         * @throws ConnectException 
138
         */
139
        public void sendRequest(ICancellable cancel, File file) throws ConnectException, UnknownHostException, IOException {
140
                String onlineResource = protocolHandler.getHost();
141
                String symbol = getSymbol(onlineResource);
142
                onlineResource = onlineResource + symbol;
143
                URL url = new URL(stringUtils.replaceAll(getHttpGetRequest(onlineResource), " ", "%20"));
144
                //System.out.println(url.toString());
145
                downloadFile(url, file, cancel);        
146
                
147
                //downloadFile(new URL(protocolHandler.getHost()), getHttpGetRequest(onlineResource), file, cancel);        
148
        }
149
        
150
        /**
151
         * Send a request to the server.
152
         * @return
153
         * The server reply
154
         * @throws IOException 
155
         * @throws UnknownHostException 
156
         * @throws ConnectException 
157
         */
158
        public File sendRequest(ICancellable cancel) throws ConnectException, UnknownHostException, IOException{
159
                //if the status is null is because is a GetCapabilities operation
160
                if (status != null){
161
                        if (status.getProtocol() != Tags.PROTOCOL_UNDEFINED){
162
                                if (status.getProtocol() == Tags.PROTOCOL_GET){
163
                                        String onlineResource = protocolHandler.getHost();
164
                                        String symbol = getSymbol(onlineResource);
165
                                        onlineResource = onlineResource + symbol;
166
                                        return sendHttpGetRequest(onlineResource, cancel);
167
                                }else{
168
                                        String onlineResource = protocolHandler.getHost();
169
                                        return sendHttpPostRequest(onlineResource);
170
                                }
171
                        }
172
                }
173

    
174
                //if exists an online resource for the GET operation
175
                String onlineResource = protocolHandler.getServiceInformation().getOnlineResource(getOperationName(), Tags.PROTOCOL_GET);
176
                if (onlineResource != null){
177
                        String symbol = getSymbol(onlineResource);
178
                        onlineResource = onlineResource + symbol;
179
                        return sendHttpGetRequest(onlineResource, cancel);
180
                }
181
                //if exists an online resource for the POST operation
182
                onlineResource =  protocolHandler.getServiceInformation().getOnlineResource(getOperationName(), Tags.PROTOCOL_POST);
183
                if (onlineResource != null){
184
                        return sendHttpPostRequest(onlineResource);
185
                }
186
                //If the online resource doesn't exist, it tries with the server URL and GET
187
                onlineResource = protocolHandler.getHost();
188
                String symbol = getSymbol(onlineResource);
189
                onlineResource = onlineResource + symbol;
190
                return sendHttpGetRequest(onlineResource, cancel);
191
        }
192
        
193
        /**
194
         * Send a Http request using the get protocol
195
         * @param onlineResource
196
         * @return
197
         * @throws ConnectException
198
         * @throws UnknownHostException
199
         * @throws IOException
200
         */
201
        private File sendHttpGetRequest(String onlineResource, ICancellable cancel) throws ConnectException, UnknownHostException, IOException{
202
                URL url = new URL(stringUtils.replaceAll(getHttpGetRequest(onlineResource), " ", "%20"));
203
                if (isDeleted()){
204
                        Utilities.removeURL(url);
205
                }
206
                return Utilities.downloadFile(url, getTempFilePrefix(), cancel);                
207
        }
208

    
209
        /**
210
         * Send a Http request using the post protocol
211
         * @param onlineResource
212
         * @return
213
         * @throws ConnectException
214
         * @throws UnknownHostException
215
         * @throws IOException
216
         */
217
        private File sendHttpPostRequest(String onlineResource) throws ConnectException, UnknownHostException, IOException{
218
                URL url = new URL(onlineResource);
219
                String data = getHttpPostRequest(onlineResource);
220
                if (isDeleted()){
221
                        Utilities.removeURL(url+data);
222
                }
223
                return Utilities.downloadFile(url, data, getTempFilePrefix(), null);                
224
        }
225
        
226
        
227
        public void cancelDownload() {
228
                if(connection != null) {
229
                        connection.disconnect();
230
                        connection = null;        
231
                }
232
                if(is != null) {
233
                        try {
234
                                is.close();
235
                        } catch (IOException e) {
236
                        }
237
                }
238
                if(dos != null) {
239
                        try {
240
                                dos.close();
241
                        } catch (IOException e) {
242
                        }
243
                }
244
        }
245

    
246
        HttpURLConnection connection = null;
247
        DataOutputStream dos = null;
248
        DataInputStream is = null;
249
        
250
        public void downloadFile(URL url, File dstFile, ICancellable cancel) throws IOException {
251
                if(cancel != null && cancel.isCanceled())
252
                        throw new IOException();
253
                
254
                Preferences prefs = Preferences.userRoot().node( "gvsig.downloader" );
255
                // by default 1 minute (60000 milliseconds.
256
                int timeout = prefs.getInt("timeout", 20000);
257

    
258
                //If the used protocol is HTTPS
259
                if (url.getProtocol().equals("https")) {
260
                        try {
261
                                disableHttsValidation();
262
                        } catch (KeyManagementException e) {
263
                                throw new IOException();
264
                        } catch (NoSuchAlgorithmException e) {
265
                                throw new IOException();
266
                        }
267
                }
268
        
269

    
270
                
271
                try {
272
                        connection = (HttpURLConnection)url.openConnection();
273
                        connection.setConnectTimeout(timeout);
274
                        connection.setReadTimeout(timeout);
275
                        is = new DataInputStream(connection.getInputStream());
276

    
277
                        dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dstFile)));
278
                        byte[] buffer = new byte[4096];
279

    
280
                        int i = -1;
281

    
282
                        if(cancel != null && cancel.isCanceled()) {
283
                                throw new IOException();
284
                        }
285

    
286
                        while((i = is.read(buffer)) > 0) {
287
                                if(cancel != null && cancel.isCanceled()) {
288
                                        throw new IOException();
289
                                }
290
                                dos.write(buffer, 0, i);
291
                        }
292
                } catch (SocketTimeoutException e) {
293
                        throw new IOException();
294
                } finally {
295
                        if(is != null)
296
                                is.close();
297
                        if(dos != null)
298
                                dos.close();
299
                        if(connection != null)
300
                                connection.disconnect();
301
                }
302
        }
303

    
304
        /**
305
         * This method disables the Https certificate validation.
306
         * @throws KeyManagementException
307
         * @throws NoSuchAlgorithmException
308
         */
309
        private void disableHttsValidation() throws KeyManagementException, NoSuchAlgorithmException{
310
                // Create a trust manager that does not validate certificate chains
311
                TrustManager[] trustAllCerts = new TrustManager[] {
312
                                new X509TrustManager() {
313
                                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
314
                                                return null;
315
                                        }
316
                                        public void checkClientTrusted(
317
                                                        java.security.cert.X509Certificate[] certs, String authType) {
318
                                        }
319
                                        public void checkServerTrusted(
320
                                                        java.security.cert.X509Certificate[] certs, String authType) {
321
                                        }
322
                                }
323
                };
324

    
325
                // Install the all-trusting trust manager
326
                SSLContext sc = SSLContext.getInstance("SSL");
327
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
328
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
329
        }
330
        
331
        /**
332
         * Just for not repeat code. Gets the correct separator according 
333
         * to the server URL
334
         * @param h
335
         * @return
336
         */
337
        protected static String getSymbol(String h) {
338
                String symbol;
339
                if (h.indexOf("?")==-1) 
340
                        symbol = "?";
341
                else if (h.indexOf("?")!=h.length()-1)
342
                        symbol = "&";
343
                else
344
                        symbol = "";
345
                return symbol;
346
        }
347

    
348
        public boolean isDeleted() {
349
                return isDeleted;
350
        }
351

    
352
        public void setDeleted(boolean isDeleted) {
353
                this.isDeleted = isDeleted;
354
        }
355
        
356
        protected String createXMLStartTag(String tagName){
357
            return XMLTAG_STARTCHARACTER + tagName + XMLTAG_ENDCHARACTER;
358
        }
359
        
360
   protected String createXMLEndtTag(String tagName){
361
        return XMLTAG_FINISHCHARACTER + tagName + XMLTAG_ENDCHARACTER;
362
    }
363
        
364
}