Revision 1831

View differences:

org.gvsig.raster.wcs/tags/buildNumber_33/org.gvsig.raster.wcs/org.gvsig.raster.wcs.io/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.raster.wcs.io.DefaultWCSIOLibrary
org.gvsig.raster.wcs/tags/buildNumber_33/org.gvsig.raster.wcs/org.gvsig.raster.wcs.io/src/main/resources/org/gvsig/raster/wcs/io/i18n/text.properties
1
error_connecting=Error conectando con el servidor
2
malformed_url=URL mal formada
0 3

  
org.gvsig.raster.wcs/tags/buildNumber_33/org.gvsig.raster.wcs/org.gvsig.raster.wcs.io/src/main/resources/org/gvsig/raster/wcs/io/i18n/text_en.properties
1
error_connecting=Error connecting with the server
2
malformed_url=Malformed URL
0 3

  
org.gvsig.raster.wcs/tags/buildNumber_33/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_33/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_33/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
			if(r == null)
251
				return null;
252
			return new ExtentImpl(r.getX(),  r.getY() + r.getHeight(), r.getX() + r.getWidth(), r.getY());
253
		} catch (RemoteServiceException e1) {
254
			e1.printStackTrace();
255
		} catch (IOException e) {
256
			e.printStackTrace();
257
		}
258
		return null;
259
	}
260

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

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

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

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

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

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

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

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

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

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

  
507

  
508
	/*
509
	 * (non-Javadoc)
510
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getData(int, int, int)
511
	 */
512
	public Object getData(int x, int y, int band)
513
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
514
		int w = 25;
515
		int h = 25;
516
		
517
		Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
518
		Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
519
		Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
520
		
521
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
522
		WCSStatus wcsStatus = new WCSStatus();
523
		wcsStatus.setCoveraName(p.getCoverageName());
524
		wcsStatus.setSrs(p.getSRSCode());
525
		wcsStatus.setFormat(p.getFormat());
526
		wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
527
		wcsStatus.setExtent(bBox);
528
		wcsStatus.setHeight(h);
529
		wcsStatus.setWidth(w);
530
		wcsStatus.setDepth(p.getDepth());
531
		wcsStatus.setParameters(p.getParameter());
532
		wcsStatus.setTime(p.getTime());
533
		
534
		lastRequest = downloadFile(wcsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), w, h);
535
		
536
		DefaultRasterProvider driver = null;
537
		try {
538
			driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
539
			Buffer buf = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], w, h, getBandCount(), true);
540
			BandList bandList = new BandListImpl();
541
			int[] drawable = new int[getBandCount()];
542
			for (int i = 0; i < getBandCount(); i++) {
543
				try {
544
					bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, getDataType()[i], getBandCount()), i);
545
					drawable[i] = i;
546
				} catch (BandNotFoundInListException e1) {
547
				}
548
			}
549
			bandList.setDrawableBands(drawable);
550
			
551
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
552
			q.setAreaOfInterest(0, 0, 25, 25);
553
			q.setBandList(bandList);
554
			q.setBuffer(buf);
555
			buf = driver.getDataSet(q);
556
			driver.close();
557
			if(buf.getDataType() == Buffer.TYPE_BYTE) {
558
				return new Integer(buf.getElemByte(0, 0, band));
559
			}
560
			if(buf.getDataType() == Buffer.TYPE_SHORT) {
561
				return new Integer(buf.getElemShort(0, 0, band));
562
			}
563
			if(buf.getDataType() == Buffer.TYPE_INT) {
564
				return new Integer(buf.getElemInt(0, 0, band));
565
			}
566
			if(buf.getDataType() == Buffer.TYPE_FLOAT) {
567
				return new Float(buf.getElemFloat(0, 0, band));
568
			}
569
			if(buf.getDataType() == Buffer.TYPE_DOUBLE) {
570
				return new Double(buf.getElemDouble(0, 0, band));
571
			}
572
		} catch(InitializeException e) {
573
			throw new RasterDriverException("", e);
574
		} catch (ProviderNotRegisteredException e) {
575
			throw new RasterDriverException("", e);
576
		} catch (ProcessInterruptedException e) {
577
		}
578
		return null;
579
	}
580
	
581
	/**
582
	 * Gets the georeferencing file name form a raster file
583
	 * @param file
584
	 * a raster file
585
	 * @return
586
	 * a georeferencing file
587
	 */
588
	private String getWorldFile(String file){		
589
		String worldFile = file;
590
		int index = file.lastIndexOf(".");
591
		if (index > 0) {			
592
			worldFile = file.substring(0, index) + getExtensionWorldFile();
593
		} else {
594
			worldFile = file + getExtensionWorldFile();
595
		}
596
		return worldFile;
597
	}
598
	
599
	/**
600
	 * Obtiene la extensi?n del fichero de georreferenciaci?n
601
	 * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
602
	 * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
603
	 */
604
	private String getExtensionWorldFile() {
605
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
606
		String extWorldFile = ".wld";
607
		if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
608
			extWorldFile = ".tfw";
609
		}
610
		return extWorldFile;
611
	}
612
	
613
	private WCSStatus loadWCSStatus(Rectangle2D bBox) {
614
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
615
		WCSStatus wcsStatus = new WCSStatus();
616
		wcsStatus.setCoveraName(p.getCoverageName());
617
		wcsStatus.setSrs(p.getSRSCode());
618
		wcsStatus.setFormat(p.getFormat());
619
		wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
620
		wcsStatus.setExtent(bBox);
621
		wcsStatus.setHeight(p.getHeight());
622
		wcsStatus.setWidth(p.getWidth());
623
		wcsStatus.setDepth(p.getDepth());
624
		wcsStatus.setParameters(p.getParameter());
625
		wcsStatus.setTime(p.getTime());
626
		return wcsStatus;
627
	}
628
	
629
	/*
630
	 * (non-Javadoc)
631
	 * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#needEnhanced()
632
	 */
633
	public boolean needEnhanced() {
634
		return (getDataType()[0] != Buffer.TYPE_BYTE || 
635
				(getBandCount() == 1 && getDataType()[0] == Buffer.TYPE_BYTE));
636
	}
637
	
638
	/**
639
	 * This function downloads the file and creates the georeferencing file
640
	 * @param wcsStatus
641
	 * @param ulx
642
	 * @param uly
643
	 * @param lrx
644
	 * @param lry
645
	 * @param w
646
	 * @param h
647
	 * @return
648
	 * @throws RasterDriverException
649
	 */
650
	private File downloadFile(WCSStatus wcsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
651
		try {
652
			lastRequest = getConnector().getCoverage(wcsStatus, ((WCSDataParametersImpl)parameters).getCancellable());
653
		} catch (RemoteServiceException e) {
654
			throw new RasterDriverException(e.getMessage(), e);
655
		}
656
		
657
		String nameWorldFile = getWorldFile(lastRequest.getPath());
658
		try {
659
			fileUtil.createWorldFile(nameWorldFile, new ExtentImpl(ulx, uly, lrx, lry), w, h);
660
		} catch (IOException e) {
661
			throw new RasterDriverException("Error downloading file", e);
662
		}
663

  
664
		return lastRequest;
665
	}
666
	
667
	/**
668
	 * Assigns the list of bands RGB and read a window of data
669
	 * @param rasterBuf
670
	 * @param bandList
671
	 * @param lastFile
672
	 * @param ulx
673
	 * @param uly
674
	 * @param lrx
675
	 * @param lry
676
	 * @return
677
	 * @throws RasterDriverException
678
	 * @throws ProcessInterruptedException
679
	 */
680
	public Buffer getBuffer(Buffer rasterBuf, BandList bandList, File lastFile, 
681
			double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
682
		try {
683
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff