Revision 4010

View differences:

org.gvsig.raster.wcs/tags/org.gvsig.raster.wcs-2.2.15/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/org.gvsig.raster.wcs-2.2.15/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/org.gvsig.raster.wcs-2.2.15/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/org.gvsig.raster.wcs-2.2.15/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.io.InputStream;
33
import java.net.MalformedURLException;
34
import java.net.URL;
35
import java.net.URLConnection;
36
import java.util.Hashtable;
37
import java.util.List;
38

  
39
import org.gvsig.compat.net.ICancellable;
40
import org.gvsig.fmap.dal.DALLocator;
41
import org.gvsig.fmap.dal.DataManager;
42
import org.gvsig.fmap.dal.DataServerExplorerParameters;
43
import org.gvsig.fmap.dal.DataStoreParameters;
44
import org.gvsig.fmap.dal.NewDataStoreParameters;
45
import org.gvsig.fmap.dal.coverage.exception.ConnectException;
46
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
47
import org.gvsig.fmap.dal.coverage.store.RasterDataServerExplorer;
48
import org.gvsig.fmap.dal.exception.DataException;
49
import org.gvsig.fmap.dal.exception.InitializeException;
50
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
51
import org.gvsig.fmap.dal.spi.DataServerExplorerProvider;
52
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
53
import org.gvsig.i18n.Messages;
54

  
55
/**
56
 * Explorer for a WCS server
57
 * @author Nacho Brodin (nachobrodin@gmail.com)
58
 */
59
public class WCSServerExplorer implements RasterDataServerExplorer, DataServerExplorerProvider {
60
	private WCSConnector                connector                = null;
61
	private WCSServerExplorerParameters parameters               = null;
62
	
63
	public WCSServerExplorer(
64
			WCSServerExplorerParameters parameters,
65
			DataServerExplorerProviderServices services)
66
			throws InitializeException {
67
		this.parameters = parameters;
68
	}
69
	
70
	/**
71
	 * Gets the provider's name
72
	 * @return
73
	 */
74
	public String getDataStoreProviderName() {
75
		return WCSProvider.NAME;
76
	}
77
	
78
	public String getDescription() {
79
		return WCSProvider.DESCRIPTION;
80
	}
81
	
82
	public boolean add(String provider, NewDataStoreParameters parameters,
83
			boolean overwrite) throws DataException {
84
		return false;
85
	}
86

  
87
	public boolean canAdd() {
88
		return false;
89
	}
90

  
91
	public boolean canAdd(String storeName) throws DataException {
92
		return false;
93
	}
94

  
95
	public NewDataStoreParameters getAddParameters(String storeName)
96
			throws DataException {
97
		return null;
98
	}
99

  
100
	public List getDataStoreProviderNames() {
101
		return null;
102
	}
103

  
104
	public DataServerExplorerParameters getParameters() {
105
		return parameters;
106
	}
107

  
108
	public List list() throws DataException {
109
		return null;
110
	}
111

  
112
	public List list(int mode) throws DataException {
113
		return null;
114
	}
115

  
116
	public void remove(DataStoreParameters parameters) throws DataException {
117
		
118
	}
119

  
120
	public void dispose() {
121
		
122
	}
123

  
124
	public String getProviderName() {
125
		return null;
126
	}
127
	
128
	/**
129
	 * Gets the online resources
130
	 * @return
131
	 */
132
	public Hashtable getOnlineResources() {
133
		/*if(connector != null) {
134
			return connector.getOnlineResources();
135
		}*/
136
		return null;
137
	}
138
	
139
	//**********************************************
140
	//Connector
141
	//**********************************************
142
	
143
	public DataStoreParameters getStoredParameters() {
144
		DataManager manager = DALLocator.getDataManager();
145
		WCSDataParametersImpl params = null;
146
		try {
147
			params = (WCSDataParametersImpl) manager.createStoreParameters(this.getDataStoreProviderName());
148

  
149
			/*if(WCSProvider.TILED) {
150
				TileDataParameters tileParams = (TileDataParameters) manager.createStoreParameters("Tile Store");
151
				tileParams.setDataParameters(params);
152
				return tileParams;
153
			} */
154
			
155
		} catch (InitializeException e) {
156
			e.printStackTrace();
157
		} catch (ProviderNotRegisteredException e) {
158
			e.printStackTrace();
159
		}
160
		params.setURI(parameters.getHost());
161
		return params;
162
	}
163

  
164
	/**
165
	 * Connects to the server and throws a getCapabilities. This loads 
166
	 * the basic information to make requests.
167
	 * @throws RemoteServiceException 
168
	 */
169
	public void connect(ICancellable cancellable) throws ConnectException {
170
		URL url = null;
171
		boolean override = false;
172
		
173
		try {
174
			url = new URL(parameters.getHost());
175
		} catch (Exception e) {
176
			throw new ConnectException(Messages.getText("malformed_url"), e);
177
		}
178
        try {
179
        	connector = WCSProvider.getConnectorFromURL(url);
180
        	if (!connector.connect(override, cancellable))
181
        		throw new ConnectException(Messages.getText("error_connecting"));
182
        } catch (IOException e) {
183
			throw new ConnectException(Messages.getText("error_connecting"), e);
184
		}
185
		
186
	}
187
	
188
	/**
189
	 * Checks if the network and host are reachable
190
	 * @param timeout for the host
191
	 * @return true if both are reachable and false if they are not
192
	 */
193
	public boolean isHostReachable(int timeout) {
194
		URL url = null;
195
		try {
196
			url = new URL(parameters.getHost());
197
			URLConnection con = url.openConnection();
198
			if(con == null)
199
				return false;
200
			con.connect();
201
			InputStream stream = con.getInputStream();
202
			if(stream == null)
203
				return false;
204
		} catch (MalformedURLException e) {
205
			return false;
206
		} catch (IOException e) {
207
			return false;
208
		}
209
		
210
		return true;
211
	}
212

  
213
	/**
214
	 * Checks if the network and host are reachable
215
	 * @return true if both are reachable and false if they are not
216
	 */
217
	public boolean isHostReachable() {
218
		int timeout = 10000;
219
		return isHostReachable(timeout);
220
	}
221

  
222
	/**
223
	 * Returns true if this provider is connected to the server
224
	 * @return
225
	 */
226
	public boolean isConnected() {
227
		if(connector != null)
228
			return true;
229
		return false;
230
	}
231

  
232
	/**
233
	 * Gets the description of this service
234
	 * @return
235
	 */
236
	public String getAbstract() {
237
		if(connector != null)
238
			return connector.getDescription();
239
		return null;
240
	}
241

  
242
	/**
243
	 * Gets the server title
244
	 * @return
245
	 */
246
	public String getServerType() {
247
		if (getVersion() == null) 
248
			return "WCS";
249
        return "WCS "+ getVersion();
250
	}
251

  
252
	/**
253
	 * Gets the protocol supported by the server
254
	 * @return
255
	 */
256
	public String getVersion() {
257
		if(connector != null) {
258
			return (connector.getVersion() == null) ? "" : connector.getVersion();
259
		}
260
		return null;
261
	}
262

  
263
	/**
264
	 * Gets the host URI
265
	 * @return
266
	 */
267
	public String getHost() {
268
		return parameters.getHost();
269
	}
270
	
271
	/**
272
	 * Gets the title
273
	 * @return
274
	 */
275
	public String getTitle() {
276
		return null;
277
	}
278

  
279
	public DataServerExplorerProviderServices getServerExplorerProviderServices() {
280
		return null;
281
	}
282

  
283
	public Point2D getMaxResolution(String layerName) {
284
		return connector.getMaxResolution(layerName);
285
	}
286

  
287
	/**
288
	 * Gets the coverage list
289
	 * @return
290
	 */
291
	public WCSLayerNode[] getCoverageList() {
292
		return connector.getLayerList();
293
	}
294
	
295
	/**
296
	 * Gets a layer searching by its name 
297
	 * @return
298
	 */
299
	public WCSLayerNode getCoverageByName(String name) {
300
		WCSLayerNode[] list = getCoverageList();
301
		for (int i = 0; i < list.length; i++) {
302
			if(list[i].getName().compareTo(name) == 0)
303
				return list[i];
304
		}
305
		return null;
306
	}
307
}
0 308

  
org.gvsig.raster.wcs/tags/org.gvsig.raster.wcs-2.2.15/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
public class WCSConnector  {
66
	private WCSClient                         client;
67
	private Hashtable<String, WCSLayerNode>   coverages;
68
    private WCSLayerNode[]                    layerList;
69
    
70
    public WCSConnector(URL url) throws ConnectException, IOException {
71
    	client = new WCSClient(url.toString());
72
    }
73

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

  
82
	/**
83
	 * Sets the server that we want to connect to.
84
	 *
85
	 * @param host
86
	 * @throws IOException
87
	 */
88
	public void setHost(String host) throws IOException{
89
		client = new WCSClient(host);
90
	}
91

  
92

  
93
	/**
94
	 * Returns a human-readable string containing the server's name.
95
	 *
96
	 * @return String
97
	 */
98
	public String getLabel() {
99
		return client.getServiceTitle();
100
	}
101

  
102
	/**
103
	 * Returns a string containing the server's WCS version number.
104
	 *
105
	 * @return String
106
	 */
107
	public String getVersion(){
108
		return client.getVersion();
109
	}
110

  
111
	/**
112
	 * <p>
113
	 * Returns name and description of the server. It is supposed to be used
114
	 * as the source of the abstract field in your application's interface.
115
	 * </p>
116
	 * <p>
117
	 * Devuelve nombre y descripci?n (abstract) del servidor.
118
	 * </p>
119
	 * @return String
120
	 */
121
	public String getDescription(){
122
		return client.getDescription();
123
	}
124

  
125
	/**
126
	 * Returns the layer descriptor for a given coverage name.
127
	 * @param layerName
128
	 * @return WCSLayer
129
	 */
130
	public WCSLayerNode getLayer(String layerName) {
131
		getLayerList();
132
		return (WCSLayerNode) getCoverages().get(layerName);
133
	}
134
	
135
	private Hashtable<String, WCSLayerNode> getCoverages() {
136
		if(coverages == null || coverages.isEmpty()) {
137
			getLayerList();
138
		}
139
		return coverages;
140
	}
141

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

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

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

  
170
				// title
171
				lyr.setTitle(cov.getTitle());
172

  
173
				// description
174
				lyr.setDescription(cov.getAbstract());
175

  
176
				// srs
177
				lyr.addAllSrs(cov.getAllSrs());
178

  
179
				// native srs
180
				lyr.setNativeSRS(cov.getNativeSRS());
181

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

  
199
				// formats
200
				lyr.setFormats(cov.getFormats());
201

  
202
				// time positions
203
				lyr.setTimePositions(cov.getTimePositions());
204
				
205
				RectifiedGrid rf = cov.getRectifiedGrid();
206
				if(rf != null){
207
					int w = rf.getHighGridEnvelopLimits()[0][0] - rf.getLowGridEnvelopLimits()[0][0];
208
					int h = rf.getHighGridEnvelopLimits()[0][1] - rf.getLowGridEnvelopLimits()[0][1];
209
					
210
					lyr.setWidth(w);
211
					lyr.setHeight(h);
212
				}
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 (getCoverages().containsKey(coverageName)) {
297
			return ((WCSLayerNode) getCoverages().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 (getCoverages().containsKey(coverageName)) {
309
			return ((WCSLayerNode) getCoverages().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 (getCoverages().containsKey(coverageName)) {
321
			return ((WCSLayerNode) getCoverages().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 (getCoverages().containsKey(coverageName)) {
333
			return ((WCSLayerNode) getCoverages().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 (getCoverages().containsKey(coverageName)) {
345
			return ((WCSLayerNode) getCoverages().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 (getCoverages().containsKey(coverageName)) {
358
			return ((WCSLayerNode) getCoverages().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("WCS: error downloading the file. File:" + file.getAbsolutePath() + "...." + e.getMessage(),e);
394
		} catch (ServerErrorException e) {
395
			throw new RemoteServiceException("WCS Unexpected server error."+e.getMessage(),e);
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/org.gvsig.raster.wcs-2.2.15/org.gvsig.raster.wcs.io/src/main/java/org/gvsig/raster/wcs/io/WCSProvider.java
1
package org.gvsig.raster.wcs.io;
2

  
3
import java.awt.Rectangle;
4
import java.awt.geom.AffineTransform;
5
import java.awt.geom.NoninvertibleTransformException;
6
import java.awt.geom.Point2D;
7
import java.awt.geom.Rectangle2D;
8
import java.io.File;
9
import java.io.IOException;
10
import java.net.URL;
11
import java.util.ArrayList;
12
import java.util.Hashtable;
13

  
14
import org.apache.commons.lang3.StringUtils;
15
import org.cresques.cts.IProjection;
16
import org.gvsig.fmap.dal.DALLocator;
17
import org.gvsig.fmap.dal.DataStore;
18
import org.gvsig.fmap.dal.DataStoreParameters;
19
import org.gvsig.fmap.dal.coverage.RasterLocator;
20
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
21
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
22
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
23
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
24
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
25
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
26
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
27
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
28
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
29
import org.gvsig.fmap.dal.coverage.exception.QueryException;
30
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
31
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
32
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
33
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
34
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
35
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
36
import org.gvsig.fmap.dal.exception.InitializeException;
37
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
38
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
39
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
40
import org.gvsig.metadata.MetadataLocator;
41
import org.gvsig.raster.cache.tile.provider.TileServer;
42
import org.gvsig.raster.impl.buffer.DefaultRasterQuery;
43
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
44
import org.gvsig.raster.impl.datastruct.BandListImpl;
45
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
46
import org.gvsig.raster.impl.datastruct.ExtentImpl;
47
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
48
import org.gvsig.raster.impl.provider.RasterProvider;
49
import org.gvsig.raster.impl.provider.RemoteRasterProvider;
50
import org.gvsig.raster.impl.store.DefaultRasterStore;
51
import org.gvsig.raster.impl.store.DefaultStoreFactory;
52
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
53
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
54
import org.gvsig.raster.impl.store.properties.RemoteDataStoreStatistics;
55
import org.gvsig.raster.impl.store.properties.RemoteStoreHistogram;
56
import org.gvsig.raster.util.DefaultProviderServices;
57
import org.gvsig.raster.wcs.io.downloader.WCSTileServer;
58
import org.gvsig.remoteclient.wcs.WCSStatus;
59
import org.gvsig.tools.ToolsLocator;
60
/**
61
 * Clase que representa al driver de acceso a datos de wcs.
62
 *
63
 * @author Nacho Brodin (nachobrodin@gmail.com)
64
 */
65
public class WCSProvider extends AbstractRasterProvider implements RemoteRasterProvider {
66
	public static String                NAME                     = "Wcs Store";
67
	public static String                DESCRIPTION              = "Wcs Raster file";
68
	public static final String          METADATA_DEFINITION_NAME = "WcsStore";
69

  
70
	private Extent                      viewRequest              = null;
71
	private static Hashtable<URL, WCSConnector>    
72
	drivers                  = new Hashtable<URL, WCSConnector> ();
73
	private boolean                     open                     = false;
74
	private DataStoreTransparency       fileTransparency         = null;
75
	private File                        lastRequest              = null;
76
	private AbstractRasterProvider      lastRequestProvider      = null; 
77

  
78
	public static void register() {
79
		DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
80
		if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
81
			dataman.registerStoreProvider(NAME,
82
					WCSProvider.class, WCSDataParametersImpl.class);
83
		}
84

  
85
		if (!dataman.getExplorerProviders().contains(NAME)) {
86
			dataman.registerExplorerProvider(NAME, WCSServerExplorer.class, WCSServerExplorerParameters.class);
87
		}
88
		dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
89
	}
90

  
91
	public WCSProvider() throws NotSupportedExtensionException {
92
		super();
93
	}
94

  
95
	/**
96
	 * Constructor. Abre el dataset.
97
	 * @param proj Proyecci?n
98
	 * @param fName Nombre del fichero
99
	 * @throws NotSupportedExtensionException
100
	 */
101
	public WCSProvider(String params) throws InitializeException {
102
		super(params);
103
		if(params instanceof String) {
104
			WCSDataParametersImpl p = new WCSDataParametersImpl();
105
			p.setURI((String)params);
106
			super.init(p, null, ToolsLocator.getDynObjectManager()
107
					.createDynObject(
108
							MetadataLocator.getMetadataManager().getDefinition(
109
									DataStore.METADATA_DEFINITION_NAME)));
110
			init(p, null);
111
		}
112
	}
113

  
114
	public WCSProvider(WCSDataParametersImpl params,
115
			DataStoreProviderServices storeServices) throws InitializeException {
116
		super(params, storeServices, ToolsLocator.getDynObjectManager()
117
				.createDynObject(
118
						MetadataLocator.getMetadataManager().getDefinition(
119
								DataStore.METADATA_DEFINITION_NAME)));
120
		init(params, storeServices);
121
	}
122

  
123
	/**
124
	 * Gets the connector from the URL
125
	 * @return
126
	 * @throws RemoteServiceException
127
	 */
128
	public WCSConnector getConnector() throws RemoteServiceException {
129
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
130
		URL url = null;
131
		try {
132
			url = new URL(p.getURI());
133
		} catch (Exception e) {
134
			throw new RemoteServiceException("Malformed URL",e);
135
		}
136
		try {
137
			return WCSProvider.getConnectorFromURL(url);
138
		} catch (IOException e) {
139
			throw new RemoteServiceException("Error getting the connector",e);
140
		}
141
	}
142

  
143
	/**
144
	 * Crea las referencias al fichero y carga
145
	 * las estructuras con la informaci?n y los metadatos.
146
	 * @param proj Proyecci?n
147
	 * @param param Parametros de carga
148
	 * @throws NotSupportedExtensionException
149
	 * @throws RasterDriverException 
150
	 */
151
	public void init (DataStoreParameters params,
152
			DataStoreProviderServices storeServices) throws InitializeException {
153
		setParam(storeServices, params);
154
		open = true;
155
		try {
156
			loadInitialInfo();
157
		} catch (RasterDriverException e) {
158
			throw new InitializeException(e.getMessage(), e);
159
		}
160

  
161
		stats = new RemoteDataStoreStatistics(this);
162
	}
163

  
164
	public static final WCSConnector getConnectorFromURL(URL url) throws IOException {
165
		WCSConnector drv = (WCSConnector) drivers.get(url);
166
		if (drv == null) {
167
			drv = new WCSConnector(url);
168
			drivers.put(url, drv);
169
		}
170
		return drv;
171
	}
172

  
173
	/**
174
	 * Obtiene el objeto que contiene que contiene la interpretaci?n de
175
	 * color por banda
176
	 * @return
177
	 */
178
	public ColorInterpretation getColorInterpretation() {
179
		if(super.getColorInterpretation() == null) {
180
			ColorInterpretation colorInterpretation = new DataStoreColorInterpretation();
181
			colorInterpretation.initColorInterpretation(getBandCount());
182
			if(getBandCount() == 3) {
183
				colorInterpretation = DataStoreColorInterpretation.createRGBInterpretation();
184
			} else {
185
				for (int i = 0; i < getBandCount(); i++) {
186
					colorInterpretation.setColorInterpValue(i, DataStoreColorInterpretation.GRAY_BAND);
187
				}
188
			}
189
			setColorInterpretation(colorInterpretation);
190
		}
191
		return super.getColorInterpretation();
192
	}
193

  
194
	/**
195
	 * Gets WCS parameters
196
	 * @return
197
	 */
198
	public WCSDataParameters getParameters() {
199
		return (WCSDataParameters)parameters;
200
	}
201

  
202
	public AffineTransform getAffineTransform() {
203
		Extent e = getExtent();
204
		double resolutionX = e.width() / getWidth();
205
		double resolutionY = e.height() / getHeight();
206
		ownTransformation = new AffineTransform(
207
				resolutionX, 
208
				0, 
209
				0, 
210
				-resolutionY, 
211
				e.getULX() - (resolutionX / 2),
212
				e.getULY() - (resolutionY / 2));
213
		externalTransformation = (AffineTransform) ownTransformation.clone();
214
		return ownTransformation;
215
	}
216

  
217
	/**
218
	 * Calcula el extent en coordenadas del mundo real
219
	 * @return Extent
220
	 */
221
	public Extent getExtent() {
222
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
223
		try {
224
			p.setFormat("image/tiff");
225
			if(p.getSRSCode() == null){
226
				WCSConnector connector = WCSProvider.getConnectorFromURL(new URL(p.getURI()));
227
				ArrayList srs = connector.getSRSs(p.getCoverageName());
228
				if(!srs.isEmpty() && !StringUtils.isBlank((String)srs.get(0))){
229
					p.setSRSID((String) srs.get(0));
230
				}else{
231
					return null;
232
				}
233
			}
234
			Rectangle2D r = getConnector().getFullExtent(p.getCoverageName(), p.getSRSCode());
235
			if(r == null)
236
				return null;
237
			return new ExtentImpl(r.getX(),  r.getY() + r.getHeight(), r.getX() + r.getWidth(), r.getY());
238
		} catch (RemoteServiceException e1) {
239
			e1.printStackTrace();
240
		} catch (IOException e) {
241
			e.printStackTrace();
242
		}
243
		return null;
244
	}
245

  
246
	public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
247
		return null;
248
	}
249

  
250
	public RasterProvider load() {
251
		return this;
252
	}
253

  
254
	public boolean isOpen() {
255
		return open;
256
	}
257

  
258
	public void close() {
259
		open = false;
260
	}
261

  
262
	public Transparency getTransparency() {
263
		if(fileTransparency == null)
264
			fileTransparency = new DataStoreTransparency(getColorInterpretation());
265
		return fileTransparency;
266
	}
267

  
268
	public String translateFileName(String fileName) {
269
		return fileName;
270
	}
271

  
272
	public void setView(Extent e) {
273
		viewRequest = e;
274
	}
275

  
276
	public Extent getView() {
277
		return viewRequest;
278
	}
279

  
280
	public double getWidth() {
281
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
282
		try {
283
			return getConnector().getWidth(p.getCoverageName());
284
		} catch (RemoteServiceException e) {
285
			e.printStackTrace();
286
		}
287
		return 0;
288
	}
289

  
290
	public double getHeight() {
291
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
292
		try {
293
			return getConnector().getHeight(p.getCoverageName());
294
		} catch (RemoteServiceException e) {
295
			e.printStackTrace();
296
		}
297
		return 0;
298
	}
299

  
300
	public Object readCompleteLine(int line, int band)
301
			throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
302
		return null;
303
	}
304

  
305
	/**
306
	 * When the remote layer has fixed size this method downloads the file and return its reference. 
307
	 * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
308
	 * useful to build an histogram or calculate statistics. This represents a sample of data.
309
	 * @return
310
	 * @throws RasterDriverException
311
	 */
312
	public File getFileLayer() throws RasterDriverException {
313
		Extent e = getExtent();
314
		Rectangle2D bBox = new Rectangle2D.Double(e.getULX(), e.getLRY(), e.width(), e.height());
315
		WCSStatus wcsStatus = loadWCSStatus(bBox);
316

  
317
		return downloadFile(wcsStatus, e, (int)getWidth(), (int)getHeight());
318
	}
319

  
320
	/**
321
	 * Reads a complete block of data and returns an tridimensional array of the right type. This function is useful
322
	 * to read a file very fast without setting a view. In a WCS service when the size is fixed then it will read the
323
	 * entire image but when the source hasn't pixel size it will read a sample of data. This set of data will have
324
	 * the size defined in FIXED_SIZE. 
325
	 * 
326
	 * @param pos Posici?n donde se empieza  a leer
327
	 * @param blockHeight Altura m?xima del bloque leido
328
	 * @return Object que es un array tridimendional del tipo de datos del raster. (Bandas X Filas X Columnas)
329
	 * @throws InvalidSetViewException
330
	 * @throws FileNotOpenException
331
	 * @throws RasterDriverException
332
	 */
333
	public Object readBlock(int pos, int blockHeight, double scale) 
334
			throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
335
		File lastFile = getFileLayer();
336
		BandList bandList = new BandListImpl();
337
		for (int i = 0; i < 3; i++) {
338
			try {
339
				bandList.addBand(new DatasetBandImpl(lastFile.getPath(), pos, Buffer.TYPE_BYTE, 3));
340
			} catch (BandNotFoundInListException e1) {
341
			}
342
		}
343
		bandList.setDrawableBands(new int[]{0, 1, 2});
344

  
345
		try {
346
			lastRequestProvider = openLastRequest();
347
			return lastRequestProvider.readBlock(pos, blockHeight, scale);
348
		} catch (ProviderNotRegisteredException exc) {
349
			throw new RasterDriverException("Error building GdalDriver", exc);
350
		} catch (InitializeException exc) {
351
			throw new RasterDriverException("Error building GdalDriver", exc);
352
		}
353
	}
354

  
355
	public double getLastRequestHeight() throws RasterDriverException {
356
		if(lastRequestProvider == null) {
357
			try {
358
				lastRequestProvider = openLastRequest();
359
			} catch (ProviderNotRegisteredException e) {
360
				throw new RasterDriverException("Error building GdalDriver", e);
361
			} catch (InitializeException e) {
362
				throw new RasterDriverException("Error building GdalDriver", e);
363
			}
364
		}
365
		return lastRequestProvider.getHeight();
366
	}
367

  
368
	public double getLastRequestWidth() throws RasterDriverException {
369
		if(lastRequestProvider == null) {
370
			try {
371
				lastRequestProvider = openLastRequest();
372
			} catch (ProviderNotRegisteredException e) {
373
				throw new RasterDriverException("Error building GdalDriver", e);
374
			} catch (InitializeException e) {
375
				throw new RasterDriverException("Error building GdalDriver", e);
376
			}
377
		}
378
		return lastRequestProvider.getWidth();
379
	}
380

  
381
	public File getLastRequest() {
382
		return lastRequest;
383
	}
384

  
385
	public Buffer getBufferLastRequest() throws ProcessInterruptedException, RasterDriverException {
386
		try {
387
			lastRequestProvider = openLastRequest();
388

  
389
			/*BandList bandList = new BandListImpl();
390
			for (int i = 0; i < lastRequestProvider.getBandCount(); i++) {
391
				try {
392
					bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, Buffer.TYPE_BYTE, 3));
393
				} catch (BandNotFoundInListException e1) {
394
				}
395
			}
396
			bandList.setDrawableBands(new int[]{0, 1, 2});*/
397

  
398
			RasterQuery q = RasterLocator.getManager().createQuery();
399
			q.setAreaOfInterest(lastRequestProvider.getExtent(), 
400
					(int)lastRequestProvider.getWidth(), 
401
					(int)lastRequestProvider.getHeight());
402
			q.setAllDrawableBands();
403
			q.setAdjustToExtent(true);
404

  
405
			DefaultRasterStore store = new DefaultRasterStore();
406
			store.setProvider(lastRequestProvider);
407
			return store.query(q);
408
		} catch (ProviderNotRegisteredException e) {
409
			throw new RasterDriverException("Error building GdalDriver", e);
410
		} catch (InitializeException e) {
411
			throw new RasterDriverException("Error building GdalDriver", e);
412
		} catch (QueryException e) {
413
			throw new RasterDriverException("Error reading data", e);
414
		}
415
	}
416

  
417
	/**
418
	 * Opens the last request downloaded
419
	 * @return
420
	 * @throws ProviderNotRegisteredException
421
	 * @throws InitializeException
422
	 * @throws RasterDriverException
423
	 */
424
	private AbstractRasterProvider openLastRequest() throws ProviderNotRegisteredException, InitializeException, RasterDriverException {
425
		if(lastRequestProvider != null)
426
			lastRequestProvider.close();
427
		File lastFile = getFileLayer();
428
		lastRequestProvider = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
429
		return lastRequestProvider;
430
	}
431

  
432
	public Object getData(int x, int y, int band)
433
			throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
434
		int w = 25;
435
		int h = 25;
436

  
437
		Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
438
		Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
439
		Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
440

  
441
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
442
		WCSStatus wcsStatus = new WCSStatus();
443
		wcsStatus.setCoveraName(p.getCoverageName());
444
		wcsStatus.setSrs(p.getSRSCode());
445
		wcsStatus.setFormat(p.getFormat());
446
		wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
447
		wcsStatus.setExtent(bBox);
448
		wcsStatus.setHeight(h);
449
		wcsStatus.setWidth(w);
450
		wcsStatus.setDepth(p.getDepth());
451
		wcsStatus.setParameters(p.getParameter());
452
		wcsStatus.setTime(p.getTime());
453

  
454
		lastRequest = downloadFile(wcsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), w, h);
455

  
456
		AbstractRasterProvider driver = null;
457
		try {
458
			driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
459
			/*Buffer buf = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], w, h, getBandCount(), true);
460
			BandList bandList = new BandListImpl();
461
			int[] drawable = new int[getBandCount()];
462
			for (int i = 0; i < getBandCount(); i++) {
463
				try {
464
					bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, getDataType()[i], getBandCount()));
465
					drawable[i] = i;
466
				} catch (BandNotFoundInListException e1) {
467
				}
468
			}
469
			bandList.setDrawableBands(drawable);*/
470

  
471
			RasterQuery q = RasterLocator.getManager().createQuery();
472
			Rectangle r = new Rectangle(0, 0, 25, 25);
473
			q.setAreaOfInterest(r);
474
			q.setAllDrawableBands();
475
			DefaultRasterStore store = new DefaultRasterStore();
476
			store.setProvider(driver);
477

  
478
			Buffer buf = store.query(q);
479
			driver.close();
480
			if(buf.getDataType() == Buffer.TYPE_BYTE) {
481
				return new Integer(buf.getElemByte(0, 0, band));
482
			}
483
			if(buf.getDataType() == Buffer.TYPE_SHORT) {
484
				return new Integer(buf.getElemShort(0, 0, band));
485
			}
486
			if(buf.getDataType() == Buffer.TYPE_INT) {
487
				return new Integer(buf.getElemInt(0, 0, band));
488
			}
489
			if(buf.getDataType() == Buffer.TYPE_FLOAT) {
490
				return new Float(buf.getElemFloat(0, 0, band));
491
			}
492
			if(buf.getDataType() == Buffer.TYPE_DOUBLE) {
493
				return new Double(buf.getElemDouble(0, 0, band));
494
			}
495
		} catch(InitializeException e) {
496
			throw new RasterDriverException("", e);
497
		} catch (ProviderNotRegisteredException e) {
498
			throw new RasterDriverException("", e);
499
		} catch (ProcessInterruptedException e) {
500
		} catch (QueryException e) {
501
			throw new RasterDriverException("", e);
502
		}
503
		return null;
504
	}
505

  
506
	/**
507
	 * Gets the georeferencing file name form a raster file
508
	 * @param file
509
	 * a raster file
510
	 * @return
511
	 * a georeferencing file
512
	 */
513
	private String getWorldFile(String file){		
514
		String worldFile = file;
515
		int index = file.lastIndexOf(".");
516
		if (index > 0) {			
517
			worldFile = file.substring(0, index) + getExtensionWorldFile();
518
		} else {
519
			worldFile = file + getExtensionWorldFile();
520
		}
521
		return worldFile;
522
	}
523

  
524
	/**
525
	 * Obtiene la extensi?n del fichero de georreferenciaci?n
526
	 * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
527
	 * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
528
	 */
529
	private String getExtensionWorldFile() {
530
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
531
		String extWorldFile = ".wld";
532
		if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
533
			extWorldFile = ".tfw";
534
		}
535
		return extWorldFile;
536
	}
537

  
538
	private WCSStatus loadWCSStatus(Rectangle2D bBox) {
539
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
540
		WCSStatus wcsStatus = new WCSStatus();
541
		wcsStatus.setCoveraName(p.getCoverageName());
542
		wcsStatus.setSrs(p.getSRSCode());
543
		wcsStatus.setFormat(p.getFormat());
544
		wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
545
		wcsStatus.setExtent(bBox);
546
		wcsStatus.setHeight(p.getHeight());
547
		wcsStatus.setWidth(p.getWidth());
548
		wcsStatus.setDepth(p.getDepth());
549
		wcsStatus.setParameters(p.getParameter());
550
		wcsStatus.setTime(p.getTime());
551
		return wcsStatus;
552
	}
553

  
554
	public boolean needEnhanced() {
555
		return (getDataType()[0] != Buffer.TYPE_BYTE || 
556
				(getBandCount() == 1 && getDataType()[0] == Buffer.TYPE_BYTE));
557
	}
558

  
559
	/**
560
	 * This function downloads the file and creates the georeferencing file
561
	 * @param wcsStatus
562
	 * @param ulx
563
	 * @param uly
564
	 * @param lrx
565
	 * @param lry
566
	 * @param w
567
	 * @param h
568
	 * @return
569
	 * @throws RasterDriverException
570
	 */
571
	private File downloadFile(WCSStatus wcsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
572
		Extent extent = new ExtentImpl(ulx, uly, lrx, lry);
573
		return downloadFile(wcsStatus, extent, w, h);
574
	}
575

  
576
	/**
577
	 * This function downloads the file and creates the georeferencing file
578
	 * @param wcsStatus
579
	 * @param ulx
580
	 * @param uly
581
	 * @param lrx
582
	 * @param lry
583
	 * @param w
584
	 * @param h
585
	 * @return
586
	 * @throws RasterDriverException
587
	 */
588
	private File downloadFile(WCSStatus wcsStatus, Extent extent, int w, int h) throws RasterDriverException {
589
		try {
590
			lastRequest = getConnector().getCoverage(wcsStatus, ((WCSDataParametersImpl)parameters).getCancellable());
591
		} catch (RemoteServiceException e) {
592
			throw new RasterDriverException(e.getMessage(), e);
593
		}
594

  
595
		String nameWorldFile = getWorldFile(lastRequest.getPath());
596
		try {
597
			fileUtil.createWorldFile(nameWorldFile, extent, w, h);
598
		} catch (IOException e) {
599
			throw new RasterDriverException("Error downloading file", e);
600
		}
601

  
602
		return lastRequest;
603
	}
604

  
605
	/**
606
	 * Assigns the list of bands RGB and read a window of data
607
	 * @param rasterBuf
608
	 * @param bandList
609
	 * @param lastFile
610
	 * @param ulx
611
	 * @param uly
612
	 * @param lrx
613
	 * @param lry
614
	 * @return
615
	 * @throws RasterDriverException
616
	 * @throws ProcessInterruptedException
617
	 */
618
	public Buffer getBuffer(BandList bandList, File lastFile, 
619
			double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
620
		try {
621
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
622
			/*String serverName = bandList.getBand(0).getFileName();
623
			for (int i = 0; i < bandList.getBandCount(); i++) {
624
				bandList.getBand(i).setFileName(lastFile.getPath());
625
			}*/
626

  
627
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
628

  
629
			RasterQuery q = RasterLocator.getManager().createQuery();
630
			q.setAreaOfInterest(new ExtentImpl(ulx, uly, lrx, lry));
631
			q.setDrawableBands(bandList.getDrawableBands());
632
			DefaultRasterStore store = new DefaultRasterStore();
633
			store.setProvider(driver);
634
			Buffer buf = store.query(q);
635

  
636
			/*for (int i = 0; i < bandList.getBandCount(); i++) {
637
				bandList.getBand(i).setFileName(serverName);
638
			}*/
639

  
640
			return buf;
641
		} catch (ProviderNotRegisteredException e) {
642
			throw new RasterDriverException("Error building GdalDriver", e);
643
		} catch (InitializeException e) {
644
			throw new RasterDriverException("Error building GdalDriver", e);
645
		} catch (QueryException e) {
646
			throw new RasterDriverException("Error reading data", e);
647
		}
648
	}
649

  
650
	@Override
651
	public void loadBuffer(SpiRasterQuery query)
652
			throws ProcessInterruptedException, RasterDriverException {
653
		Extent ex = query.getAdjustedRequestBoundingBox();
654
		WCSStatus wcsStatus = loadWCSStatus(ex.toRectangle2D());
655

  
656
		lastRequest = downloadFile(
657
				wcsStatus, 
658
				ex, 
659
				query.getAdjustedBufWidth(), 
660
				query.getAdjustedBufHeight());
661

  
662
		if (lastRequest == null) {
663
			return;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff