Revision 2210

View differences:

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

  
41
import org.gvsig.compat.net.ICancellable;
42
import org.gvsig.fmap.dal.DALLocator;
43
import org.gvsig.fmap.dal.DataManager;
44
import org.gvsig.fmap.dal.DataServerExplorerParameters;
45
import org.gvsig.fmap.dal.DataStoreParameters;
46
import org.gvsig.fmap.dal.NewDataStoreParameters;
47
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
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 DataServerExplorerProvider {
60
	public static final String          NAME                     = "WCSRemoteServerExplorer";
61
	private WCSConnector                connector                = null;
62
	private WCSServerExplorerParameters parameters               = null;
63
	
64
	public WCSServerExplorer(
65
			WCSServerExplorerParameters parameters,
66
			DataServerExplorerProviderServices services)
67
			throws InitializeException {
68
		this.parameters = parameters;
69
	}
70
	
71
	/**
72
	 * Gets the provider's name
73
	 * @return
74
	 */
75
	public String getDataStoreProviderName() {
76
		return WCSProvider.NAME;
77
	}
78
	
79
	/*
80
	 * (non-Javadoc)
81
	 * @see org.gvsig.fmap.dal.coverage.store.remote.RemoteServerExplorerProvider#getDescription()
82
	 */
83
	public String getDescription() {
84
		return WCSProvider.DESCRIPTION;
85
	}
86
	
87
	public DataStoreParameters getStoreParameters() {
88
		DataManager manager = DALLocator.getDataManager();
89
		WCSDataParametersImpl params = null;
90
		try {
91
			params = (WCSDataParametersImpl) manager.createStoreParameters(this.getDataStoreProviderName());
92

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

  
108
	public boolean add(String provider, NewDataStoreParameters parameters,
109
			boolean overwrite) throws DataException {
110
		return false;
111
	}
112

  
113
	public boolean canAdd() {
114
		return false;
115
	}
116

  
117
	public boolean canAdd(String storeName) throws DataException {
118
		return false;
119
	}
120

  
121
	public NewDataStoreParameters getAddParameters(String storeName)
122
			throws DataException {
123
		return null;
124
	}
125

  
126
	public List getDataStoreProviderNames() {
127
		return null;
128
	}
129

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

  
138
	public List list() throws DataException {
139
		return null;
140
	}
141

  
142
	public List list(int mode) throws DataException {
143
		return null;
144
	}
145

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

  
150
	public void dispose() {
151
		
152
	}
153

  
154
	public String getProviderName() {
155
		return null;
156
	}
157
	
158
	/**
159
	 * Gets the online resources
160
	 * @return
161
	 */
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
	 * Checks if the network and host are reachable
199
	 * @param timeout for the host
200
	 * @return true if both are reachable and false if they are not
201
	 */
202
	public boolean isHostReachable(int timeout) {
203
		URL url = null;
204
		try {
205
			url = new URL(parameters.getHost());
206
			URLConnection con = url.openConnection();
207
			if(con == null)
208
				return false;
209
			con.connect();
210
			InputStream stream = con.getInputStream();
211
			if(stream == null)
212
				return false;
213
		} catch (MalformedURLException e) {
214
			return false;
215
		} catch (IOException e) {
216
			return false;
217
		}
218
		
219
		return true;
220
	}
221

  
222
	/**
223
	 * Checks if the network and host are reachable
224
	 * @return true if both are reachable and false if they are not
225
	 */
226
	public boolean isHostReachable() {
227
		int timeout = 10000;
228
		return isHostReachable(timeout);
229
	}
230

  
231
	/**
232
	 * Returns true if this provider is connected to the server
233
	 * @return
234
	 */
235
	public boolean isConnected() {
236
		if(connector != null)
237
			return true;
238
		return false;
239
	}
240

  
241
	/**
242
	 * Gets the description of this service
243
	 * @return
244
	 */
245
	public String getAbstract() {
246
		if(connector != null)
247
			return connector.getDescription();
248
		return null;
249
	}
250

  
251
	/**
252
	 * Gets the server title
253
	 * @return
254
	 */
255
	public String getServerType() {
256
		if (getVersion() == null) 
257
			return "WCS";
258
        return "WCS "+ getVersion();
259
	}
260

  
261
	/**
262
	 * Gets the protocol supported by the server
263
	 * @return
264
	 */
265
	public String getVersion() {
266
		if(connector != null) {
267
			return (connector.getVersion() == null) ? "" : connector.getVersion();
268
		}
269
		return null;
270
	}
271

  
272
	/**
273
	 * Gets the host URI
274
	 * @return
275
	 */
276
	public String getHost() {
277
		return parameters.getHost();
278
	}
279
	
280
	/**
281
	 * Gets the title
282
	 * @return
283
	 */
284
	public String getTitle() {
285
		return null;
286
	}
287

  
288
	public DataServerExplorerProviderServices getServerExplorerProviderServices() {
289
		// TODO Auto-generated method stub
290
		return null;
291
	}
292

  
293
	/*
294
	 * (non-Javadoc)
295
	 * @see org.gvsig.fmap.dal.coverage.explorer.WCSServerExplorer#getMaxResolution(java.lang.String)
296
	 */
297
	public Point2D getMaxResolution(String layerName) {
298
		return connector.getMaxResolution(layerName);
299
	}
300

  
301
	/**
302
	 * Gets the coverage list
303
	 * @return
304
	 */
305
	public WCSLayerNode[] getCoverageList() {
306
		return connector.getLayerList();
307
	}
308
	
309
	/**
310
	 * Gets a layer searching by its name 
311
	 * @return
312
	 */
313
	public WCSLayerNode getCoverageByName(String name) {
314
		WCSLayerNode[] list = getCoverageList();
315
		for (int i = 0; i < list.length; i++) {
316
			if(list[i].getName().compareTo(name) == 0)
317
				return list[i];
318
		}
319
		return null;
320
	}
321
}
0 322

  
org.gvsig.raster.wcs/tags/tagdate_11102013_11_26/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/tagdate_11102013_11_26/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
	public AffineTransform getAffineTransform() {
224
		Extent e = getExtent();
225
		double resolutionX = e.width() / getWidth();
226
		double resolutionY = e.height() / getHeight();
227
		ownTransformation = new AffineTransform(
228
				resolutionX, 
229
				0, 
230
				0, 
231
				-resolutionY, 
232
				e.getULX() - (resolutionX / 2),
233
				e.getULY() - (resolutionY / 2));
234
		externalTransformation = (AffineTransform) ownTransformation.clone();
235
		return ownTransformation;
236
	}
237
	
238
	/**
239
	 * Calcula el extent en coordenadas del mundo real
240
	 * @return Extent
241
	 */
242
	public Extent getExtent() {
243
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
244
		try {
245
			Rectangle2D r = getConnector().getFullExtent(p.getCoverageName(), p.getSRSCode());
246
			if(r == null)
247
				return null;
248
			return new ExtentImpl(r.getX(),  r.getY() + r.getHeight(), r.getX() + r.getWidth(), r.getY());
249
		} catch (RemoteServiceException e1) {
250
			e1.printStackTrace();
251
		} catch (IOException e) {
252
			e.printStackTrace();
253
		}
254
		return null;
255
	}
256

  
257
	public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
258
		return null;
259
	}
260

  
261
	public RasterProvider load() {
262
		return this;
263
	}
264
	
265
	public boolean isOpen() {
266
		return open;
267
	}
268

  
269
	public void close() {
270
		open = false;
271
	}
272
	
273
	public Transparency getTransparency() {
274
		if(fileTransparency == null)
275
			fileTransparency = new DataStoreTransparency();
276
		return fileTransparency;
277
	}
278

  
279
	public String translateFileName(String fileName) {
280
		return fileName;
281
	}
282

  
283
	public void setView(Extent e) {
284
		viewRequest = e;
285
	}
286

  
287
	public Extent getView() {
288
		return viewRequest;
289
	}
290
	
291
	public double getWidth() {
292
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
293
		try {
294
			return getConnector().getWidth(p.getCoverageName());
295
		} catch (RemoteServiceException e) {
296
			e.printStackTrace();
297
		}
298
		return 0;
299
	}
300

  
301
	public double getHeight() {
302
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
303
		try {
304
			return getConnector().getHeight(p.getCoverageName());
305
		} catch (RemoteServiceException e) {
306
			e.printStackTrace();
307
		}
308
		return 0;
309
	}
310

  
311
	public Object readCompleteLine(int line, int band)
312
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
313
		return null;
314
	}
315
	
316
	/**
317
	 * When the remote layer has fixed size this method downloads the file and return its reference. 
318
	 * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
319
	 * useful to build an histogram or calculate statistics. This represents a sample of data.
320
	 * @return
321
	 * @throws RasterDriverException
322
	 */
323
	public File getFileLayer() throws RasterDriverException {
324
		Extent e = getExtent();
325
		Rectangle2D bBox = new Rectangle2D.Double(e.getULX(), e.getLRY(), e.width(), e.height());
326
		WCSStatus wcsStatus = loadWCSStatus(bBox);
327
		
328
		return downloadFile(wcsStatus, e.getULX(), e.getULY(), e.getLRX(), e.getLRY(), 
329
				(int)getWidth(), (int)getHeight());
330
	}
331

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

  
357
		try {
358
			lastRequestProvider = openLastRequest();
359
			return lastRequestProvider.readBlock(pos, blockHeight, scale);
360
		} catch (ProviderNotRegisteredException exc) {
361
			throw new RasterDriverException("Error building GdalDriver", exc);
362
		} catch (InitializeException exc) {
363
			throw new RasterDriverException("Error building GdalDriver", exc);
364
		}
365
	}
366
	
367
	public double getLastRequestHeight() throws RasterDriverException {
368
		if(lastRequestProvider == null) {
369
			try {
370
				lastRequestProvider = openLastRequest();
371
			} catch (ProviderNotRegisteredException e) {
372
				throw new RasterDriverException("Error building GdalDriver", e);
373
			} catch (InitializeException e) {
374
				throw new RasterDriverException("Error building GdalDriver", e);
375
			}
376
		}
377
		return lastRequestProvider.getHeight();
378
	}
379
	
380
	public double getLastRequestWidth() throws RasterDriverException {
381
		if(lastRequestProvider == null) {
382
			try {
383
				lastRequestProvider = openLastRequest();
384
			} catch (ProviderNotRegisteredException e) {
385
				throw new RasterDriverException("Error building GdalDriver", e);
386
			} catch (InitializeException e) {
387
				throw new RasterDriverException("Error building GdalDriver", e);
388
			}
389
		}
390
		return lastRequestProvider.getWidth();
391
	}
392
	
393
	public File getLastRequest() {
394
		return lastRequest;
395
	}
396
	
397
	public Buffer getBufferLastRequest() throws ProcessInterruptedException, RasterDriverException {
398
		try {
399
			lastRequestProvider = openLastRequest();
400
			
401
			BandList bandList = new BandListImpl();
402
			for (int i = 0; i < lastRequestProvider.getBandCount(); i++) {
403
				try {
404
					bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, Buffer.TYPE_BYTE, 3));
405
				} catch (BandNotFoundInListException e1) {
406
				}
407
			}
408
			bandList.setDrawableBands(new int[]{0, 1, 2});
409
			Buffer newBuffer = DefaultRasterManager.getInstance().createBuffer(lastRequestProvider.getDataType()[0], (int)lastRequestProvider.getWidth(), (int)lastRequestProvider.getHeight(), lastRequestProvider.getBandCount(), true);
410
			
411
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
412
			q.setAreaOfInterest(lastRequestProvider.getExtent(), 
413
					(int)lastRequestProvider.getWidth(), 
414
					(int)lastRequestProvider.getHeight());
415
			q.setBandList(bandList);
416
			q.setBuffer(newBuffer);
417
			q.setAdjustToExtent(true);
418
			
419
			return lastRequestProvider.getDataSet(q);
420
		} catch (ProviderNotRegisteredException e) {
421
			throw new RasterDriverException("Error building GdalDriver", e);
422
		} catch (InitializeException e) {
423
			throw new RasterDriverException("Error building GdalDriver", e);
424
		}
425
	}
426
	
427
	/**
428
	 * Opens the last request downloaded
429
	 * @return
430
	 * @throws ProviderNotRegisteredException
431
	 * @throws InitializeException
432
	 * @throws RasterDriverException
433
	 */
434
	private DefaultRasterProvider openLastRequest() throws ProviderNotRegisteredException, InitializeException, RasterDriverException {
435
		if(lastRequestProvider != null)
436
			lastRequestProvider.close();
437
		File lastFile = getFileLayer();
438
		lastRequestProvider = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
439
		return lastRequestProvider;
440
	}
441

  
442
	public Object getData(int x, int y, int band)
443
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
444
		int w = 25;
445
		int h = 25;
446
		
447
		Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
448
		Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
449
		Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
450
		
451
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
452
		WCSStatus wcsStatus = new WCSStatus();
453
		wcsStatus.setCoveraName(p.getCoverageName());
454
		wcsStatus.setSrs(p.getSRSCode());
455
		wcsStatus.setFormat(p.getFormat());
456
		wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
457
		wcsStatus.setExtent(bBox);
458
		wcsStatus.setHeight(h);
459
		wcsStatus.setWidth(w);
460
		wcsStatus.setDepth(p.getDepth());
461
		wcsStatus.setParameters(p.getParameter());
462
		wcsStatus.setTime(p.getTime());
463
		
464
		lastRequest = downloadFile(wcsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), w, h);
465
		
466
		DefaultRasterProvider driver = null;
467
		try {
468
			driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
469
			Buffer buf = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], w, h, getBandCount(), true);
470
			BandList bandList = new BandListImpl();
471
			int[] drawable = new int[getBandCount()];
472
			for (int i = 0; i < getBandCount(); i++) {
473
				try {
474
					bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, getDataType()[i], getBandCount()));
475
					drawable[i] = i;
476
				} catch (BandNotFoundInListException e1) {
477
				}
478
			}
479
			bandList.setDrawableBands(drawable);
480
			
481
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
482
			q.setAreaOfInterest(0, 0, 25, 25);
483
			q.setBandList(bandList);
484
			q.setBuffer(buf);
485
			buf = driver.getDataSet(q);
486
			driver.close();
487
			if(buf.getDataType() == Buffer.TYPE_BYTE) {
488
				return new Integer(buf.getElemByte(0, 0, band));
489
			}
490
			if(buf.getDataType() == Buffer.TYPE_SHORT) {
491
				return new Integer(buf.getElemShort(0, 0, band));
492
			}
493
			if(buf.getDataType() == Buffer.TYPE_INT) {
494
				return new Integer(buf.getElemInt(0, 0, band));
495
			}
496
			if(buf.getDataType() == Buffer.TYPE_FLOAT) {
497
				return new Float(buf.getElemFloat(0, 0, band));
498
			}
499
			if(buf.getDataType() == Buffer.TYPE_DOUBLE) {
500
				return new Double(buf.getElemDouble(0, 0, band));
501
			}
502
		} catch(InitializeException e) {
503
			throw new RasterDriverException("", e);
504
		} catch (ProviderNotRegisteredException e) {
505
			throw new RasterDriverException("", e);
506
		} catch (ProcessInterruptedException e) {
507
		}
508
		return null;
509
	}
510
	
511
	/**
512
	 * Gets the georeferencing file name form a raster file
513
	 * @param file
514
	 * a raster file
515
	 * @return
516
	 * a georeferencing file
517
	 */
518
	private String getWorldFile(String file){		
519
		String worldFile = file;
520
		int index = file.lastIndexOf(".");
521
		if (index > 0) {			
522
			worldFile = file.substring(0, index) + getExtensionWorldFile();
523
		} else {
524
			worldFile = file + getExtensionWorldFile();
525
		}
526
		return worldFile;
527
	}
528
	
529
	/**
530
	 * Obtiene la extensi?n del fichero de georreferenciaci?n
531
	 * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
532
	 * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
533
	 */
534
	private String getExtensionWorldFile() {
535
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
536
		String extWorldFile = ".wld";
537
		if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
538
			extWorldFile = ".tfw";
539
		}
540
		return extWorldFile;
541
	}
542
	
543
	private WCSStatus loadWCSStatus(Rectangle2D bBox) {
544
		WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
545
		WCSStatus wcsStatus = new WCSStatus();
546
		wcsStatus.setCoveraName(p.getCoverageName());
547
		wcsStatus.setSrs(p.getSRSCode());
548
		wcsStatus.setFormat(p.getFormat());
549
		wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
550
		wcsStatus.setExtent(bBox);
551
		wcsStatus.setHeight(p.getHeight());
552
		wcsStatus.setWidth(p.getWidth());
553
		wcsStatus.setDepth(p.getDepth());
554
		wcsStatus.setParameters(p.getParameter());
555
		wcsStatus.setTime(p.getTime());
556
		return wcsStatus;
557
	}
558
	
559
	public boolean needEnhanced() {
560
		return (getDataType()[0] != Buffer.TYPE_BYTE || 
561
				(getBandCount() == 1 && getDataType()[0] == Buffer.TYPE_BYTE));
562
	}
563
	
564
	/**
565
	 * This function downloads the file and creates the georeferencing file
566
	 * @param wcsStatus
567
	 * @param ulx
568
	 * @param uly
569
	 * @param lrx
570
	 * @param lry
571
	 * @param w
572
	 * @param h
573
	 * @return
574
	 * @throws RasterDriverException
575
	 */
576
	private File downloadFile(WCSStatus wcsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
577
		try {
578
			lastRequest = getConnector().getCoverage(wcsStatus, ((WCSDataParametersImpl)parameters).getCancellable());
579
		} catch (RemoteServiceException e) {
580
			throw new RasterDriverException(e.getMessage(), e);
581
		}
582
		
583
		String nameWorldFile = getWorldFile(lastRequest.getPath());
584
		try {
585
			fileUtil.createWorldFile(nameWorldFile, new ExtentImpl(ulx, uly, lrx, lry), w, h);
586
		} catch (IOException e) {
587
			throw new RasterDriverException("Error downloading file", e);
588
		}
589

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

  
639
		Buffer raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], bufWidth, bufHeight, 3, true);
640
		getWindow(ex, bufWidth, bufHeight, bandList, raster, true, null);
641
		raster.setDataExtent(ex.toRectangle2D());
642

  
643
		TileCacheManager m = TileCacheLocator.getManager();
644
		org.gvsig.raster.cache.tile.Tile t = m.createTile(-1, 0, 0);
645
		t.setData(new Object[]{raster});
646
		t.setUl(new Point2D.Double(ex.getULX(), ex.getULY()));
647
		t.setLr(new Point2D.Double(ex.getLRX(), ex.getLRY()));
648
		t.setDownloaderParams("AffineTransform", getAffineTransform());
649
		t.setDownloaderParams("Tiling", new Boolean(false));
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff