Revision 9598

View differences:

org.gvsig.raster.wms/tags/org.gvsig.raster.wms-2.2.83/org.gvsig.raster.wms.io/src/main/java/org/gvsig/raster/wms/io/WMSConnector.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.wms.io;
23

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

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

  
50
import org.cresques.cts.ICoordTrans;
51
import org.cresques.cts.IProjection;
52
import org.gvsig.compat.net.ICancellable;
53
import org.gvsig.fmap.crs.CRSFactory;
54
import org.gvsig.fmap.dal.DataParameters;
55
import org.gvsig.fmap.dal.DataServerExplorerParameters;
56
import org.gvsig.fmap.dal.DataStoreParameters;
57
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
58
import org.gvsig.remoteclient.exceptions.ServerErrorException;
59
import org.gvsig.remoteclient.utils.BoundaryBox;
60
import org.gvsig.remoteclient.utils.Utilities;
61
import org.gvsig.remoteclient.wms.WMSClient;
62
import org.gvsig.remoteclient.wms.WMSDimension;
63
import org.gvsig.remoteclient.wms.WMSLayer;
64
import org.gvsig.remoteclient.wms.WMSStatus;
65
import org.gvsig.remoteclient.wms.WMSStyle;
66
import org.slf4j.Logger;
67
import org.slf4j.LoggerFactory;
68

  
69

  
70
public class WMSConnector  {
71
	private WMSClient                     client;
72
    private WMSLayerNode                  fmapRootLayer;
73
    private TreeMap<String, WMSLayerNode> layers = new TreeMap<String, WMSLayerNode>();
74
    private Logger                        log    = LoggerFactory.getLogger(WMSConnector.class);
75

  
76
    public WMSConnector(URL url) throws ConnectException, IOException {
77
    	client = new WMSClient(url.toString());
78
    }
79

  
80
    public String[] getLayerNames() {
81
    	return client.getLayerNames();
82
    }
83
    
84
    public String[] getLayerTitles() {
85
    	return client.getLayerTitles();
86
    }
87
    
88
	public void getCapabilities(URL server) throws RemoteServiceException {
89
//		try {
90
//			client.connect();
91
//		} catch (Exception e) {
92
//			throw new WMSException(e);
93
//		}
94
	}
95

  
96
    public File getMap(WMSStatus status, ICancellable cancel) throws RemoteServiceException {
97
        try {
98
			return client.getMap(status, cancel);
99
        } catch (org.gvsig.remoteclient.exceptions.WMSException e) {
100
            throw new RemoteServiceException(e.getMessage());
101
        } catch (ServerErrorException e) {
102
            throw new RemoteServiceException("WMS Unexpected server error." + e.getMessage(), e);
103
        }
104
    }
105
    
106
    /**
107
     * 
108
     * @param status
109
     * @param cancel
110
     * @param file
111
     * @throws RemoteServiceException
112
     */
113
    public void getMap(WMSStatus status, ICancellable cancel, File file) throws RemoteServiceException {
114
        try {
115
			URL url = client.getGetMapURL(status, cancel);
116
			downloadFile(url, file, cancel);
117
			String exceptionMessage = client.getExceptionMessage(file);
118
			if(exceptionMessage != null)
119
				throw new RemoteServiceException(exceptionMessage);
120
		} catch(IOException e) {
121
			throw new RemoteServiceException("WMS: error downloading the file. File:" + file.getAbsolutePath() + "...." + e.getMessage());
122
		} catch (ServerErrorException e) {
123
            throw new RemoteServiceException("WMS Unexpected server error."+e.getMessage());
124
        }  catch (org.gvsig.remoteclient.exceptions.WMSException e) {
125
            throw new RemoteServiceException(e.getMessage());
126
        }
127
    }
128

  
129
    
130
    public void downloadFile(URL url, File dstFile, ICancellable cancel) throws IOException {
131
		Preferences prefs = Preferences.userRoot().node( "gvsig.downloader" );
132
		// by default 1 minute (60000 milliseconds.
133
		int timeout = prefs.getInt("timeout", 60000);
134

  
135
		DataOutputStream dos;
136
		DataInputStream is;
137
		OutputStreamWriter os = null;
138
		HttpURLConnection connection = null;
139
		//If the used protocol is HTTPS
140
		if (url.getProtocol().equals("https")) {
141
			try {
142
				disableHttsValidation();
143
			} catch (KeyManagementException e) {
144
				e.printStackTrace();
145
			} catch (NoSuchAlgorithmException e) {
146
				e.printStackTrace();
147
			}
148
		}
149
		connection = (HttpURLConnection)url.openConnection();
150
		connection.setConnectTimeout(timeout);
151
		is = new DataInputStream(url.openStream());
152

  
153
		dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(dstFile)));
154
		byte[] buffer = new byte[1024 * 4];
155

  
156

  
157
		long readed = 0;
158
		for (int i = is.read(buffer); i > 0; i = is.read(buffer)){
159
			dos.write(buffer, 0, i);
160
			readed += i;
161
			if(cancel != null && cancel.isCanceled())
162
				return;
163
		}
164
		if(os != null) {
165
			os.close();
166
		}
167
		dos.close();
168
		is.close();
169
		is = null;
170
		dos = null;
171
	}
172

  
173
	/**
174
	 * This method disables the Https certificate validation.
175
	 * @throws KeyManagementException
176
	 * @throws NoSuchAlgorithmException
177
	 */
178
	private void disableHttsValidation() throws KeyManagementException, NoSuchAlgorithmException{
179
		// Create a trust manager that does not validate certificate chains
180
		TrustManager[] trustAllCerts = new TrustManager[] {
181
				new X509TrustManager() {
182
					public java.security.cert.X509Certificate[] getAcceptedIssuers() {
183
						return null;
184
					}
185
					public void checkClientTrusted(
186
							java.security.cert.X509Certificate[] certs, String authType) {
187
					}
188
					public void checkServerTrusted(
189
							java.security.cert.X509Certificate[] certs, String authType) {
190
					}
191
				}
192
		};
193

  
194
		// Install the all-trusting trust manager
195
		SSLContext sc = SSLContext.getInstance("SSL");
196
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
197
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
198
	}
199

  
200
    /**
201
     * Gets the legend graphic of one layer
202
     */
203
    public File getLegendGraphic(WMSStatus status, String layerName, ICancellable cancel) throws RemoteServiceException {
204
        try {
205
        	File f = client.getLegendGraphic(status, layerName, cancel);
206
			return f;
207
        } catch (org.gvsig.remoteclient.exceptions.WMSException e) {
208
            //throw new RemoteServiceException(e.getMessage());
209
        } catch (ServerErrorException e) {
210
            throw new RemoteServiceException("WMS Unexpected server error."+e.getMessage());
211
        }
212
        return null;
213
    }
214

  
215
	/**
216
	 * Devuelve WMSClient a partir de su URL.
217
	 *
218
	 * @param url URL.
219
	 *
220
	 * @return WMSClient.
221
	 * @throws IOException
222
	 * @throws ConnectException
223
	 *
224
	 * @throws UnsupportedVersionException
225
	 * @throws IOException
226
	 */
227

  
228

  
229
    /**
230
     * Establishes the connection.
231
     * @param override, if true the previous downloaded data will be overridden
232
     * @return <b>true</b> if the connection was successful, or <b>false</b> if it was no possible
233
     * to establish the connection for any reason such as version negotiation.
234
     */
235
    public boolean connect(boolean override, ICancellable cancel) {
236
    	if (override) {
237
    		fmapRootLayer = null;
238
    		layers.clear();
239
    	}
240
		return client.connect(override, cancel);
241
    }
242
    
243
    /**
244
     * Establishes the connection.
245
     * @param override, if true the previous downloaded data will be overridden
246
     * @return <b>true</b> if the connection was successful, or <b>false</b> if it was no possible
247
     * to establish the connection for any reason such as version negotiation.
248
     */
249
    public boolean connect(DataServerExplorerParameters p, boolean override, ICancellable cancel) {
250
    	if (override) {
251
    		fmapRootLayer = null;
252
    		layers.clear();
253
    	}
254
    	WMSStatus status = new WMSStatus();
255
    	if (p!=null && p instanceof WMSServerExplorerParameters) {
256
    		status.setXyAxisOrder(((WMSServerExplorerParameters) p).isXyAxisOrder());
257
    	}
258

  
259
		return client.connect(status, override, cancel);
260
    }
261

  
262
    /**
263
     * 
264
     * @param cancel
265
     * @return
266
     * @deprecated Use {@link #connect(WMSServerExplorerParameters, boolean, ICancellable)}
267
     * instead
268
     */
269
    public boolean connect(ICancellable cancel) {
270
    	return client.connect(false, cancel);
271
    }
272

  
273
    /**
274
     * @return the version of this client.
275
     */
276
    public String getVersion() {
277
    	return client.getVersion();
278
    }
279

  
280
    /**
281
     * @return The title of the service offered by the WMS server.
282
     */
283
    public String getServiceTitle() {
284
		return client.getServiceInformation().title;
285
    }
286

  
287
    /**
288
     * Returns a Hash table containing the values for each online resource.
289
     * Using as key a String with name of the WMS request and the value returned
290
     * by the hash is another string containing the corresponding Url
291
     * @return HashTable
292
     */
293
	public Hashtable getOnlineResources() {
294
    	return client.getServiceInformation().getSupportedOperationsByName();
295
    }
296

  
297
    /**
298
     * @return <b>Vector</b> containing strings with the formats supported by this server.
299
     */
300
    public Vector getFormats() {
301
    	return client.getFormats();
302
    }
303
    
304
    /**
305
     * @return <b>Vector</b> containing strings with the information formats supported by this server.
306
     */
307
    public Vector getInfoFormats() {
308
    	return client.getInfoFormats();
309
    }
310

  
311
    /**
312
     * @return <b>Boolean</b> returns if the WMS is queryable (suppports GetFeatureInfo)
313
     */
314
    public boolean isQueryable() {
315
        return client.isQueryable();
316
    }
317
    /**
318
     * @return <b>Boolean</b> returns if the WMS supports getLegendGraphic operation (suppports GetFeatureInfo)
319
     */
320
    public boolean hasLegendGraphic() {
321
        return client.hasLegendGraphic();
322
    }
323
    /**
324
     * @return A tree containing the info of all layers available on this server.
325
     */
326
    public WMSLayerNode getLayersTree() {
327
        if (fmapRootLayer == null){
328
            WMSLayer clientRoot;
329
            if (client.getLayersRoot() == null) {
330
            	client.connect(false, null);
331
            }
332
            clientRoot = client.getLayersRoot();
333

  
334

  
335
            fmapRootLayer = parseTree(clientRoot, null);
336
        }
337
        return fmapRootLayer;
338
    }
339

  
340
    /**
341
     * Parses the client's layer node and translates it to a fmap's layer node
342
     * @param WMSLayer
343
     * @return WMSLayerNode
344
     */
345
    @SuppressWarnings("unchecked")
346
	private WMSLayerNode parseTree(WMSLayer node, WMSLayerNode parentNode) {
347

  
348
        WMSLayerNode myNode = new WMSLayerNode();
349

  
350
        // Name
351
        myNode.setName(node.getName());
352

  
353
        // Title
354
        myNode.setTitle(node.getTitle());
355

  
356
        // Transparency
357
        myNode.setTransparency(node.hasTransparency());
358

  
359
	// CRS
360

  
361
//        for (int i = 0; i < node.getAllSrs().size(); i++) {
362
//        	String srs = (String)node.getAllSrs().get(i);
363
//        	if(node.getBbox(srs) == null) {
364
//        		IProjection projSrc = CRSFactory.getCRS("EPSG:4326");
365
//        		try {
366
//        			IProjection projDst = CRSFactory.getCRS(srs);
367
//        			if(projDst != null) {
368
//        				try {
369
//        					ICoordTrans t = projSrc.getCT(projDst);
370
//        					Rectangle2D r = t.convert(getRectangleFromBoundaryBox(node.getLatLonBox()));
371
//        					BoundaryBox bbox = getBoundaryBoxFromRectangle(r);
372
//        					bbox.setSrs(srs);
373
//        					node.addBBox(bbox);
374
//        				} catch (Exception e) {
375
//        					log.info("I cannot get the transformation between EPSG:4326 and " + srs, e);
376
//        				}
377
//        			}
378
//        		} catch (Exception e1) {
379
//        			log.info("I cannot get " + srs, e1);
380
//        			node.removeSrs(srs);
381
//        		}
382
//        	}
383
//		}
384
        myNode.setSrs(node.getAllSrs());
385

  
386
        // Queryable
387

  
388
        myNode.setQueryable(node.isQueryable() && client.getServiceInformation().isQueryable());
389

  
390
        // Parent layer
391
        myNode.setParent(parentNode);
392

  
393
        // Abstract
394
        myNode.setAbstract(node.getAbstract());
395

  
396
        // Fixed Size
397
        myNode.setFixedSize(node.getfixedWidth(), node.getfixedHeight());
398

  
399
        // LatLonBox
400
        if (node.getLatLonBox()!=null)
401
            myNode.setLatLonBox(node.getLatLonBox().toString());
402

  
403
        // Keywords
404
        ArrayList keywords = node.getKeywords();
405
        for (int i = 0; i < keywords.size(); i++) {
406
        	myNode.addKeyword((String) keywords.get(i));
407
		}
408

  
409
        // Styles
410
        ArrayList styles = node.getStyles();
411
        for (int i = 0; i < styles.size(); i++) {
412
            WMSStyle style = (WMSStyle) styles.get(i);
413
            myNode.addStyle(style);
414
        }
415

  
416
        // Dimensions
417
        ArrayList dimensions = node.getDimensions();
418
        for (int i = 0; i < dimensions.size(); i++) {
419
            WMSDimension d = (WMSDimension) dimensions.get(i);
420
            myNode.addDimension(d.getName(), d.getUnits(), d.getUnitSymbol(), d.getDimensionExpression());
421
        }
422

  
423
        // Children
424
        int children = node.getChildren().size();
425
        myNode.setChildren(new ArrayList());
426
        for (int i = 0; i < children; i++) {
427
            myNode.getChildren().add(parseTree((WMSLayer)node.getChildren().get(i), myNode));
428
        }
429

  
430
        if (myNode.getName()!=null)
431
            layers.put(myNode.getName(), myNode);
432

  
433
        return myNode;
434
    }
435
    
436
    public Rectangle2D getRectangleFromBoundaryBox(BoundaryBox bbox) {
437
    	return new Rectangle2D.Double(bbox.getXmin(),
438
    			bbox.getYmin(),
439
    			Math.abs(bbox.getXmax() - bbox.getXmin()),
440
    			Math.abs(bbox.getYmax() - bbox.getYmin()));
441
    }
442
    
443
    public BoundaryBox getBoundaryBoxFromRectangle(Rectangle2D r) {
444
    	BoundaryBox bbox = new BoundaryBox();
445
    	bbox.setXmin(r.getMinX());
446
    	bbox.setXmax(r.getMaxX());
447
    	bbox.setYmin(r.getMinY());
448
    	bbox.setYmax(r.getMaxY());
449
    	return bbox;
450
    }
451

  
452
    public String getAbstract() {
453
    	return client.getServiceInformation().abstr;
454
    }
455

  
456
    public Rectangle2D getLayersExtent(String[] layerName, String srs) {
457
    	return client.getLayersExtent(layerName, srs);
458
    }
459

  
460
    public WMSLayerNode getLayer(String layerName) {
461
        if (getLayers().get(layerName) != null) {
462
            return (WMSLayerNode)layers.get(layerName);
463
        }
464
        return null;
465
    }
466

  
467
	private TreeMap getLayers() {
468
        if (fmapRootLayer == null){
469
            fmapRootLayer = getLayersTree();
470
        }
471
        return layers;
472
    }
473

  
474
    public String getFeatureInfo(WMSStatus _wmsStatus, int i, int j, int max_value, ICancellable cancellable) throws RemoteServiceException {
475
        try {
476
            return client.getFeatureInfo(_wmsStatus, i, j, max_value, cancellable);
477
        } catch (org.gvsig.remoteclient.exceptions.WMSException e) {
478
            throw new RemoteServiceException();
479
		}
480
    }
481

  
482
    public String getHost(){
483
    	return client.getHost();
484
    }
485
   
486
}
0 487

  
org.gvsig.raster.wms/tags/org.gvsig.raster.wms-2.2.83/org.gvsig.raster.wms.io/src/main/java/org/gvsig/raster/wms/io/WMSProvider.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.wms.io;
23

  
24
import java.awt.Image;
25
import java.awt.geom.AffineTransform;
26
import java.awt.geom.NoninvertibleTransformException;
27
import java.awt.geom.Point2D;
28
import java.awt.geom.Rectangle2D;
29
import java.io.File;
30
import java.io.IOException;
31
import java.net.URI;
32
import java.net.URISyntaxException;
33
import java.net.URL;
34
import java.util.Hashtable;
35
import java.util.List;
36
import java.util.Vector;
37

  
38
import javax.swing.ImageIcon;
39

  
40
import org.apache.commons.io.FilenameUtils;
41
import org.cresques.cts.ICoordTrans;
42
import org.cresques.cts.IProjection;
43

  
44
import org.gvsig.compat.net.ICancellable;
45
import org.gvsig.fmap.crs.CRSFactory;
46
import org.gvsig.fmap.dal.DALLocator;
47
import org.gvsig.fmap.dal.DataStore;
48
import org.gvsig.fmap.dal.DataStoreParameters;
49
import org.gvsig.fmap.dal.coverage.RasterLocator;
50
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
51
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
52
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
53
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
54
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
55
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
56
import org.gvsig.fmap.dal.coverage.exception.InfoByPointException;
57
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
58
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
59
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
60
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
61
import org.gvsig.fmap.dal.coverage.exception.QueryException;
62
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
63
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
64
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
65
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
66
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
67
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
68
import org.gvsig.fmap.dal.exception.InitializeException;
69
import org.gvsig.fmap.dal.exception.OpenException;
70
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
71
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
72
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
73
import org.gvsig.metadata.MetadataLocator;
74
import org.gvsig.raster.cache.tile.provider.TileServer;
75
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
76
import org.gvsig.raster.impl.datastruct.BandListImpl;
77
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
78
import org.gvsig.raster.impl.datastruct.ExtentImpl;
79
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
80
import org.gvsig.raster.impl.provider.RasterProvider;
81
import org.gvsig.raster.impl.provider.RemoteRasterProvider;
82
import org.gvsig.raster.impl.store.DefaultRasterStore;
83
import org.gvsig.raster.impl.store.DefaultStoreFactory;
84
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
85
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
86
import org.gvsig.raster.impl.store.properties.RemoteStoreHistogram;
87
import org.gvsig.raster.util.DefaultProviderServices;
88
import org.gvsig.raster.wms.io.downloader.WMSTileServer;
89
import org.gvsig.remoteclient.utils.Utilities;
90
import org.gvsig.remoteclient.wms.WMSStatus;
91
import org.gvsig.tools.ToolsLocator;
92

  
93
import org.slf4j.Logger;
94
import org.slf4j.LoggerFactory;
95
/**
96
 * Clase que representa al driver de acceso a datos de wms.
97
 *
98
 * @author Nacho Brodin (nachobrodin@gmail.com)
99
 */
100
public class WMSProvider extends AbstractRasterProvider implements RemoteRasterProvider {
101
	public static String                NAME                     = "Wms Store";
102
	public static String                DESCRIPTION              = "Wms Raster file";
103
	public static final String          METADATA_DEFINITION_NAME = "WmsStore";
104
	private static final Logger         logger                    = LoggerFactory.getLogger(WMSProvider.class);
105
	private static final int            FIXED_SIZE               = 800;
106
	private Extent                      viewRequest              = null;
107
	private static Hashtable<String, WMSConnector>
108
	                                    drivers                  = new Hashtable<String, WMSConnector> ();
109
	private boolean                     open                     = false;
110
	private DataStoreTransparency       fileTransparency         = null;
111
	private final int					minTilePrintWidth        = 12;
112
	private final int					minTilePrintHeight       = 12;
113
	//The out size depends on the last request
114
	private int                         lastWidthRequest         = 0;
115
	private int                         lastHeightRequest        = 0;
116
	//Only for fixed size. Complete extent and FIXED_SIZE in long side
117
	private File                        fileLayerPixelSize       = null;
118
	private File                        lastRequest              = null;
119
	private AbstractRasterProvider       lastRequestProvider      = null;
120

  
121
	public static void register() {
122
		DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
123
		if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
124
			dataman.registerStoreProvider(NAME,
125
					WMSProvider.class, WMSDataParametersImpl.class);
126
		}
127

  
128
		if (!dataman.getExplorerProviders().contains(WMSServerExplorer.NAME)) {
129
			dataman.registerExplorerProvider(WMSServerExplorer.NAME, WMSServerExplorer.class, WMSServerExplorerParameters.class);
130
		}
131
		dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
132
	}
133

  
134
	public WMSProvider() throws NotSupportedExtensionException {
135
		super();
136
	}
137

  
138
	public void registerTileProviderFormats(Class<RasterProvider> c) {
139

  
140
	}
141

  
142
	/**
143
	 * Constructor. Abre el dataset.
144
	 * @throws OpenException
145
	 * @throws NotSupportedExtensionException
146
     * @deprecated use {@link #WMSProvider(URI)}, this constructor will be removed in gvSIG 2.5
147
	 */
148
    public WMSProvider(String params) throws InitializeException, OpenException {
149
        super(params);
150
        logger.info("Deprecated use of WMSProvider constructor");
151
        if (params instanceof String) {
152
            WMSDataParameters p = new WMSDataParametersImpl();
153
            try {
154
                p.setURI(new URI((String) params));
155
            } catch (URISyntaxException e) {
156
                throw new OpenException("Can't create URI from" + (String) params, e);
157
            }
158
            super.init(
159
                p,
160
                null,
161
                ToolsLocator.getDynObjectManager().createDynObject(
162
                    MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
163
            init(p, null);
164
        }
165
    }
166

  
167
    public WMSProvider(URI uri) throws InitializeException {
168
        super(uri);
169
        WMSDataParameters p = new WMSDataParametersImpl();
170
        p.setURI(uri);
171
        super.init(
172
            p,
173
            null,
174
            ToolsLocator.getDynObjectManager().createDynObject(
175
                MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
176
        init(p, null);
177
    }
178

  
179
    /**
180
     * Constructor. Abre el dataset.
181
     * @param fName Nombre del fichero
182
     * @throws OpenException
183
     * @throws NotSupportedExtensionException
184
     * @deprecated use {@link #WMSProvider(URI)}, this constructor will be removed in gvSIG 2.5
185
     */
186
	public WMSProvider(WMSDataParameters params,
187
			DataStoreProviderServices storeServices) throws InitializeException {
188
		super(params, storeServices, ToolsLocator.getDynObjectManager()
189
				.createDynObject(
190
						MetadataLocator.getMetadataManager().getDefinition(
191
								DataStore.METADATA_DEFINITION_NAME)));
192
		init(params, storeServices);
193
	}
194

  
195
	/**
196
	 * Gets the connector from the URL
197
	 * @return
198
	 * @throws RemoteServiceException
199
	 */
200
	public WMSConnector getConnector() throws RemoteServiceException {
201
		WMSDataParameters p = (WMSDataParameters)parameters;
202
		URL url = null;
203
		try {
204
			url =p.getURI().toURL();
205
		} catch (Exception e) {
206
			throw new RemoteServiceException("Malformed URL",e);
207
		}
208
		try {
209
			return WMSProvider.getConnectorFromURL(url, false);
210
		} catch (IOException e) {
211
			throw new RemoteServiceException("Error getting the connector",e);
212
		}
213
	}
214

  
215
	/**
216
	 * Crea las referencias al fichero y carga
217
	 * las estructuras con la informaci?n y los metadatos.
218
	 * @param proj Proyecci?n
219
	 * @param param Parametros de carga
220
	 * @throws NotSupportedExtensionException
221
	 */
222
	public void init (DataStoreParameters params,
223
			DataStoreProviderServices storeServices) throws InitializeException {
224
		setParam(storeServices, params);
225
		setDataType(new int[]{Buffer.TYPE_BYTE, Buffer.TYPE_BYTE, Buffer.TYPE_BYTE});
226
		bandCount = 3;
227
		open = true;
228
		try {
229
			loadInitialInfo();
230
		} catch (RasterDriverException e) {
231
			throw new InitializeException(e.getMessage(), e);
232
		}
233
	}
234

  
235
	/**
236
	 * When a WMS provider is opened the information of data type, number of bands and transparency
237
	 * is not available. Only after the first time a raster has been downloaded it can be know.
238
	 * @param newDataType
239
	 * @param buf
240
	 * @param bandList
241
	 * @return
242
	 * @throws RasterDriverException
243
	 */
244
	private void loadInitialInfo() throws RasterDriverException {
245
		WMSDataParametersImpl p = (WMSDataParametersImpl)parameters;
246
		Extent ext = getExtent();
247
		Rectangle2D bBox = ext.toRectangle2D();
248
		int w = 0;
249
		int h = 0;
250
		if(ext.width() > ext.height()) {
251
			w = 200;
252
			h = (int)((ext.height() * w) / ext.width());
253
		} else {
254
			h = 200;
255
			w = (int)((ext.width() * h) / ext.height());
256
		}
257
		p.setWidth(w);
258
		p.setHeight(h);
259
		p.setExtent(bBox);
260
		if(p.getSRSCode() != null) {
261
			try {
262
				IProjection proj = CRSFactory.getCRS(p.getSRSCode());
263
				setProjection(proj, false);
264
			} catch (Exception e) {
265
			}
266
		}
267
		WMSStatus wmsStatus = loadWMSStatus(bBox);
268

  
269
		lastRequest = downloadFile(wmsStatus, ext.getULX(), ext.getULY(), ext.getLRX(), ext.getLRY(), w, h);
270
		AbstractRasterProvider driver;
271
		try {
272
			driver = DefaultProviderServices.loadProvider(lastRequest);
273
			setDataType(driver.getDataType());
274
			bandCount = driver.getBandCount();
275
			if(bandCount > 3) {
276
				getColorInterpretation().setColorInterpValue(3, DataStoreColorInterpretation.ALPHA_BAND);
277
				getTransparency().setTransparencyBand(3);
278
			}
279
			setColorTable(driver.getColorTable());
280
			driver.close();
281
		} catch (ProviderNotRegisteredException e) {
282
			throw new RasterDriverException("", e);
283
		} catch (InitializeException e) {
284
			throw new RasterDriverException("", e);
285
		}
286
	}
287

  
288
	public static final WMSConnector getConnectorFromURL(URL url, boolean updating) throws IOException {
289
		WMSConnector drv = null;
290
		if(!updating) {
291
			drv = (WMSConnector) drivers.get(url.toString());
292
		} else {
293
			if(drivers.get(url.toString()) != null)
294
				drivers.remove(url.toString());
295
		}
296

  
297
		if (drv == null) {
298
			drv = new WMSConnector(url);
299
			drivers.put(url.toString(), drv);
300
		}
301

  
302
		return drv;
303
	}
304

  
305
	/**
306
	 * Obtiene el objeto que contiene que contiene la interpretaci?n de
307
	 * color por banda
308
	 * @return
309
	 */
310
	public ColorInterpretation getColorInterpretation() {
311
		if(super.getColorInterpretation() == null) {
312
			ColorInterpretation colorInterpretation = new DataStoreColorInterpretation(getBandCount());
313
			if(getBandCount() == 1 || getBandCount() == 2)
314
				colorInterpretation = DataStoreColorInterpretation.createGrayInterpretation();
315
			if(getBandCount() == 3)
316
				colorInterpretation = DataStoreColorInterpretation.createRGBInterpretation();
317
			if(getBandCount() == 4)
318
				colorInterpretation = DataStoreColorInterpretation.createRGBAInterpretation();
319
			setColorInterpretation(colorInterpretation);
320
		}
321
		return super.getColorInterpretation();
322
	}
323

  
324
	public AffineTransform getAffineTransform() {
325
		WMSDataParameters p = (WMSDataParameters)parameters;
326
		if(p.isSizeFixed()) {
327
			Extent e = getExtent(); // FIXME: it should also be taken from parameters instead of from the full layer extent
328
			double psX = e.width() / (p.getWidth() - 1);
329
			double psY = -(e.height() / (p.getHeight() - 1));
330
			ownTransformation = new AffineTransform(
331
					psX ,
332
					0,
333
					0,
334
					psY,
335
					e.getULX() - (psX / 2),
336
					e.getULY() - (psY / 2));
337
		} else {
338
			Rectangle2D bbox = p.getExtent();
339
			double psX = bbox.getWidth() / p.getWidth();
340
			double psY = -(bbox.getHeight() / p.getHeight());
341
			ownTransformation = new AffineTransform(
342
					psX,
343
					0,
344
					0,
345
					psY,
346
					bbox.getX(),
347
					(bbox.getY()+bbox.getHeight())); // FIXME: check for other CRSs such as 4326
348
		}
349
		externalTransformation = (AffineTransform) ownTransformation.clone();
350
		return ownTransformation;
351
	}
352

  
353
	/**
354
	 * Calcula el extent en coordenadas del mundo real
355
	 * @return Extent
356
	 */
357
	public Extent getExtent() {
358
		WMSDataParameters p = (WMSDataParameters)parameters;
359
		Vector<?> layerNames = Utilities.createVector(p.getLayerQuery(), ",");
360

  
361
		String[] ln = new String[layerNames.size()];
362
		for (int i = 0; i < ln.length; i++) {
363
			ln[i] = (String)layerNames.get(i);
364
		}
365
		Rectangle2D r = null;
366
		try {
367
			r = getConnector().getLayersExtent(ln, p.getSRSCode());
368
			if (r == null) {
369
				String latLonID = "EPSG:4326";
370
				r = getConnector().getLayersExtent(ln, latLonID);
371
				if (r == null) {
372
					r = getConnector().getLayersExtent(ln, "CRS:84");
373
				}
374

  
375
				IProjection reqProj = CRSFactory.getCRS(p.getSRSCode());
376
				IProjection latLonProj = CRSFactory.getCRS(latLonID);
377
				if ((reqProj != null) && (latLonProj != null)) {
378
					ICoordTrans ct = latLonProj.getCT(reqProj);
379
					Rectangle2D reprojectedRect = ct.convert(r);
380
					r = reprojectedRect;
381
				}
382
			}
383
		} catch (RemoteServiceException e) {
384
		}
385
		if(r == null)
386
			return null;
387
		return new ExtentImpl(r.getMinX(), r.getMaxY(), r.getMaxX(), r.getMinY());
388
	}
389

  
390
	public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
391
		return getConnector().getLayersExtent(new String[]{layerName}, srs);
392
	}
393

  
394
	public RasterProvider load() {
395
		return this;
396
	}
397

  
398
	public boolean isOpen() {
399
		return open;
400
	}
401

  
402
	public void close() {
403
		open = false;
404
	}
405

  
406
	public Transparency getTransparency() {
407
		if(fileTransparency == null)
408
			fileTransparency = new DataStoreTransparency(getColorInterpretation());
409
		return fileTransparency;
410
	}
411

  
412
	public URI translateURI(URI uri) {
413
		return uri;
414
	}
415

  
416
	public void setView(Extent e) {
417
		viewRequest = e;
418
	}
419

  
420
	public Extent getView() {
421
		return viewRequest;
422
	}
423

  
424
	public double getWidth() {
425
		WMSDataParameters p = (WMSDataParameters)parameters;
426
		return p.getWidth();
427
	}
428

  
429
	public double getHeight() {
430
		WMSDataParameters p = (WMSDataParameters)parameters;
431
		return p.getHeight();
432
	}
433

  
434
	/**
435
	 * Gets WMS parameters
436
	 * @return
437
	 */
438
	public WMSDataParameters getParameters() {
439
		return (WMSDataParameters)parameters;
440
	}
441

  
442
	public Object readCompleteLine(int line, int band)
443
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
444
		return null;
445
	}
446

  
447
	/**
448
	 * When the remote layer has fixed size this method downloads the file and return its reference.
449
	 * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
450
	 * useful to build an histogram or calculate statistics. This represents a sample of data.
451
	 * @return
452
	 * @throws RasterDriverException
453
	 */
454
	public File getFileLayer() throws RasterDriverException {
455
		if(fileLayerPixelSize != null)
456
			return fileLayerPixelSize;
457

  
458
		WMSDataParameters p = (WMSDataParameters)parameters;
459
		Extent e = getExtent();
460
		Rectangle2D bBox = new Rectangle2D.Double(e.getULX(), e.getLRY(), e.width(), e.height());
461
		WMSStatus wmsStatus = loadWMSStatus(bBox);
462

  
463
		if(!p.isSizeFixed()) {
464
			int w = 0;
465
			int h = 0;
466
			if(e.width() > e.height()) {
467
				w = FIXED_SIZE;
468
				h = (int)((e.height() * FIXED_SIZE) / e.width());
469
			} else {
470
				h = FIXED_SIZE;
471
				w = (int)((e.width() * FIXED_SIZE) / e.height());
472
			}
473
			wmsStatus.setWidth(w);
474
			wmsStatus.setHeight(h);
475
			fileLayerPixelSize = downloadFile(wmsStatus, e.getULX(), e.getULY(), e.getLRX(), e.getLRY(), w, h);
476
		} else {
477
			fileLayerPixelSize = downloadFile(wmsStatus, e.getULX(), e.getULY(), e.getLRX(), e.getLRY(),
478
					p.getFixedSize().width, p.getFixedSize().height);
479
		}
480
		return fileLayerPixelSize;
481
	}
482

  
483
	/**
484
	 * Reads a complete block of data and returns an tridimensional array of the right type. This function is useful
485
	 * to read a file very fast without setting a view. In a WMS service when the size is fixed then it will read the
486
	 * entire image but when the source hasn't pixel size it will read a sample of data. This set of data will have
487
	 * the size defined in FIXED_SIZE.
488
	 *
489
	 * @param pos Posici?n donde se empieza  a leer
490
	 * @param blockHeight Altura m?xima del bloque leido
491
	 * @return Object que es un array tridimendional del tipo de datos del raster. (Bandas X Filas X Columnas)
492
	 * @throws InvalidSetViewException
493
	 * @throws FileNotOpenException
494
	 * @throws RasterDriverException
495
	 */
496
	public Object readBlock(int pos, int blockHeight, double scale)
497
	throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
498
		File lastFile = getFileLayer();
499
		BandList bandList = new BandListImpl();
500
		for (int i = 0; i < 3; i++) {
501
			try {
502
				bandList.addBand(new DatasetBandImpl(lastFile.getPath(), pos, Buffer.TYPE_BYTE, 3));
503
			} catch (BandNotFoundInListException e1) {
504
			}
505
		}
506
		bandList.setDrawableBands(new int[]{0, 1, 2});
507

  
508
		try {
509
			lastRequestProvider = openLastRequest();
510
			return lastRequestProvider.readBlock(pos, blockHeight, scale);
511
		} catch (ProviderNotRegisteredException exc) {
512
			throw new RasterDriverException("Error building GdalDriver", exc);
513
		} catch (InitializeException exc) {
514
			throw new RasterDriverException("Error building GdalDriver", exc);
515
		}
516
	}
517

  
518
	public double getLastRequestHeight() throws RasterDriverException {
519
		if(lastRequestProvider == null) {
520
			try {
521
				lastRequestProvider = openLastRequest();
522
			} catch (ProviderNotRegisteredException e) {
523
				throw new RasterDriverException("Error building GdalDriver", e);
524
			} catch (InitializeException e) {
525
				throw new RasterDriverException("Error building GdalDriver", e);
526
			}
527
		}
528
		return lastRequestProvider.getHeight();
529
	}
530

  
531
	public double getLastRequestWidth() throws RasterDriverException {
532
		if(lastRequestProvider == null) {
533
			try {
534
				lastRequestProvider = openLastRequest();
535
			} catch (ProviderNotRegisteredException e) {
536
				throw new RasterDriverException("Error building GdalDriver", e);
537
			} catch (InitializeException e) {
538
				throw new RasterDriverException("Error building GdalDriver", e);
539
			}
540
		}
541
		return lastRequestProvider.getWidth();
542
	}
543

  
544
	public File getLastRequest() {
545
		return lastRequest;
546
	}
547

  
548
	public Buffer getBufferLastRequest() throws ProcessInterruptedException, RasterDriverException {
549
		try {
550
			lastRequestProvider = openLastRequest();
551
			return getDownloadedRaster(lastRequestProvider);
552
		} catch (ProviderNotRegisteredException e) {
553
			throw new RasterDriverException("Error building GdalDriver", e);
554
		} catch (InitializeException e) {
555
			throw new RasterDriverException("Error building GdalDriver", e);
556
		} catch (QueryException e) {
557
			throw new RasterDriverException("Error building GdalDriver", e);
558
		}
559
	}
560

  
561
	/**
562
	 * Opens the last request downloaded
563
	 * @return
564
	 * @throws ProviderNotRegisteredException
565
	 * @throws InitializeException
566
	 * @throws RasterDriverException
567
	 */
568
	private AbstractRasterProvider openLastRequest() throws ProviderNotRegisteredException, InitializeException, RasterDriverException {
569
		if(lastRequestProvider != null)
570
			lastRequestProvider.close();
571
		File lastFile = getFileLayer();
572
		lastRequestProvider = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
573
		setColorTable(lastRequestProvider.getColorTable());
574
		return lastRequestProvider;
575
	}
576

  
577
	public Object getData(int x, int y, int band)
578
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
579
		return null;
580
	}
581

  
582
	/**
583
	 * Gets the georeferencing file name form a raster file
584
	 * @param file
585
	 * a raster file
586
	 * @return
587
	 * a georeferencing file
588
	 */
589
	private String getWorldFile(String file){
590
		String worldFile = file;
591
		int index = file.lastIndexOf(".");
592
		if (index > 0){
593
			worldFile = file.substring(0, index) + getExtensionWorldFile();
594
		}
595
		return worldFile;
596
	}
597

  
598
	/**
599
	 * Obtiene la extensi?n del fichero de georreferenciaci?n
600
	 * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
601
	 * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
602
	 */
603
	private String getExtensionWorldFile() {
604
		WMSDataParameters p = (WMSDataParameters)parameters;
605
		String extWorldFile = ".wld";
606
		if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
607
			extWorldFile = ".tfw";
608
		}
609
		return extWorldFile;
610
	}
611

  
612
	public WMSStatus loadWMSStatus(Rectangle2D bBox) {
613
		WMSDataParameters p = (WMSDataParameters)parameters;
614
		WMSStatus wmsStatus = new WMSStatus();
615
		wmsStatus.setLayerNames(Utilities.createVector(p.getLayerQuery(), ","));
616
		wmsStatus.setSrs(p.getSRSCode());
617
		wmsStatus.setFormat(p.getFormat());
618
		wmsStatus.setInfoFormat(p.getInfoFormat());
619
		List<RemoteWMSStyle> listStyles = p.getStyles();
620
		Vector<?> v = listStyles != null ? new Vector<RemoteWMSStyle>(listStyles) : null;
621
		wmsStatus.setStyles(v);
622
		wmsStatus.setDimensions(p.getDimensions());
623
		wmsStatus.setTransparency(p.isWmsTransparent());
624
		wmsStatus.setOnlineResource((String) p.getOnlineResource().get("GetMap"));
625
		if(p.isSizeFixed()) {
626
			wmsStatus.setExtent(getExtent().toRectangle2D());
627
		} else
628
			wmsStatus.setExtent(bBox);
629
		wmsStatus.setHeight(p.getHeight());
630
		wmsStatus.setWidth(p.getWidth());
631
		wmsStatus.setXyAxisOrder(p.isXyAxisOrder());
632
		IProjection proj = getProjection();
633
		if(proj != null)
634
			wmsStatus.setProjected(proj.isProjected());
635
		return wmsStatus;
636
	}
637

  
638
	/**
639
	 * This function downloads the file and creates the georeferencing file
640
	 * @param wmsStatus
641
	 * @param ulx
642
	 * @param uly
643
	 * @param lrx
644
	 * @param lry
645
	 * @param w
646
	 * @param h
647
	 * @return
648
	 * @throws RasterDriverException
649
	 */
650
	private File downloadFile(WMSStatus wmsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
651
		WMSDataParameters p = (WMSDataParameters)parameters;
652
		try {
653
			lastRequest = getConnector().getMap(wmsStatus, ((WMSDataParameters)parameters).getCancellable());
654
		} catch (RemoteServiceException e) {
655
			throw new RasterDriverException(e.getMessage(), e);
656
		}
657

  
658
		if(lastRequest == null)
659
			return null;
660

  
661
		String nameWorldFile = getWorldFile(lastRequest.getPath());
662
		try {
663
			if(p.isSizeFixed()) {
664
				Extent e = getExtent();
665
				fileUtil.createWorldFile(nameWorldFile, e, p.getWidth(), p.getHeight());
666
			} else {
667
				fileUtil.createWorldFile(nameWorldFile, new ExtentImpl(ulx, uly, lrx, lry), w, h);
668
			}
669
		} catch (IOException e) {
670
			throw new RasterDriverException("Error creating world file", e);
671
		}
672

  
673
		return lastRequest;
674
	}
675

  
676
	@Override
677
	public void loadBuffer(SpiRasterQuery q)
678
			throws ProcessInterruptedException, RasterDriverException {
679
		Extent bbox = q.getRequestBoundingBox();
680
		lastWidthRequest = q.getBufWidth();
681
		lastHeightRequest = q.getBufHeight();
682
		WMSStatus wmsStatus = loadWMSStatus(bbox.toRectangle2D());
683

  
684
		lastRequest = downloadFile(wmsStatus,
685
				bbox.getULX(),
686
				bbox.getULY(),
687
				bbox.getLRX(),
688
				bbox.getLRY(),
689
				q.getBufWidth(),
690
				q.getBufHeight());
691

  
692
		if (lastRequest == null) {
693
			return;
694
		}
695

  
696
		Buffer b = null;
697
		try {
698
			b = getDownloadedRaster(lastRequest);
699
		} catch (QueryException e) {
700
			throw new RasterDriverException("Error building GdalDriver", e);
701
		} catch (ProviderNotRegisteredException e) {
702
			throw new RasterDriverException("Error building GdalDriver", e);
703
		} catch (InitializeException e) {
704
			throw new RasterDriverException("Error building GdalDriver", e);
705
		}
706
		q.setBufferResult(b);
707
	}
708

  
709
	private Buffer getDownloadedRaster(File f) throws ProcessInterruptedException, QueryException, ProviderNotRegisteredException, InitializeException {
710
		AbstractRasterProvider provider = DefaultProviderServices.loadProvider(new File(f.getPath()));
711
		setColorTable(provider.getColorTable());
712
		return getDownloadedRaster(provider);
713
	}
714

  
715
	private Buffer getDownloadedRaster(AbstractRasterProvider provider) throws ProcessInterruptedException, QueryException, ProviderNotRegisteredException, InitializeException {
716
		DefaultRasterStore store = new DefaultRasterStore();
717
		store.setProvider(provider);
718

  
719
		RasterQuery q = RasterLocator.getManager().createQuery();
720
		q.setAreaOfInterest();
721
		if(getColorInterpretation() != null)
722
			q.setDrawableBands(getColorInterpretation().buildRenderBands());
723
		if(store.getBandCount() > 3)
724
			q.forceARGBRequest();
725
		else
726
			q.forceRGBRequest();
727

  
728
		Buffer buf = store.query(q);
729

  
730
		store.close();
731
		return buf;
732
	}
733

  
734
	/**
735
	 * Assigns the list of bands RGB and read a window of data
736
	 * @param rasterBuf
737
	 * @param bandList
738
	 * @param lastFile
739
	 * @param ulx
740
	 * @param uly
741
	 * @param lrx
742
	 * @param lry
743
	 * @return
744
	 * @throws RasterDriverException
745
	 * @throws ProcessInterruptedException
746
	 */
747
	/*public Buffer getBuffer(Buffer rasterBuf, BandList bandList, File lastFile,
748
			double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
749
		try {
750
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
751
			String serverName = bandList.getBand(0).getFileName();
752
			for (int i = 0; i < bandList.getBandCount(); i++) {
753
				bandList.getBand(i).setFileName(lastFile.getPath());
754
			}
755

  
756
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
757
			setColorTable(driver.getColorTable());
758

  
759
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
760
			q.setAreaOfInterest(new ExtentImpl(ulx, uly, lrx, lry));
761
			q.setBandList(bandList);
762
			q.setBuffer(rasterBuf);
763
			Buffer buf = driver.getDataSet(q);
764

  
765
			for (int i = 0; i < bandList.getBandCount(); i++) {
766
				bandList.getBand(i).setFileName(serverName);
767
			}
768

  
769
			return buf;
770
		} catch (ProviderNotRegisteredException e) {
771
			throw new RasterDriverException("Error building GdalDriver", e);
772
		} catch (InitializeException e) {
773
			throw new RasterDriverException("Error building GdalDriver", e);
774
		}
775
	}*/
776

  
777
	/*public void getWindow(Extent ex, int bufWidth, int bufHeight,
778
			BandList bandList, TileListener listener, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
779

  
780
		Buffer raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], bufWidth, bufHeight, 3, true);
781
		getWindow(ex, bufWidth, bufHeight, bandList, raster, true, null);
782
		raster.setDataExtent(ex.toRectangle2D());
783

  
784
		TileCacheManager m = TileCacheLocator.getManager();
785
		org.gvsig.raster.cache.tile.Tile t = m.createTile(-1, 0, 0);
786
		t.setData(new Object[]{raster});
787
		t.setUl(new Point2D.Double(ex.getULX(), ex.getULY()));
788
		t.setLr(new Point2D.Double(ex.getLRX(), ex.getLRY()));
789
		t.setDownloaderParams("AffineTransform", getAffineTransform());
790
		t.setDownloaderParams("Tiling", new Boolean(false));
791
		try {
792
			listener.tileReady(t);
793
		} catch (TileGettingException e) {
794
			throw new RasterDriverException("Error throwing a tile", e);
795
		}
796

  
797
		//listener.nextBuffer(raster, null, new ExtentImpl(minX, minY, maxX, maxY), getAffineTransform(), null, false);
798
		listener.endReading();
799
	}*/
800

  
801
	/*public Buffer getWindow(Extent ex, BandList bandList, Buffer rasterBuf, TaskStatus status)
802
		throws ProcessInterruptedException, RasterDriverException {
803
		Rectangle2D bBox = ex.toRectangle2D();
804
		lastWidthRequest = rasterBuf.getWidth();
805
		lastHeightRequest = rasterBuf.getHeight();
806
		WMSStatus wmsStatus = loadWMSStatus(bBox);
807

  
808
		lastRequest = downloadFile(wmsStatus, ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), rasterBuf.getWidth(), rasterBuf.getHeight());
809

  
810
		if (lastRequest == null) {
811
			return rasterBuf;
812
		}
813

  
814
		try {
815
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
816
			String serverName = bandList.getBand(0).getFileName();
817
			for (int i = 0; i < bandList.getBandCount(); i++) {
818
				bandList.getBand(i).setFileName(lastRequest.getPath());
819
			}
820

  
821
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
822
			setColorTable(driver.getColorTable());
823

  
824
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
825
			q.setAreaOfInterest(ex);
826
			q.setBandList(bandList);
827
			q.setBuffer(rasterBuf);
828
			Buffer buf = driver.getDataSet(q);
829

  
830
			for (int i = 0; i < bandList.getBandCount(); i++) {
831
				bandList.getBand(i).setFileName(serverName);
832
			}
833
			driver.close();
834
			return buf;
835
		} catch (ProviderNotRegisteredException e) {
836
			throw new RasterDriverException("Error building GdalDriver", e);
837
		} catch (InitializeException e) {
838
			throw new RasterDriverException("Error building GdalDriver", e);
839
		}
840
	}*/
841

  
842
	/*public Buffer getWindow(double ulx, double uly, double w, double h,
843
			BandList bandList, Buffer rasterBuf, boolean adjustToExtent, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
844
		Rectangle2D bBox = new Rectangle2D.Double(ulx, uly, w, h);
845
		lastWidthRequest = rasterBuf.getWidth();
846
		lastHeightRequest = rasterBuf.getHeight();
847
		WMSStatus wmsStatus = loadWMSStatus(bBox);
848

  
849
		lastRequest = downloadFile(wmsStatus, ulx, uly, ulx + w, uly - h, rasterBuf.getWidth(), rasterBuf.getHeight());
850

  
851
		if (lastRequest == null) {
852
			return rasterBuf;
853
		}
854

  
855
		try {
856
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
857
			String serverName = bandList.getBand(0).getFileName();
858
			for (int i = 0; i < bandList.getBandCount(); i++) {
859
				bandList.getBand(i).setFileName(lastRequest.getPath());
860
			}
861

  
862
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
863
			setColorTable(driver.getColorTable());
864

  
865
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
866
			q.setAreaOfInterest(ulx, uly, w, h);
867
			q.setBandList(bandList);
868
			q.setBuffer(rasterBuf);
869
			q.setAdjustToExtent(adjustToExtent);
870

  
871
			Buffer buf = driver.getDataSet(q);
872

  
873
			for (int i = 0; i < bandList.getBandCount(); i++) {
874
				bandList.getBand(i).setFileName(serverName);
875
			}
876

  
877
			return buf;
878
		} catch (ProviderNotRegisteredException e) {
879
			throw new RasterDriverException("Error building GdalDriver", e);
880
		} catch (InitializeException e) {
881
			throw new RasterDriverException("Error building GdalDriver", e);
882
		}
883
	}*/
884

  
885
	/*public Buffer getWindow(Extent extent, int bufWidth, int bufHeight,
886
			BandList bandList, Buffer rasterBuf, boolean adjustToExtent, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
887
		Rectangle2D bBox = extent.toRectangle2D();//new Rectangle2D.Double(ulx, lry, Math.abs(lrx - ulx), Math.abs(lry - uly));
888
		lastWidthRequest = rasterBuf.getWidth();
889
		lastHeightRequest = rasterBuf.getHeight();
890
		WMSStatus wmsStatus = loadWMSStatus(bBox);
891
		lastRequest = downloadFile(wmsStatus, extent.getULX(), extent.getULY(), extent.getLRX(), extent.getLRY(), rasterBuf.getWidth(), rasterBuf.getHeight());
892

  
893
		if (lastRequest == null) {
894
			return rasterBuf;
895
		}
896

  
897
		try {
898
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
899
			String serverName = bandList.getBand(0).getFileName();
900
			for (int i = 0; i < bandList.getBandCount(); i++) {
901
				bandList.getBand(i).setFileName(lastRequest.getPath());
902
			}
903

  
904
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
905
			setColorTable(driver.getColorTable());
906

  
907
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
908
			q.setAreaOfInterest(extent, bufWidth, bufHeight);
909
			q.setBandList(bandList);
910
			q.setBuffer(rasterBuf);
911
			q.setAdjustToExtent(adjustToExtent);
912
			Buffer buf = driver.getDataSet(q);
913

  
914
			for (int i = 0; i < bandList.getBandCount(); i++) {
915
				bandList.getBand(i).setFileName(serverName);
916
			}
917

  
918
			return buf;
919
		} catch (ProviderNotRegisteredException e) {
920
			throw new RasterDriverException("Error building GdalDriver", e);
921
		} catch (InitializeException e) {
922
			throw new RasterDriverException("Error building GdalDriver", e);
923
		}
924
	}*/
925

  
926
//	public Buffer getWindow(int x, int y,
927
//			BandList bandList, Buffer rasterBuf) throws ProcessInterruptedException, RasterDriverException {
928
//		int w = rasterBuf.getWidth();
929
//		int h = rasterBuf.getHeight();
930
//		Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
931
//		Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
932
//		lastWidthRequest = rasterBuf.getWidth();
933
//		lastHeightRequest = rasterBuf.getHeight();
934
//		Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p1.getX()), Math.abs(p1.getY() - p2.getY()));
935
//		WMSStatus wmsStatus = loadWMSStatus(bBox);
936
//
937
//		lastRequest = downloadFile(wmsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), rasterBuf.getWidth(), rasterBuf.getHeight());
938
//
939
//		if (lastRequest == null) {
940
//			return rasterBuf;
941
//		}
942
//
943
//		AbstractRasterProvider driver = null;
944
//		try {
945
//			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
946
//			String serverName = bandList.getBand(0).getFileName();
947
//			for (int i = 0; i < bandList.getBandCount(); i++) {
948
//				bandList.getBand(i).setFileName(lastRequest.getPath());
949
//			}
950
//
951
//			driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
952
//			Buffer buf = driver.getWindow(0, 0, w, h, bandList, rasterBuf);
953
//
954
//			for (int i = 0; i < bandList.getBandCount(); i++) {
955
//				bandList.getBand(i).setFileName(serverName);
956
//			}
957
//
958
//			return buf;
959
//		} catch (ProviderNotRegisteredException e) {
960
//			throw new RasterDriverException("Error building GdalDriver", e);
961
//		} catch (InitializeException e) {
962
//			throw new RasterDriverException("Error building GdalDriver", e);
963
//		}
964
//	}
965

  
966
	/*public Buffer getWindow(int x, int y, int w, int h,
967
			BandList bandList, Buffer rasterBuf, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
968
		Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
969
		Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
970
		lastWidthRequest = rasterBuf.getWidth();
971
		lastHeightRequest = rasterBuf.getHeight();
972
		Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p1.getX()), Math.abs(p1.getY() - p2.getY()));
973
		WMSStatus wmsStatus = loadWMSStatus(bBox);
974

  
975
		lastRequest = downloadFile(wmsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), rasterBuf.getWidth(), rasterBuf.getHeight());
976

  
977
		if (lastRequest == null) {
978
			return rasterBuf;
979
		}
980

  
981
		AbstractRasterProvider driver = null;
982
		try {
983
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
984
			String serverName = bandList.getBand(0).getFileName();
985
			for (int i = 0; i < bandList.getBandCount(); i++) {
986
				bandList.getBand(i).setFileName(lastRequest.getPath());
987
			}
988

  
989
			driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
990
			setColorTable(driver.getColorTable());
991

  
992
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
993
			q.setAreaOfInterest(0, 0, w, h);
994
			q.setBandList(bandList);
995
			q.setBuffer(rasterBuf);
996
			Buffer buf = driver.getDataSet(q);
997

  
998
			for (int i = 0; i < bandList.getBandCount(); i++) {
999
				bandList.getBand(i).setFileName(serverName);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff