Revision 1163

View differences:

org.gvsig.raster.wcs/tags/buildNumber_20/org.gvsig.raster.wcs/org.gvsig.raster.wcs.io/src/main/java/org/gvsig/raster/wcs/io/WCSServerExplorer.java
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
package org.gvsig.raster.wcs.io;
29

  
30
import java.awt.geom.Point2D;
31
import java.io.IOException;
32
import java.net.URL;
33
import java.util.Hashtable;
34
import java.util.List;
35

  
36
import org.gvsig.compat.net.ICancellable;
37
import org.gvsig.fmap.dal.DALLocator;
38
import org.gvsig.fmap.dal.DataManager;
39
import org.gvsig.fmap.dal.DataServerExplorerParameters;
40
import org.gvsig.fmap.dal.DataStoreParameters;
41
import org.gvsig.fmap.dal.NewDataStoreParameters;
42
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
43
import org.gvsig.fmap.dal.exception.DataException;
44
import org.gvsig.fmap.dal.exception.InitializeException;
45
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
46
import org.gvsig.fmap.dal.spi.DataServerExplorerProvider;
47
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
48

  
49
/**
50
 * Explorer for a WCS server
51
 * @author Nacho Brodin (nachobrodin@gmail.com)
52
 */
53
public class WCSServerExplorer implements DataServerExplorerProvider {
54
	public static final String          NAME                     = "WCSRemoteServerExplorer";
55
	private WCSConnector                connector                = null;
56
	private WCSServerExplorerParameters parameters               = null;
57
	
58
	public WCSServerExplorer(
59
			WCSServerExplorerParameters parameters,
60
			DataServerExplorerProviderServices services)
61
			throws InitializeException {
62
		this.parameters = parameters;
63
	}
64
	
65
	/**
66
	 * Gets the provider's name
67
	 * @return
68
	 */
69
	public String getDataStoreProviderName() {
70
		return WCSProvider.NAME;
71
	}
72
	
73
	/*
74
	 * (non-Javadoc)
75
	 * @see org.gvsig.fmap.dal.coverage.store.remote.RemoteServerExplorerProvider#getDescription()
76
	 */
77
	public String getDescription() {
78
		return WCSProvider.DESCRIPTION;
79
	}
80
	
81
	public DataStoreParameters getStoreParameters() {
82
		DataManager manager = DALLocator.getDataManager();
83
		WCSDataParametersImpl params = null;
84
		try {
85
			params = (WCSDataParametersImpl) manager.createStoreParameters(this.getDataStoreProviderName());
86

  
87
			/*if(WCSProvider.TILED) {
88
				TileDataParameters tileParams = (TileDataParameters) manager.createStoreParameters("Tile Store");
89
				tileParams.setDataParameters(params);
90
				return tileParams;
91
			} */
92
			
93
		} catch (InitializeException e) {
94
			e.printStackTrace();
95
		} catch (ProviderNotRegisteredException e) {
96
			e.printStackTrace();
97
		}
98
		params.setURI(parameters.getHost());
99
		return params;
100
	}
101

  
102
	public boolean add(String provider, NewDataStoreParameters parameters,
103
			boolean overwrite) throws DataException {
104
		return false;
105
	}
106

  
107
	public boolean canAdd() {
108
		return false;
109
	}
110

  
111
	public boolean canAdd(String storeName) throws DataException {
112
		return false;
113
	}
114

  
115
	public NewDataStoreParameters getAddParameters(String storeName)
116
			throws DataException {
117
		return null;
118
	}
119

  
120
	@SuppressWarnings("unchecked")
121
	public List getDataStoreProviderNames() {
122
		return null;
123
	}
124

  
125

  
126
	/*
127
	 * (non-Javadoc)
128
	 * @see org.gvsig.fmap.dal.DataServerExplorer#getParameters()
129
	 */
130
	public DataServerExplorerParameters getParameters() {
131
		return parameters;
132
	}
133

  
134
	@SuppressWarnings("unchecked")
135
	public List list() throws DataException {
136
		return null;
137
	}
138

  
139
	@SuppressWarnings("unchecked")
140
	public List list(int mode) throws DataException {
141
		return null;
142
	}
143

  
144
	public void remove(DataStoreParameters parameters) throws DataException {
145
		
146
	}
147

  
148
	public void dispose() {
149
		
150
	}
151

  
152
	public String getProviderName() {
153
		return null;
154
	}
155
	
156
	/**
157
	 * Gets the online resources
158
	 * @return
159
	 */
160
	@SuppressWarnings("unchecked")
161
	public Hashtable getOnlineResources() {
162
		/*if(connector != null) {
163
			return connector.getOnlineResources();
164
		}*/
165
		return null;
166
	}
167
	
168
	//**********************************************
169
	//Connector
170
	//**********************************************
171

  
172
	/**
173
	 * Connects to the server and throws a getCapabilities. This loads 
174
	 * the basic information to make requests.
175
	 * @throws RemoteServiceException 
176
	 */
177
	public void connect(ICancellable cancellable) throws RemoteServiceException {
178
		URL url = null;
179
		boolean override = false;
180
		
181
		try {
182
			url = new URL(parameters.getHost());
183
		} catch (Exception e) {
184
			throw new RemoteServiceException("Malformed URL",e);
185
		}
186
        try {
187
        	connector = WCSProvider.getConnectorFromURL(url);
188
        	if (!connector.connect(override, cancellable))
189
        		throw new RemoteServiceException("Error connecting");
190
        } catch (IOException e) {
191
			throw new RemoteServiceException("Error connecting",e);
192
		}
193
		
194
	}
195

  
196
	/**
197
	 * Returns true if this provider is connected to the server
198
	 * @return
199
	 */
200
	public boolean isConnected() {
201
		if(connector != null)
202
			return true;
203
		return false;
204
	}
205

  
206
	/**
207
	 * Gets the description of this service
208
	 * @return
209
	 */
210
	public String getAbstract() {
211
		if(connector != null)
212
			return connector.getDescription();
213
		return null;
214
	}
215

  
216
	/**
217
	 * Gets the server title
218
	 * @return
219
	 */
220
	public String getServerType() {
221
		if (getVersion() == null) 
222
			return "WCS";
223
        return "WCS "+ getVersion();
224
	}
225

  
226
	/**
227
	 * Gets the protocol supported by the server
228
	 * @return
229
	 */
230
	public String getVersion() {
231
		if(connector != null) {
232
			return (connector.getVersion() == null) ? "" : connector.getVersion();
233
		}
234
		return null;
235
	}
236

  
237
	/**
238
	 * Gets the host URI
239
	 * @return
240
	 */
241
	public String getHost() {
242
		return parameters.getHost();
243
	}
244
	
245
	/**
246
	 * Gets the title
247
	 * @return
248
	 */
249
	public String getTitle() {
250
		return null;
251
	}
252

  
253
	public DataServerExplorerProviderServices getServerExplorerProviderServices() {
254
		// TODO Auto-generated method stub
255
		return null;
256
	}
257

  
258
	/*
259
	 * (non-Javadoc)
260
	 * @see org.gvsig.fmap.dal.coverage.explorer.WCSServerExplorer#getMaxResolution(java.lang.String)
261
	 */
262
	public Point2D getMaxResolution(String layerName) {
263
		return connector.getMaxResolution(layerName);
264
	}
265

  
266
	/**
267
	 * Gets the coverage list
268
	 * @return
269
	 */
270
	public WCSLayerNode[] getCoverageList() {
271
		return connector.getLayerList();
272
	}
273
	
274
	/**
275
	 * Gets a layer searching by its name 
276
	 * @return
277
	 */
278
	public WCSLayerNode getCoverageByName(String name) {
279
		WCSLayerNode[] list = getCoverageList();
280
		for (int i = 0; i < list.length; i++) {
281
			if(list[i].getName().compareTo(name) == 0)
282
				return list[i];
283
		}
284
		return null;
285
	}
286
}
0 287

  
org.gvsig.raster.wcs/tags/buildNumber_20/org.gvsig.raster.wcs/org.gvsig.raster.wcs.io/src/main/java/org/gvsig/raster/wcs/io/WCSConnector.java
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
package org.gvsig.raster.wcs.io;
23

  
24
import java.awt.geom.Point2D;
25
import java.awt.geom.Rectangle2D;
26
import java.io.BufferedOutputStream;
27
import java.io.DataInputStream;
28
import java.io.DataOutputStream;
29
import java.io.File;
30
import java.io.FileOutputStream;
31
import java.io.IOException;
32
import java.io.OutputStreamWriter;
33
import java.net.ConnectException;
34
import java.net.HttpURLConnection;
35
import java.net.URL;
36
import java.security.KeyManagementException;
37
import java.security.NoSuchAlgorithmException;
38
import java.util.ArrayList;
39
import java.util.Hashtable;
40
import java.util.Iterator;
41
import java.util.Set;
42
import java.util.prefs.Preferences;
43

  
44
import javax.net.ssl.HttpsURLConnection;
45
import javax.net.ssl.SSLContext;
46
import javax.net.ssl.TrustManager;
47
import javax.net.ssl.X509TrustManager;
48

  
49
import org.gvsig.compat.net.ICancellable;
50
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
51
import org.gvsig.remoteclient.exceptions.ServerErrorException;
52
import org.gvsig.remoteclient.exceptions.WCSException;
53
import org.gvsig.remoteclient.utils.BoundaryBox;
54
import org.gvsig.remoteclient.wcs.WCSClient;
55
import org.gvsig.remoteclient.wcs.WCSCoverage;
56
import org.gvsig.remoteclient.wcs.WCSStatus;
57
import org.gvsig.remoteclient.wcs.WCSCoverage.AxisDescription;
58
import org.gvsig.remoteclient.wcs.WCSCoverage.RectifiedGrid;
59

  
60
/**
61
 * Connector between a WCS data provider and a WCSClient. 
62
 *
63
 * @author Nacho Brodin (nachobrodin@gmail.com)
64
 */
65
@SuppressWarnings("unchecked")
66
public class WCSConnector  {
67
	private WCSClient                     client;
68
	private Hashtable                     coverages;
69
    private WCSLayerNode[]                layerList;
70
    
71
    public WCSConnector(URL url) throws ConnectException, IOException {
72
    	client = new WCSClient(url.toString());
73
    }
74

  
75
	/**
76
	 * Returns the string "WCSDriver", which is the driver's name.
77
	 *
78
	 * Devuelve "WCSDriver", el nombre del driver.
79
	 * @return String
80
	 */
81
	public String getName() { 
82
		return "WCSDriver"; 
83
	}
84

  
85
	/**
86
	 * Sets the server that we want to connect to.
87
	 *
88
	 * Establece el servidor al que se quiere conectar.
89
	 *
90
	 * @param host
91
	 * @throws IOException
92
	 */
93
	public void setHost(String host) throws IOException{
94
		client = new WCSClient(host);
95
	}
96

  
97

  
98
	/**
99
	 * Returns a human-readable string containing the server's name.
100
	 *
101
	 * Devuelve el nombre legible del servidor devuelto por ?ste.
102
	 *
103
	 * @return String
104
	 */
105
	public String getLabel() {
106
		return client.getServiceTitle();
107
	}
108

  
109
	/**
110
	 * Returns a string containing the server's WCS version number.
111
	 *
112
	 * Devuelve el n?mero de versi?n WCS del servidor
113
	 *
114
	 * @return String
115
	 */
116
	public String getVersion(){
117
		return client.getVersion();
118
	}
119

  
120
	/**
121
	 * <p>
122
	 * Returns name and description of the server. It is supposed to be used
123
	 * as the source of the abstract field in your application's interface.
124
	 * </p>
125
	 * <p>
126
	 * Devuelve nombre y descripci?n (abstract) del servidor.
127
	 * </p>
128
	 * @return String
129
	 */
130
	public String getDescription(){
131
		return client.getDescription();
132
	}
133

  
134
	/**
135
	 * Returns the layer descriptor for a given coverage name.
136
	 * @param layerName
137
	 * @return WCSLayer
138
	 */
139
	public WCSLayerNode getLayer(String layerName) {
140
		getLayerList();
141
		return (WCSLayerNode) coverages.get(layerName);
142
	}
143

  
144
	/**
145
	 * Returns an array of WCSLayer's with the descriptors of all coverages
146
	 * @return WCSLayer[]
147
	 */
148
	public WCSLayerNode[] getLayerList() {
149
		if (coverages == null || coverages.isEmpty()) {
150
			// the WCSLayer collection will be built
151
			coverages = new Hashtable();
152
			Hashtable wcsCoverages  = client.getCoverageList();
153
			int sz = wcsCoverages.size();
154

  
155
			// Create an array with the WCSCoverages
156
			WCSCoverage[] coverageList = new WCSCoverage[sz];
157
			Iterator it = wcsCoverages.keySet().iterator();
158
			int i = 0;
159
			while (it.hasNext()) {
160
				coverageList[i] = (WCSCoverage) wcsCoverages.get(it.next());
161
				i++;
162
			}
163

  
164
			// Create a WCSLayer array from the previous WCSCoverage array
165
			layerList = new WCSLayerNode[sz];
166
			for (int j = 0; j < layerList.length; j++) {
167
				WCSLayerNode lyr = new WCSLayerNode();
168
				WCSCoverage cov = coverageList[j];
169
				// name
170
				lyr.setName(cov.getName());
171

  
172
				// title
173
				lyr.setTitle(cov.getTitle());
174

  
175
				// description
176
				lyr.setDescription(cov.getAbstract());
177

  
178
				// srs
179
				lyr.addAllSrs(cov.getAllSrs());
180

  
181
				// native srs
182
				lyr.setNativeSRS(cov.getNativeSRS());
183

  
184
				// extents
185
				Set k = cov.getBBoxes().keySet();
186
				if (!k.isEmpty()) {
187
					it = k.iterator();
188
					while (it.hasNext()) {
189
						String srs = (String) it.next();
190
						BoundaryBox bBox = cov.getBbox(srs);
191
						Rectangle2D r = new Rectangle2D.Double(
192
								bBox.getXmin(),
193
								bBox.getYmin(),
194
								bBox.getXmax() - bBox.getXmin(),
195
								bBox.getYmax() - bBox.getYmin()
196
						);
197
						lyr.addExtent(srs, r);
198
					}
199
				}
200

  
201
				// formats
202
				lyr.setFormats(cov.getFormats());
203

  
204
				// time positions
205
				lyr.setTimePositions(cov.getTimePositions());
206
				
207
				RectifiedGrid rf = cov.getRectifiedGrid();
208
				int w = rf.getHighGridEnvelopLimits()[0][0] - rf.getLowGridEnvelopLimits()[0][0];
209
				int h = rf.getHighGridEnvelopLimits()[0][1] - rf.getLowGridEnvelopLimits()[0][1]; 
210
				
211
				lyr.setWidth(w);
212
				lyr.setHeight(h);
213
				
214
				// max res
215
				lyr.setMaxRes(new Point2D.Double(cov.getResX(), cov.getResY()));
216

  
217
				// interpolations
218
				lyr.setInterpolationMethods(cov.getInterpolationMethods());
219

  
220
				// parameters
221
				k = cov.axisPool.keySet();
222
				if (!k.isEmpty()) {
223
					it = k.iterator();
224
					while (it.hasNext()) {
225
						AxisDescription ad = (AxisDescription) cov.axisPool.get(it.next());
226
						FMapWCSParameter p = new FMapWCSParameter();
227
						p.setName(ad.getName());
228
						p.setLabel(ad.getLabel());
229
						p.setType(ad.getInterval() == null ? FMapWCSParameter.VALUE_LIST : FMapWCSParameter.INTERVAL);
230
						if (p.getType() == FMapWCSParameter.VALUE_LIST) {
231
							p.setValueList(ad.getSingleValues());
232
						} /*else {
233
							p.setInterval(ad.getInterval());
234
						}*/
235
						lyr.addParameter(p);
236
					}
237
				}
238
				layerList[j] = lyr;
239
				coverages.put(lyr.getName(), lyr);
240
			}
241
		}
242
		return layerList;
243
	}
244

  
245
	/**
246
	 * Establishes the connection to the WCS server. Connecting to a WCS is
247
	 * an abstraction.<br>
248
	 * <p>
249
	 * Actually, it sends a GetCapabilities and a general DescribeCoverage
250
	 * request (not a coverage-specific DescribeCoverage request) to read the
251
	 * necessary data for building further GetCoverage requests.
252
	 * </p>
253
	 * @param override
254
	 * @throws IOException.
255
	 */
256
	public boolean connect(boolean override, ICancellable cancel)
257
			throws IOException {
258
		coverages = null;
259
		setHost(client.getHost());
260
		return client.connect(override, cancel);
261
	}
262

  
263
	/**
264
	 * No close operation is needed since WCS service it is a non-session based
265
	 * protocol. So, this does nothing and you can omit it.<br>
266
	 */
267
	public void close() {
268
//		connected = false;
269
	}
270

  
271
	/**
272
	 * Returns the label of an specific coverage given by the coverage name
273
	 * @param coverage name (string)
274
	 * @return string
275
	 */
276
	public String getLabel(String coverageName) {
277
		return client.getLabel(coverageName);
278
	}
279

  
280
	/**
281
	 * Returns the coverage's MAX extent from the server.
282
	 * @return Rectangle2D
283
	 * @throws IOException
284
	 */
285
	public Rectangle2D getFullExtent(String coverageName, String srs)
286
			throws IOException {
287
		return client.getExtent(coverageName, srs);
288
	}
289

  
290
	/**
291
	 * Returns the max resolution of a specific coverage given by the coverage's name.
292
	 * @param coverage name (string)
293
	 * @return double
294
	 */
295
	public Point2D getMaxResolution(String coverageName) {
296
		if (coverages.containsKey(coverageName)) {
297
			return ((WCSLayerNode) coverages.get(coverageName)).getMaxRes();
298
		}
299
		return null;
300
	}
301
	
302
	/**
303
	 * Gets the maximum width in pixels of this coverage
304
	 * @param coverageName
305
	 * @return
306
	 */
307
	public int getWidth(String coverageName) {
308
		if (coverages.containsKey(coverageName)) {
309
			return ((WCSLayerNode) coverages.get(coverageName)).getWidth();
310
		}
311
		return 0;
312
	}
313

  
314
	/**
315
	 * Gets the maximum height in pixels of this coverage
316
	 * @param coverageName
317
	 * @return
318
	 */
319
	public int getHeight(String coverageName) {
320
		if (coverages.containsKey(coverageName)) {
321
			return ((WCSLayerNode) coverages.get(coverageName)).getHeight();
322
		}
323
		return 0;
324
	}
325

  
326
	/**
327
	 * Returns an ArrayList containing a set of Strings with the coverage's SRSs.
328
	 * @param coverage name (string)
329
	 * @return ArrayList
330
	 */
331
	public ArrayList getSRSs(String coverageName) {
332
		if (coverages.containsKey(coverageName)) {
333
			return ((WCSLayerNode) coverages.get(coverageName)).getSRSs();
334
		}
335
		return null;
336
	}
337

  
338
	/**
339
	 * Returns a String containing a description of an specific coverage.
340
	 * @param coverage name (string)
341
	 * @return string
342
	 */
343
	public String getCoverageDescription(String coverageName) {
344
		if (coverages.containsKey(coverageName)) {
345
			return ((WCSLayerNode) coverages.get(coverageName)).getDescription();
346
		}
347
		return null;
348
	}
349

  
350
	/**
351
	 * Returns an ArrayList containing strings for the time positions of an
352
	 * specific coverage given by the coverage's name.
353
	 * @param coverage name (string)
354
	 * @return ArrayList
355
	 */
356
	public ArrayList getTimes(String coverageName) {
357
		if (coverages.containsKey(coverageName)) {
358
			return ((WCSLayerNode) coverages.get(coverageName)).getTimePositions();
359
		}
360
		return null;
361
	}
362

  
363
	/**
364
	 * Sends a GetCoverage request to the client.
365
	 * @param status
366
	 * @return
367
	 * @throws WCSException
368
	 */
369
	public File getCoverage(WCSStatus status, ICancellable cancel) throws RemoteServiceException {
370
		try {
371
			return client.getCoverage(status, cancel);
372
		} catch (ServerErrorException e) {
373
			throw new RemoteServiceException(getName(), e);
374
		} catch (org.gvsig.remoteclient.exceptions.WCSException e) {
375
			throw new RemoteServiceException(getName(), e);
376
		}
377
	}
378
	
379
	/**
380
	 * Sends a GetCoverage request to the client.
381
	 * @param status
382
	 * @return
383
	 * @throws WCSException
384
	 */
385
	public void getCoverageURL(WCSStatus status, ICancellable cancel, File file) throws RemoteServiceException {
386
		try {
387
			URL url = client.getCoverageURL(status, cancel);
388
			downloadFile(url, file, cancel);
389
			String exceptionMessage = client.getExceptionMessage(file);
390
			if(exceptionMessage != null)
391
				throw new RemoteServiceException(exceptionMessage);
392
		} catch(IOException e) {
393
			throw new RemoteServiceException("WMS: error downloading the file. File:" + file.getAbsolutePath() + "...." + e.getMessage());
394
		} catch (ServerErrorException e) {
395
			throw new RemoteServiceException("WMS Unexpected server error."+e.getMessage());
396
		}  catch (org.gvsig.remoteclient.exceptions.WMSException e) {
397
			throw new RemoteServiceException(e.getMessage());
398
		}
399
	}
400
	
401
	public void downloadFile(URL url, File dstFile, ICancellable cancel) throws IOException {
402
		Preferences prefs = Preferences.userRoot().node( "gvsig.downloader" );
403
		// by default 1 minute (60000 milliseconds.
404
		int timeout = prefs.getInt("timeout", 60000);
405

  
406
		DataOutputStream dos;
407
		DataInputStream is;
408
		OutputStreamWriter os = null;
409
		HttpURLConnection connection = null;
410
		//If the used protocol is HTTPS
411
		if (url.getProtocol().equals("https")) {
412
			try {
413
				disableHttsValidation();
414
			} catch (KeyManagementException e) {
415
				e.printStackTrace();
416
			} catch (NoSuchAlgorithmException e) {
417
				e.printStackTrace();
418
			}
419
		}
420
		connection = (HttpURLConnection)url.openConnection();
421
		connection.setConnectTimeout(timeout);
422
		is = new DataInputStream(url.openStream());
423

  
424
		dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(dstFile)));
425
		byte[] buffer = new byte[1024 * 4];
426

  
427

  
428
		long readed = 0;
429
		for (int i = is.read(buffer); i > 0; i = is.read(buffer)){
430
			dos.write(buffer, 0, i);
431
			readed += i;
432
			if(cancel != null && cancel.isCanceled())
433
				return;
434
		}
435
		if(os != null) {
436
			os.close();
437
		}
438
		dos.close();
439
		is.close();
440
		is = null;
441
		dos = null;
442
	}
443

  
444
	/**
445
	 * This method disables the Https certificate validation.
446
	 * @throws KeyManagementException
447
	 * @throws NoSuchAlgorithmException
448
	 */
449
	private void disableHttsValidation() throws KeyManagementException, NoSuchAlgorithmException{
450
		// Create a trust manager that does not validate certificate chains
451
		TrustManager[] trustAllCerts = new TrustManager[] {
452
				new X509TrustManager() {
453
					public java.security.cert.X509Certificate[] getAcceptedIssuers() {
454
						return null;
455
					}
456
					public void checkClientTrusted(
457
							java.security.cert.X509Certificate[] certs, String authType) {
458
					}
459
					public void checkServerTrusted(
460
							java.security.cert.X509Certificate[] certs, String authType) {
461
					}
462
				}
463
		};
464

  
465
		// Install the all-trusting trust manager
466
		SSLContext sc = SSLContext.getInstance("SSL");
467
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
468
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
469
	}
470
   
471
}
0 472

  
org.gvsig.raster.wcs/tags/buildNumber_20/org.gvsig.raster.wcs/org.gvsig.raster.wcs.io/src/main/java/org/gvsig/raster/wcs/io/WCSProvider.java
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
package org.gvsig.raster.wcs.io;
23

  
24
import java.awt.geom.AffineTransform;
25
import java.awt.geom.NoninvertibleTransformException;
26
import java.awt.geom.Point2D;
27
import java.awt.geom.Rectangle2D;
28
import java.io.File;
29
import java.io.IOException;
30
import java.net.URL;
31
import java.util.Hashtable;
32

  
33
import org.gvsig.compat.net.ICancellable;
34
import org.gvsig.fmap.dal.DALLocator;
35
import org.gvsig.fmap.dal.DataStore;
36
import org.gvsig.fmap.dal.DataStoreParameters;
37
import org.gvsig.fmap.dal.coverage.RasterLocator;
38
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
39
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
40
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
41
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
42
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
43
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
44
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
45
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
46
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
47
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
48
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
49
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
50
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
51
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
52
import org.gvsig.fmap.dal.exception.InitializeException;
53
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
54
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
55
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
56
import org.gvsig.metadata.MetadataLocator;
57
import org.gvsig.raster.cache.tile.TileCacheLocator;
58
import org.gvsig.raster.cache.tile.TileCacheManager;
59
import org.gvsig.raster.cache.tile.exception.TileGettingException;
60
import org.gvsig.raster.cache.tile.provider.TileListener;
61
import org.gvsig.raster.cache.tile.provider.TileServer;
62
import org.gvsig.raster.impl.DefaultRasterManager;
63
import org.gvsig.raster.impl.buffer.DefaultRasterQuery;
64
import org.gvsig.raster.impl.datastruct.BandListImpl;
65
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
66
import org.gvsig.raster.impl.datastruct.ExtentImpl;
67
import org.gvsig.raster.impl.provider.DefaultRasterProvider;
68
import org.gvsig.raster.impl.provider.RasterProvider;
69
import org.gvsig.raster.impl.provider.RemoteRasterProvider;
70
import org.gvsig.raster.impl.store.DefaultStoreFactory;
71
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
72
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
73
import org.gvsig.raster.impl.store.properties.RemoteDataStoreStatistics;
74
import org.gvsig.raster.impl.store.properties.RemoteStoreHistogram;
75
import org.gvsig.raster.util.DefaultProviderServices;
76
import org.gvsig.raster.wcs.io.downloader.WCSTileServer;
77
import org.gvsig.remoteclient.wcs.WCSStatus;
78
import org.gvsig.tools.ToolsLocator;
79
import org.gvsig.tools.task.TaskStatus;
80
import org.slf4j.Logger;
81
import org.slf4j.LoggerFactory;
82
/**
83
 * Clase que representa al driver de acceso a datos de wcs.
84
 *
85
 * @author Nacho Brodin (nachobrodin@gmail.com)
86
 */
87
public class WCSProvider extends DefaultRasterProvider implements RemoteRasterProvider {
88
	public static String                NAME                     = "Wcs Store";
89
	public static String                DESCRIPTION              = "Wcs Raster file";
90
	public static final String          METADATA_DEFINITION_NAME = "WcsStore";
91
	
92
	private static final Logger         logger                   = LoggerFactory.getLogger(WCSProvider.class);
93
	private Extent                      viewRequest              = null;
94
	private static Hashtable<URL, WCSConnector>    
95
	                                    drivers                  = new Hashtable<URL, WCSConnector> ();
96
	private boolean                     open                     = false;
97
	private DataStoreTransparency       fileTransparency         = null;
98
	private File                        lastRequest              = null;
99
	private DefaultRasterProvider       lastRequestProvider      = null; 
100
	
101
	public static void register() {
102
		DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
103
		if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
104
			dataman.registerStoreProvider(NAME,
105
					WCSProvider.class, WCSDataParametersImpl.class);
106
		}
107

  
108
		if (!dataman.getExplorerProviders().contains(WCSServerExplorer.NAME)) {
109
			dataman.registerExplorerProvider(WCSServerExplorer.NAME, WCSServerExplorer.class, WCSServerExplorerParameters.class);
110
		}
111
		dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
112
	}
113
	
114
	public WCSProvider() throws NotSupportedExtensionException {
115
		super();
116
	}
117
	
118
	/**
119
	 * Constructor. Abre el dataset.
120
	 * @param proj Proyecci?n
121
	 * @param fName Nombre del fichero
122
	 * @throws NotSupportedExtensionException
123
	 */
124
	public WCSProvider(String params) throws NotSupportedExtensionException {
125
		super(params);
126
		if(params instanceof String) {
127
			WCSDataParametersImpl p = new WCSDataParametersImpl();
128
			p.setURI((String)params);
129
			super.init(p, null, ToolsLocator.getDynObjectManager()
130
					.createDynObject(
131
							MetadataLocator.getMetadataManager().getDefinition(
132
									DataStore.METADATA_DEFINITION_NAME)));
133
			init(p, null);
134
		}
135
	}
136
	
137
	public WCSProvider(WCSDataParametersImpl params,
138
			DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
139
		super(params, storeServices, ToolsLocator.getDynObjectManager()
140
				.createDynObject(
141
						MetadataLocator.getMetadataManager().getDefinition(
142
								DataStore.METADATA_DEFINITION_NAME)));
143
		init(params, storeServices);
144
	}
145
	
146
	/**
147
	 * Gets the connector from the URL
148
	 * @return
149
	 * @throws RemoteServiceException
150
	 */
151
	public WCSConnector getConnector() throws RemoteServiceException {
152
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
153
		URL url = null;
154
		try {
155
			url = new URL(p.getURI());
156
		} catch (Exception e) {
157
			throw new RemoteServiceException("Malformed URL",e);
158
		}
159
		try {
160
			return WCSProvider.getConnectorFromURL(url);
161
		} catch (IOException e) {
162
			throw new RemoteServiceException("Error getting the connector",e);
163
		}
164
	}
165
	
166
	/**
167
	 * Crea las referencias al fichero y carga
168
	 * las estructuras con la informaci?n y los metadatos.
169
	 * @param proj Proyecci?n
170
	 * @param param Parametros de carga
171
	 * @throws NotSupportedExtensionException
172
	 */
173
	public void init (DataStoreParameters params,
174
			DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
175
		setParam(storeServices, params);
176
		open = true;
177
		try {
178
			loadInitialInfo();
179
		} catch (RasterDriverException e) {
180
			logger.info("Loaded default values in WCS provider", e);
181
		}
182
		
183
		stats = new RemoteDataStoreStatistics(this);
184
	}
185
	
186
	public static final WCSConnector getConnectorFromURL(URL url) throws IOException {
187
		WCSConnector drv = (WCSConnector) drivers.get(url);
188
		if (drv == null) {
189
			drv = new WCSConnector(url);
190
			drivers.put(url, drv);
191
		}
192
		return drv;
193
	}
194
	
195
	/**
196
	 * Obtiene el objeto que contiene que contiene la interpretaci?n de
197
	 * color por banda
198
	 * @return
199
	 */
200
	public ColorInterpretation getColorInterpretation() {
201
		if(super.getColorInterpretation() == null) {
202
			ColorInterpretation colorInterpretation = new DataStoreColorInterpretation();
203
			colorInterpretation.initColorInterpretation(getBandCount());
204
			if(getBandCount() == 3) {
205
				colorInterpretation.setColorInterpValue(0, DataStoreColorInterpretation.RED_BAND);
206
				colorInterpretation.setColorInterpValue(1, DataStoreColorInterpretation.GREEN_BAND);
207
				colorInterpretation.setColorInterpValue(2, DataStoreColorInterpretation.BLUE_BAND);
208
			} else {
209
				for (int i = 0; i < getBandCount(); i++) {
210
					colorInterpretation.setColorInterpValue(i, DataStoreColorInterpretation.GRAY_BAND);
211
				}
212
			}
213
			setColorInterpretation(colorInterpretation);
214
		}
215
		return super.getColorInterpretation();
216
	}
217
	
218
	/**
219
	 * Gets WCS parameters
220
	 * @return
221
	 */
222
	public WCSDataParameters getParameters() {
223
		return (WCSDataParameters)parameters;
224
	}
225
	
226
	/*
227
	 * (non-Javadoc)
228
	 * @see org.gvsig.fmap.dal.coverage.dataset.RasterDataSet#getAffineTransform()
229
	 */
230
	public AffineTransform getAffineTransform() {
231
		Extent e = getExtent();
232
		double resolutionX = e.width() / getWidth();
233
		double resolutionY = e.height() / getHeight();
234
		ownTransformation = new AffineTransform(
235
				resolutionX, 
236
				0, 
237
				0, 
238
				-resolutionY, 
239
				e.getULX() - (resolutionX / 2),
240
				e.getULY() - (resolutionY / 2));
241
		externalTransformation = (AffineTransform) ownTransformation.clone();
242
		return ownTransformation;
243
	}
244
	
245
	/**
246
	 * Calcula el extent en coordenadas del mundo real
247
	 * @return Extent
248
	 */
249
	public Extent getExtent() {
250
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
251
		try {
252
			Rectangle2D r = getConnector().getFullExtent(p.getCoverageName(), p.getSRSCode());
253
			return new ExtentImpl(r.getX(),  r.getY() + r.getHeight(), r.getX() + r.getWidth(), r.getY());
254
		} catch (RemoteServiceException e1) {
255
			e1.printStackTrace();
256
		} catch (IOException e) {
257
			e.printStackTrace();
258
		}
259
		return null;
260
	}
261

  
262
	
263
	/*
264
	 * (non-Javadoc)
265
	 * @see org.gvsig.raster.impl.provider.RemoteRasterProvider#getLayerExtent(java.lang.String, java.lang.String)
266
	 */
267
	public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
268
		return null;
269
	}
270

  
271
	/*
272
	 * (non-Javadoc)
273
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#load()
274
	 */
275
	public RasterProvider load() {
276
		return this;
277
	}
278
	
279
	/*
280
	 * (non-Javadoc)
281
	 * @see org.gvsig.raster.impl.provider.RasterProvider#isOpen()
282
	 */
283
	public boolean isOpen() {
284
		return open;
285
	}
286

  
287
	/*
288
	 * (non-Javadoc)
289
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#close()
290
	 */
291
	public void close() {
292
		open = false;
293
	}
294
	
295
	/*
296
	 * (non-Javadoc)
297
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getTransparency()
298
	 */
299
	public Transparency getTransparency() {
300
		if(fileTransparency == null)
301
			fileTransparency = new DataStoreTransparency();
302
		return fileTransparency;
303
	}
304

  
305
	/*
306
	 * (non-Javadoc)
307
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#translateFileName(java.lang.String)
308
	 */
309
	public String translateFileName(String fileName) {
310
		return fileName;
311
	}
312

  
313
	/*
314
	 * (non-Javadoc)
315
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#setView(org.gvsig.fmap.dal.coverage.datastruct.Extent)
316
	 */
317
	public void setView(Extent e) {
318
		viewRequest = e;
319
	}
320

  
321
	/*
322
	 * (non-Javadoc)
323
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getView()
324
	 */
325
	public Extent getView() {
326
		return viewRequest;
327
	}
328
	
329
	/*
330
	 * (non-Javadoc)
331
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getWidth()
332
	 */
333
	public double getWidth() {
334
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
335
		try {
336
			return getConnector().getWidth(p.getCoverageName());
337
		} catch (RemoteServiceException e) {
338
			e.printStackTrace();
339
		}
340
		return 0;
341
	}
342

  
343
	/*
344
	 * (non-Javadoc)
345
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getHeight()
346
	 */
347
	public double getHeight() {
348
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
349
		try {
350
			return getConnector().getHeight(p.getCoverageName());
351
		} catch (RemoteServiceException e) {
352
			e.printStackTrace();
353
		}
354
		return 0;
355
	}
356

  
357
	/*
358
	 * (non-Javadoc)
359
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#readCompleteLine(int, int)
360
	 */
361
	public Object readCompleteLine(int line, int band)
362
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
363
		return null;
364
	}
365
	
366
	/**
367
	 * When the remote layer has fixed size this method downloads the file and return its reference. 
368
	 * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
369
	 * useful to build an histogram or calculate statistics. This represents a sample of data.
370
	 * @return
371
	 * @throws RasterDriverException
372
	 */
373
	public File getFileLayer() throws RasterDriverException {
374
		Extent e = getExtent();
375
		Rectangle2D bBox = new Rectangle2D.Double(e.getULX(), e.getLRY(), e.width(), e.height());
376
		WCSStatus wcsStatus = loadWCSStatus(bBox);
377
		
378
		return downloadFile(wcsStatus, e.getULX(), e.getULY(), e.getLRX(), e.getLRY(), 
379
				(int)getWidth(), (int)getHeight());
380
	}
381

  
382
	/**
383
	 * Reads a complete block of data and returns an tridimensional array of the right type. This function is useful
384
	 * to read a file very fast without setting a view. In a WCS service when the size is fixed then it will read the
385
	 * entire image but when the source hasn't pixel size it will read a sample of data. This set of data will have
386
	 * the size defined in FIXED_SIZE. 
387
	 * 
388
	 * @param pos Posici?n donde se empieza  a leer
389
	 * @param blockHeight Altura m?xima del bloque leido
390
	 * @return Object que es un array tridimendional del tipo de datos del raster. (Bandas X Filas X Columnas)
391
	 * @throws InvalidSetViewException
392
	 * @throws FileNotOpenException
393
	 * @throws RasterDriverException
394
	 */
395
	public Object readBlock(int pos, int blockHeight, double scale) 
396
	throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
397
		File lastFile = getFileLayer();
398
		BandList bandList = new BandListImpl();
399
		for (int i = 0; i < 3; i++) {
400
			try {
401
				bandList.addBand(new DatasetBandImpl(lastFile.getPath(), pos, Buffer.TYPE_BYTE, 3), pos);
402
			} catch (BandNotFoundInListException e1) {
403
			}
404
		}
405
		bandList.setDrawableBands(new int[]{0, 1, 2});
406

  
407
		try {
408
			lastRequestProvider = openLastRequest();
409
			return lastRequestProvider.readBlock(pos, blockHeight, scale);
410
		} catch (ProviderNotRegisteredException exc) {
411
			throw new RasterDriverException("Error building GdalDriver", exc);
412
		} catch (InitializeException exc) {
413
			throw new RasterDriverException("Error building GdalDriver", exc);
414
		}
415
	}
416
	
417
	/*
418
	 * (non-Javadoc)
419
	 * @see org.gvsig.raster.impl.provider.RemoteRasterProvider#getLastRequestHeight()
420
	 */
421
	public double getLastRequestHeight() throws RasterDriverException {
422
		if(lastRequestProvider == null) {
423
			try {
424
				lastRequestProvider = openLastRequest();
425
			} catch (ProviderNotRegisteredException e) {
426
				throw new RasterDriverException("Error building GdalDriver", e);
427
			} catch (InitializeException e) {
428
				throw new RasterDriverException("Error building GdalDriver", e);
429
			}
430
		}
431
		return lastRequestProvider.getHeight();
432
	}
433
	
434
	/*
435
	 * (non-Javadoc)
436
	 * @see org.gvsig.raster.impl.provider.RemoteRasterProvider#getLastRequestWidth()
437
	 */
438
	public double getLastRequestWidth() throws RasterDriverException {
439
		if(lastRequestProvider == null) {
440
			try {
441
				lastRequestProvider = openLastRequest();
442
			} catch (ProviderNotRegisteredException e) {
443
				throw new RasterDriverException("Error building GdalDriver", e);
444
			} catch (InitializeException e) {
445
				throw new RasterDriverException("Error building GdalDriver", e);
446
			}
447
		}
448
		return lastRequestProvider.getWidth();
449
	}
450
	
451
	/*
452
	 * (non-Javadoc)
453
	 * @see org.gvsig.raster.impl.provider.RemoteRasterProvider#getLastRequest()
454
	 */
455
	public File getLastRequest() {
456
		return lastRequest;
457
	}
458
	
459
	/*
460
	 * (non-Javadoc)
461
	 * @see org.gvsig.raster.impl.provider.RemoteRasterProvider#getBufferLastRequest()
462
	 */
463
	public Buffer getBufferLastRequest() throws ProcessInterruptedException, RasterDriverException {
464
		try {
465
			lastRequestProvider = openLastRequest();
466
			
467
			BandList bandList = new BandListImpl();
468
			for (int i = 0; i < lastRequestProvider.getBandCount(); i++) {
469
				try {
470
					bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, Buffer.TYPE_BYTE, 3), i);
471
				} catch (BandNotFoundInListException e1) {
472
				}
473
			}
474
			bandList.setDrawableBands(new int[]{0, 1, 2});
475
			Buffer newBuffer = DefaultRasterManager.getInstance().createBuffer(lastRequestProvider.getDataType()[0], (int)lastRequestProvider.getWidth(), (int)lastRequestProvider.getHeight(), lastRequestProvider.getBandCount(), true);
476
			
477
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
478
			q.setAreaOfInterest(lastRequestProvider.getExtent(), 
479
					(int)lastRequestProvider.getWidth(), 
480
					(int)lastRequestProvider.getHeight());
481
			q.setBandList(bandList);
482
			q.setBuffer(newBuffer);
483
			q.setAdjustToExtent(true);
484
			
485
			return lastRequestProvider.getDataSet(q);
486
		} catch (ProviderNotRegisteredException e) {
487
			throw new RasterDriverException("Error building GdalDriver", e);
488
		} catch (InitializeException e) {
489
			throw new RasterDriverException("Error building GdalDriver", e);
490
		}
491
	}
492
	
493
	/**
494
	 * Opens the last request downloaded
495
	 * @return
496
	 * @throws ProviderNotRegisteredException
497
	 * @throws InitializeException
498
	 * @throws RasterDriverException
499
	 */
500
	private DefaultRasterProvider openLastRequest() throws ProviderNotRegisteredException, InitializeException, RasterDriverException {
501
		if(lastRequestProvider != null)
502
			lastRequestProvider.close();
503
		File lastFile = getFileLayer();
504
		lastRequestProvider = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
505
		return lastRequestProvider;
506
	}
507

  
508

  
509
	/*
510
	 * (non-Javadoc)
511
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getData(int, int, int)
512
	 */
513
	public Object getData(int x, int y, int band)
514
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
515
		return null;
516
	}
517
	
518
	/**
519
	 * Gets the georeferencing file name form a raster file
520
	 * @param file
521
	 * a raster file
522
	 * @return
523
	 * a georeferencing file
524
	 */
525
	private String getWorldFile(String file){		
526
		String worldFile = file;
527
		int index = file.lastIndexOf(".");
528
		if (index > 0) {			
529
			worldFile = file.substring(0, index) + getExtensionWorldFile();
530
		} else {
531
			worldFile = file + getExtensionWorldFile();
532
		}
533
		return worldFile;
534
	}
535
	
536
	/**
537
	 * Obtiene la extensi?n del fichero de georreferenciaci?n
538
	 * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
539
	 * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
540
	 */
541
	private String getExtensionWorldFile() {
542
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
543
		String extWorldFile = ".wld";
544
		if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
545
			extWorldFile = ".tfw";
546
		}
547
		return extWorldFile;
548
	}
549
	
550
	private WCSStatus loadWCSStatus(Rectangle2D bBox) {
551
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
552
		WCSStatus wcsStatus = new WCSStatus();
553
		wcsStatus.setCoveraName(p.getCoverageName());
554
		wcsStatus.setSrs(p.getSRSCode());
555
		wcsStatus.setFormat(p.getFormat());
556
		wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
557
		wcsStatus.setExtent(bBox);
558
		wcsStatus.setHeight(p.getHeight());
559
		wcsStatus.setWidth(p.getWidth());
560
		wcsStatus.setDepth(p.getDepth());
561
		wcsStatus.setParameters(p.getParameter());
562
		wcsStatus.setTime(p.getTime());
563
		return wcsStatus;
564
	}
565
	
566
	/*
567
	 * (non-Javadoc)
568
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#needEnhanced()
569
	 */
570
	public boolean needEnhanced() {
571
		return (getDataType()[0] != Buffer.TYPE_BYTE || 
572
				(getBandCount() == 1 && getDataType()[0] == Buffer.TYPE_BYTE));
573
	}
574
	
575
	/**
576
	 * This function downloads the file and creates the georeferencing file
577
	 * @param wcsStatus
578
	 * @param ulx
579
	 * @param uly
580
	 * @param lrx
581
	 * @param lry
582
	 * @param w
583
	 * @param h
584
	 * @return
585
	 * @throws RasterDriverException
586
	 */
587
	private File downloadFile(WCSStatus wcsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
588
		try {
589
			lastRequest = getConnector().getCoverage(wcsStatus, ((WCSDataParametersImpl)parameters).getCancellable());
590
		} catch (RemoteServiceException e) {
591
			throw new RasterDriverException(e.getMessage(), e);
592
		}
593
		
594
		String nameWorldFile = getWorldFile(lastRequest.getPath());
595
		try {
596
			fileUtil.createWorldFile(nameWorldFile, new ExtentImpl(ulx, uly, lrx, lry), w, h);
597
		} catch (IOException e) {
598
			throw new RasterDriverException("Error downloading file", e);
599
		}
600

  
601
		return lastRequest;
602
	}
603
	
604
	/**
605
	 * Assigns the list of bands RGB and read a window of data
606
	 * @param rasterBuf
607
	 * @param bandList
608
	 * @param lastFile
609
	 * @param ulx
610
	 * @param uly
611
	 * @param lrx
612
	 * @param lry
613
	 * @return
614
	 * @throws RasterDriverException
615
	 * @throws ProcessInterruptedException
616
	 */
617
	public Buffer getBuffer(Buffer rasterBuf, BandList bandList, File lastFile, 
618
			double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
619
		try {
620
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
621
			String serverName = bandList.getBand(0).getFileName();
622
			for (int i = 0; i < bandList.getBandCount(); i++) {
623
				bandList.getBand(i).setFileName(lastFile.getPath());
624
			}
625
			
626
			DefaultRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
627
			
628
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
629
			q.setAreaOfInterest(new ExtentImpl(ulx, uly, lrx, lry));
630
			q.setBandList(bandList);
631
			q.setBuffer(rasterBuf);
632
			
633
			Buffer buf = driver.getDataSet(q);
634
			
635
			for (int i = 0; i < bandList.getBandCount(); i++) {
636
				bandList.getBand(i).setFileName(serverName);
637
			}
638
			
639
			return buf;
640
		} catch (ProviderNotRegisteredException e) {
641
			throw new RasterDriverException("Error building GdalDriver", e);
642
		} catch (InitializeException e) {
643
			throw new RasterDriverException("Error building GdalDriver", e);
644
		}
645
	}
646
	
647
	/*
648
	 * (non-Javadoc)
649
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getWindowRaster(org.gvsig.fmap.dal.coverage.datastruct.Extent, int, int, org.gvsig.fmap.dal.coverage.datastruct.BandList, org.gvsig.raster.cache.tile.provider.TileListener)
650
	 */
651
	public void getWindow(Extent ex, int bufWidth, int bufHeight, 
652
			BandList bandList, TileListener listener, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
653

  
654
		Buffer raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], bufWidth, bufHeight, 3, true);
655
		getWindow(ex, bufWidth, bufHeight, bandList, raster, true, null);
656
		raster.setDataExtent(ex.toRectangle2D());
657

  
658
		TileCacheManager m = TileCacheLocator.getManager();
659
		org.gvsig.raster.cache.tile.Tile t = m.createTile(-1, 0, 0);
660
		t.setData(new Object[]{raster});
661
		t.setUl(new Point2D.Double(ex.getULX(), ex.getULY()));
662
		t.setLr(new Point2D.Double(ex.getLRX(), ex.getLRY()));
663
		t.setDownloaderParams("AffineTransform", getAffineTransform());
664
		t.setDownloaderParams("Tiling", new Boolean(false));
665
		try {
666
			listener.tileReady(t);
667
		} catch (TileGettingException e) {
668
			throw new RasterDriverException("Error throwing a tile", e);
669
		}
670

  
671
		//listener.nextBuffer(raster, null, new ExtentImpl(minX, minY, maxX, maxY), getAffineTransform(), null, false);
672
		listener.endReading();
673

  
674
	}
675

  
676
	/*
677
	 * (non-Javadoc)
678
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getWindowRaster(double, double, double, double, org.gvsig.fmap.dal.coverage.datastruct.BandList, org.gvsig.fmap.dal.coverage.dataset.Buffer)
679
	 */
680
	public Buffer getWindow(Extent ex, BandList bandList, Buffer rasterBuf, TaskStatus status) 
681
		throws ProcessInterruptedException, RasterDriverException {
682
		Rectangle2D bBox = ex.toRectangle2D();
683
		WCSStatus wcsStatus = loadWCSStatus(bBox);
684
		
685
		lastRequest = downloadFile(wcsStatus, ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), rasterBuf.getWidth(), rasterBuf.getHeight());
686
		
687
		if (lastRequest == null) {
688
			return rasterBuf;
689
		}
690
		
691
		try {
692
			DefaultRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
693
			/*bandCount = driver.getBandCount();
694
			setDataType(driver.getDataType());
695
			rasterBuf = changeBufferDataType(getDataType()[0], rasterBuf, bandList);*/
696
			
697
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
698
			String serverName = bandList.getBand(0).getFileName();
699
			for (int i = 0; i < bandList.getBandCount(); i++) {
700
				bandList.getBand(i).setFileName(lastRequest.getPath());
701
			}
702
			
703
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
704
			q.setAreaOfInterest(ex);
705
			q.setBandList(bandList);
706
			q.setBuffer(rasterBuf);
707
			Buffer buf = driver.getDataSet(q);
708
			
709
			for (int i = 0; i < bandList.getBandCount(); i++) {
710
				bandList.getBand(i).setFileName(serverName);
711
			}
712
			driver.close();
713
			return buf;
714
		} catch (ProviderNotRegisteredException e) {
715
			throw new RasterDriverException("Error building GdalDriver", e);
716
		} catch (InitializeException e) {
717
			throw new RasterDriverException("Error building GdalDriver", e);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff