Revision 1376

View differences:

org.gvsig.raster.wcs/tags/buildNumber_24/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
import org.gvsig.i18n.Messages;
49

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

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

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

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

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

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

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

  
126

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

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

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

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

  
149
	public void dispose() {
150
		
151
	}
152

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
505

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

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

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

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

  
668
		//listener.nextBuffer(raster, null, new ExtentImpl(minX, minY, maxX, maxY), getAffineTransform(), null, false);
669
		listener.endReading();
670

  
671
	}
672

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

Also available in: Unified diff