Revision 4079

View differences:

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

  
384
        // Queryable
385

  
386
        myNode.setQueryable(node.isQueryable() && client.getServiceInformation().isQueryable());
387

  
388
        // Parent layer
389
        myNode.setParent(parentNode);
390

  
391
        // Abstract
392
        myNode.setAbstract(node.getAbstract());
393

  
394
        // Fixed Size
395
        myNode.setFixedSize(node.getfixedWidth(), node.getfixedHeight());
396

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

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

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

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

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

  
428
        if (myNode.getName()!=null)
429
            layers.put(myNode.getName(), myNode);
430

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

  
450
    public String getAbstract() {
451
    	return client.getServiceInformation().abstr;
452
    }
453

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

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

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

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

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

  
org.gvsig.raster.wms/tags/org.gvsig.raster.wms-2.2.18/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.URL;
32
import java.util.Hashtable;
33
import java.util.List;
34
import java.util.Vector;
35

  
36
import javax.swing.ImageIcon;
37

  
38
import org.cresques.cts.ICoordTrans;
39
import org.cresques.cts.IProjection;
40
import org.gvsig.compat.net.ICancellable;
41
import org.gvsig.fmap.crs.CRSFactory;
42
import org.gvsig.fmap.dal.DALLocator;
43
import org.gvsig.fmap.dal.DataStore;
44
import org.gvsig.fmap.dal.DataStoreParameters;
45
import org.gvsig.fmap.dal.coverage.RasterLocator;
46
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
47
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
48
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
49
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
50
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
51
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
52
import org.gvsig.fmap.dal.coverage.exception.InfoByPointException;
53
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
54
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
55
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
56
import org.gvsig.fmap.dal.coverage.exception.QueryException;
57
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
58
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
59
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
60
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
61
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
62
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
63
import org.gvsig.fmap.dal.exception.InitializeException;
64
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
65
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
66
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
67
import org.gvsig.metadata.MetadataLocator;
68
import org.gvsig.raster.cache.tile.provider.TileServer;
69
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
70
import org.gvsig.raster.impl.datastruct.BandListImpl;
71
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
72
import org.gvsig.raster.impl.datastruct.ExtentImpl;
73
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
74
import org.gvsig.raster.impl.provider.RasterProvider;
75
import org.gvsig.raster.impl.provider.RemoteRasterProvider;
76
import org.gvsig.raster.impl.store.DefaultRasterStore;
77
import org.gvsig.raster.impl.store.DefaultStoreFactory;
78
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
79
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
80
import org.gvsig.raster.impl.store.properties.RemoteStoreHistogram;
81
import org.gvsig.raster.util.DefaultProviderServices;
82
import org.gvsig.raster.wms.io.downloader.WMSTileServer;
83
import org.gvsig.remoteclient.utils.Utilities;
84
import org.gvsig.remoteclient.wms.WMSStatus;
85
import org.gvsig.tools.ToolsLocator;
86
import org.slf4j.Logger;
87
import org.slf4j.LoggerFactory;
88
/**
89
 * Clase que representa al driver de acceso a datos de wms.
90
 *
91
 * @author Nacho Brodin (nachobrodin@gmail.com)
92
 */
93
public class WMSProvider extends AbstractRasterProvider implements RemoteRasterProvider {
94
	public static String                NAME                     = "Wms Store";
95
	public static String                DESCRIPTION              = "Wms Raster file";
96
	public static final String          METADATA_DEFINITION_NAME = "WmsStore";
97
	private static final Logger         logger                    = LoggerFactory.getLogger(WMSProvider.class);
98
	private static final int            FIXED_SIZE               = 800;
99
	private Extent                      viewRequest              = null;
100
	private static Hashtable<String, WMSConnector>    
101
	                                    drivers                  = new Hashtable<String, WMSConnector> ();
102
	private boolean                     open                     = false;
103
	private DataStoreTransparency       fileTransparency         = null;
104
	private final int					minTilePrintWidth        = 12;
105
	private final int					minTilePrintHeight       = 12;
106
	//The out size depends on the last request
107
	private int                         lastWidthRequest         = 0;
108
	private int                         lastHeightRequest        = 0;
109
	//Only for fixed size. Complete extent and FIXED_SIZE in long side
110
	private File                        fileLayerPixelSize       = null;
111
	private File                        lastRequest              = null;
112
	private AbstractRasterProvider       lastRequestProvider      = null;
113
	
114
	public static void register() {
115
		DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
116
		if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
117
			dataman.registerStoreProvider(NAME,
118
					WMSProvider.class, WMSDataParametersImpl.class);
119
		}
120

  
121
		if (!dataman.getExplorerProviders().contains(WMSServerExplorer.NAME)) {
122
			dataman.registerExplorerProvider(WMSServerExplorer.NAME, WMSServerExplorer.class, WMSServerExplorerParameters.class);
123
		}
124
		dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
125
	}
126
	
127
	public WMSProvider() throws NotSupportedExtensionException {
128
		super();
129
	}
130
	
131
	public void registerTileProviderFormats(Class<RasterProvider> c) {
132

  
133
	}
134
	
135
	/**
136
	 * Constructor. Abre el dataset.
137
	 * @param proj Proyecci?n
138
	 * @param fName Nombre del fichero
139
	 * @throws NotSupportedExtensionException
140
	 */
141
	public WMSProvider(String params) throws InitializeException {
142
		super(params);
143
		if(params instanceof String) {
144
			WMSDataParameters p = new WMSDataParametersImpl();
145
			p.setURI((String)params);
146
			super.init(p, null, ToolsLocator.getDynObjectManager()
147
					.createDynObject(
148
							MetadataLocator.getMetadataManager().getDefinition(
149
									DataStore.METADATA_DEFINITION_NAME)));
150
			init(p, null);
151
		}
152
	}
153
	
154
	public WMSProvider(WMSDataParameters params,
155
			DataStoreProviderServices storeServices) throws InitializeException {
156
		super(params, storeServices, ToolsLocator.getDynObjectManager()
157
				.createDynObject(
158
						MetadataLocator.getMetadataManager().getDefinition(
159
								DataStore.METADATA_DEFINITION_NAME)));
160
		init(params, storeServices);
161
	}
162
	
163
	/**
164
	 * Gets the connector from the URL
165
	 * @return
166
	 * @throws RemoteServiceException
167
	 */
168
	public WMSConnector getConnector() throws RemoteServiceException {
169
		WMSDataParameters p = (WMSDataParameters)parameters;
170
		URL url = null;
171
		try {
172
			url = new URL(p.getURI());
173
		} catch (Exception e) {
174
			throw new RemoteServiceException("Malformed URL",e);
175
		}
176
		try {
177
			return WMSProvider.getConnectorFromURL(url, false);
178
		} catch (IOException e) {
179
			throw new RemoteServiceException("Error getting the connector",e);
180
		}
181
	}
182
	
183
	/**
184
	 * Crea las referencias al fichero y carga
185
	 * las estructuras con la informaci?n y los metadatos.
186
	 * @param proj Proyecci?n
187
	 * @param param Parametros de carga
188
	 * @throws NotSupportedExtensionException
189
	 */
190
	public void init (DataStoreParameters params,
191
			DataStoreProviderServices storeServices) throws InitializeException {
192
		setParam(storeServices, params);
193
		setDataType(new int[]{Buffer.TYPE_BYTE, Buffer.TYPE_BYTE, Buffer.TYPE_BYTE});
194
		bandCount = 3;
195
		open = true;
196
		try {
197
			loadInitialInfo();
198
		} catch (RasterDriverException e) {
199
			throw new InitializeException(e.getMessage(), e);
200
		}
201
	}
202
	
203
	/**
204
	 * When a WMS provider is opened the information of data type, number of bands and transparency 
205
	 * is not available. Only after the first time a raster has been downloaded it can be know.
206
	 * @param newDataType
207
	 * @param buf
208
	 * @param bandList
209
	 * @return
210
	 * @throws RasterDriverException 
211
	 */
212
	private void loadInitialInfo() throws RasterDriverException {
213
		WMSDataParametersImpl p = (WMSDataParametersImpl)parameters;
214
		Extent ext = getExtent();
215
		Rectangle2D bBox = ext.toRectangle2D();
216
		int w = 0;
217
		int h = 0;
218
		if(ext.width() > ext.height()) {
219
			w = 200;
220
			h = (int)((ext.height() * w) / ext.width());
221
		} else {
222
			h = 200;
223
			w = (int)((ext.width() * h) / ext.height());
224
		}
225
		p.setWidth(w);
226
		p.setHeight(h);
227
		p.setExtent(bBox);
228
		if(p.getSRSCode() != null) {
229
			try {
230
				IProjection proj = CRSFactory.getCRS(p.getSRSCode());
231
				setProjection(proj, false);
232
			} catch (Exception e) {
233
			}
234
		}
235
		WMSStatus wmsStatus = loadWMSStatus(bBox);
236
		
237
		lastRequest = downloadFile(wmsStatus, ext.getULX(), ext.getULY(), ext.getLRX(), ext.getLRY(), w, h);
238
		AbstractRasterProvider driver;
239
		try {
240
			driver = DefaultProviderServices.loadProvider(lastRequest);
241
			setDataType(driver.getDataType());
242
			bandCount = driver.getBandCount();
243
			if(bandCount > 3) {
244
				getColorInterpretation().setColorInterpValue(3, DataStoreColorInterpretation.ALPHA_BAND);
245
				getTransparency().setTransparencyBand(3);
246
			}
247
			setColorTable(driver.getColorTable());
248
			driver.close();
249
		} catch (ProviderNotRegisteredException e) {
250
			throw new RasterDriverException("", e);
251
		} catch (InitializeException e) {
252
			throw new RasterDriverException("", e);
253
		}
254
	}
255
	
256
	public static final WMSConnector getConnectorFromURL(URL url, boolean updating) throws IOException {
257
		WMSConnector drv = null;
258
		if(!updating) {
259
			drv = (WMSConnector) drivers.get(url.toString());
260
		} else {
261
			if(drivers.get(url.toString()) != null)
262
				drivers.remove(url.toString());
263
		}
264
		
265
		if (drv == null) {
266
			drv = new WMSConnector(url);
267
			drivers.put(url.toString(), drv);
268
		}
269
		
270
		return drv;
271
	}
272
	
273
	/**
274
	 * Obtiene el objeto que contiene que contiene la interpretaci?n de
275
	 * color por banda
276
	 * @return
277
	 */
278
	public ColorInterpretation getColorInterpretation() {
279
		if(super.getColorInterpretation() == null) {
280
			ColorInterpretation colorInterpretation = new DataStoreColorInterpretation(getBandCount());
281
			if(getBandCount() == 1 || getBandCount() == 2)
282
				colorInterpretation = DataStoreColorInterpretation.createGrayInterpretation();
283
			if(getBandCount() == 3)
284
				colorInterpretation = DataStoreColorInterpretation.createRGBInterpretation();
285
			if(getBandCount() == 4)
286
				colorInterpretation = DataStoreColorInterpretation.createRGBAInterpretation();
287
			setColorInterpretation(colorInterpretation);
288
		}
289
		return super.getColorInterpretation();
290
	}
291
	
292
	public AffineTransform getAffineTransform() {
293
		WMSDataParameters p = (WMSDataParameters)parameters;
294
		if(p.isSizeFixed()) {
295
			Extent e = getExtent(); // FIXME: it should also be taken from parameters instead of from the full layer extent
296
			double psX = e.width() / (p.getWidth() - 1);
297
			double psY = -(e.height() / (p.getHeight() - 1));
298
			ownTransformation = new AffineTransform(
299
					psX , 
300
					0, 
301
					0, 
302
					psY, 
303
					e.getULX() - (psX / 2),
304
					e.getULY() - (psY / 2));
305
		} else {
306
			Rectangle2D bbox = p.getExtent();
307
			double psX = bbox.getWidth() / p.getWidth();
308
			double psY = -(bbox.getHeight() / p.getHeight());
309
			ownTransformation = new AffineTransform(
310
					psX, 
311
					0, 
312
					0, 
313
					psY,
314
					bbox.getX(),
315
					(bbox.getY()+bbox.getHeight())); // FIXME: check for other CRSs such as 4326
316
		}
317
		externalTransformation = (AffineTransform) ownTransformation.clone();
318
		return ownTransformation;
319
	}
320
	
321
	/**
322
	 * Calcula el extent en coordenadas del mundo real
323
	 * @return Extent
324
	 */
325
	public Extent getExtent() {
326
		WMSDataParameters p = (WMSDataParameters)parameters;
327
		Vector<?> layerNames = Utilities.createVector(p.getLayerQuery(), ",");
328
		
329
		String[] ln = new String[layerNames.size()];
330
		for (int i = 0; i < ln.length; i++) {
331
			ln[i] = (String)layerNames.get(i);
332
		}
333
		Rectangle2D r = null;
334
		try {
335
			r = getConnector().getLayersExtent(ln, p.getSRSCode());
336
			if (r == null) {
337
				String latLonID = "EPSG:4326";
338
				r = getConnector().getLayersExtent(ln, latLonID);
339
				if (r == null) {
340
					r = getConnector().getLayersExtent(ln, "CRS:84");
341
				}
342
				
343
				IProjection reqProj = CRSFactory.getCRS(p.getSRSCode());
344
				IProjection latLonProj = CRSFactory.getCRS(latLonID);
345
				if ((reqProj != null) && (latLonProj != null)) {
346
					ICoordTrans ct = latLonProj.getCT(reqProj);
347
					Rectangle2D reprojectedRect = ct.convert(r);
348
					r = reprojectedRect;
349
				}
350
			}
351
		} catch (RemoteServiceException e) {
352
		}
353
		if(r == null)
354
			return null;
355
		return new ExtentImpl(r.getMinX(), r.getMaxY(), r.getMaxX(), r.getMinY());
356
	}
357

  
358
	public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
359
		return getConnector().getLayersExtent(new String[]{layerName}, srs);
360
	}
361

  
362
	public RasterProvider load() {
363
		return this;
364
	}
365
	
366
	public boolean isOpen() {
367
		return open;
368
	}
369

  
370
	public void close() {
371
		open = false;
372
	}
373
	
374
	public Transparency getTransparency() {
375
		if(fileTransparency == null)
376
			fileTransparency = new DataStoreTransparency(getColorInterpretation());
377
		return fileTransparency;
378
	}
379

  
380
	public String translateFileName(String fileName) {
381
		return fileName;
382
	}
383

  
384
	public void setView(Extent e) {
385
		viewRequest = e;
386
	}
387

  
388
	public Extent getView() {
389
		return viewRequest;
390
	}
391
	
392
	public double getWidth() {
393
		WMSDataParameters p = (WMSDataParameters)parameters;
394
		return p.getWidth();
395
	}
396

  
397
	public double getHeight() {
398
		WMSDataParameters p = (WMSDataParameters)parameters;
399
		return p.getHeight();
400
	}
401
	
402
	/**
403
	 * Gets WMS parameters
404
	 * @return
405
	 */
406
	public WMSDataParameters getParameters() {
407
		return (WMSDataParameters)parameters;
408
	}
409

  
410
	public Object readCompleteLine(int line, int band)
411
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
412
		return null;
413
	}
414
	
415
	/**
416
	 * When the remote layer has fixed size this method downloads the file and return its reference. 
417
	 * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
418
	 * useful to build an histogram or calculate statistics. This represents a sample of data.
419
	 * @return
420
	 * @throws RasterDriverException
421
	 */
422
	public File getFileLayer() throws RasterDriverException {
423
		if(fileLayerPixelSize != null)
424
			return fileLayerPixelSize;
425
		
426
		WMSDataParameters p = (WMSDataParameters)parameters;
427
		Extent e = getExtent();
428
		Rectangle2D bBox = new Rectangle2D.Double(e.getULX(), e.getLRY(), e.width(), e.height());
429
		WMSStatus wmsStatus = loadWMSStatus(bBox);
430
		
431
		if(!p.isSizeFixed()) {
432
			int w = 0;
433
			int h = 0;
434
			if(e.width() > e.height()) {
435
				w = FIXED_SIZE;
436
				h = (int)((e.height() * FIXED_SIZE) / e.width());
437
			} else {
438
				h = FIXED_SIZE;
439
				w = (int)((e.width() * FIXED_SIZE) / e.height());
440
			}
441
			wmsStatus.setWidth(w);
442
			wmsStatus.setHeight(h);
443
			fileLayerPixelSize = downloadFile(wmsStatus, e.getULX(), e.getULY(), e.getLRX(), e.getLRY(), w, h);
444
		} else {
445
			fileLayerPixelSize = downloadFile(wmsStatus, e.getULX(), e.getULY(), e.getLRX(), e.getLRY(), 
446
					p.getFixedSize().width, p.getFixedSize().height);
447
		}
448
		return fileLayerPixelSize;
449
	}
450

  
451
	/**
452
	 * Reads a complete block of data and returns an tridimensional array of the right type. This function is useful
453
	 * to read a file very fast without setting a view. In a WMS service when the size is fixed then it will read the
454
	 * entire image but when the source hasn't pixel size it will read a sample of data. This set of data will have
455
	 * the size defined in FIXED_SIZE. 
456
	 * 
457
	 * @param pos Posici?n donde se empieza  a leer
458
	 * @param blockHeight Altura m?xima del bloque leido
459
	 * @return Object que es un array tridimendional del tipo de datos del raster. (Bandas X Filas X Columnas)
460
	 * @throws InvalidSetViewException
461
	 * @throws FileNotOpenException
462
	 * @throws RasterDriverException
463
	 */
464
	public Object readBlock(int pos, int blockHeight, double scale) 
465
	throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
466
		File lastFile = getFileLayer();
467
		BandList bandList = new BandListImpl();
468
		for (int i = 0; i < 3; i++) {
469
			try {
470
				bandList.addBand(new DatasetBandImpl(lastFile.getPath(), pos, Buffer.TYPE_BYTE, 3));
471
			} catch (BandNotFoundInListException e1) {
472
			}
473
		}
474
		bandList.setDrawableBands(new int[]{0, 1, 2});
475

  
476
		try {
477
			lastRequestProvider = openLastRequest();
478
			return lastRequestProvider.readBlock(pos, blockHeight, scale);
479
		} catch (ProviderNotRegisteredException exc) {
480
			throw new RasterDriverException("Error building GdalDriver", exc);
481
		} catch (InitializeException exc) {
482
			throw new RasterDriverException("Error building GdalDriver", exc);
483
		}
484
	}
485
	
486
	public double getLastRequestHeight() throws RasterDriverException {
487
		if(lastRequestProvider == null) {
488
			try {
489
				lastRequestProvider = openLastRequest();
490
			} catch (ProviderNotRegisteredException e) {
491
				throw new RasterDriverException("Error building GdalDriver", e);
492
			} catch (InitializeException e) {
493
				throw new RasterDriverException("Error building GdalDriver", e);
494
			}
495
		}
496
		return lastRequestProvider.getHeight();
497
	}
498
	
499
	public double getLastRequestWidth() throws RasterDriverException {
500
		if(lastRequestProvider == null) {
501
			try {
502
				lastRequestProvider = openLastRequest();
503
			} catch (ProviderNotRegisteredException e) {
504
				throw new RasterDriverException("Error building GdalDriver", e);
505
			} catch (InitializeException e) {
506
				throw new RasterDriverException("Error building GdalDriver", e);
507
			}
508
		}
509
		return lastRequestProvider.getWidth();
510
	}
511
	
512
	public File getLastRequest() {
513
		return lastRequest;
514
	}
515
	
516
	public Buffer getBufferLastRequest() throws ProcessInterruptedException, RasterDriverException {
517
		try {
518
			lastRequestProvider = openLastRequest();
519
			return getDownloadedRaster(lastRequestProvider);
520
		} catch (ProviderNotRegisteredException e) {
521
			throw new RasterDriverException("Error building GdalDriver", e);
522
		} catch (InitializeException e) {
523
			throw new RasterDriverException("Error building GdalDriver", e);
524
		} catch (QueryException e) {
525
			throw new RasterDriverException("Error building GdalDriver", e);
526
		}
527
	}
528
	
529
	/**
530
	 * Opens the last request downloaded
531
	 * @return
532
	 * @throws ProviderNotRegisteredException
533
	 * @throws InitializeException
534
	 * @throws RasterDriverException
535
	 */
536
	private AbstractRasterProvider openLastRequest() throws ProviderNotRegisteredException, InitializeException, RasterDriverException {
537
		if(lastRequestProvider != null)
538
			lastRequestProvider.close();
539
		File lastFile = getFileLayer();
540
		lastRequestProvider = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
541
		setColorTable(lastRequestProvider.getColorTable());
542
		return lastRequestProvider;
543
	}
544

  
545
	public Object getData(int x, int y, int band)
546
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
547
		return null;
548
	}
549
	
550
	/**
551
	 * Gets the georeferencing file name form a raster file
552
	 * @param file
553
	 * a raster file
554
	 * @return
555
	 * a georeferencing file
556
	 */
557
	private String getWorldFile(String file){		
558
		String worldFile = file;
559
		int index = file.lastIndexOf(".");
560
		if (index > 0){			
561
			worldFile = file.substring(0, index) + getExtensionWorldFile();
562
		}
563
		return worldFile;
564
	}
565
	
566
	/**
567
	 * Obtiene la extensi?n del fichero de georreferenciaci?n
568
	 * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
569
	 * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
570
	 */
571
	private String getExtensionWorldFile() {
572
		WMSDataParameters p = (WMSDataParameters)parameters;
573
		String extWorldFile = ".wld";
574
		if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
575
			extWorldFile = ".tfw";
576
		}
577
		return extWorldFile;
578
	}
579
	
580
	public WMSStatus loadWMSStatus(Rectangle2D bBox) {
581
		WMSDataParameters p = (WMSDataParameters)parameters;
582
		WMSStatus wmsStatus = new WMSStatus();
583
		wmsStatus.setLayerNames(Utilities.createVector(p.getLayerQuery(), ","));
584
		wmsStatus.setSrs(p.getSRSCode());
585
		wmsStatus.setFormat(p.getFormat());
586
		wmsStatus.setInfoFormat(p.getInfoFormat());
587
		List<RemoteWMSStyle> listStyles = p.getStyles();
588
		Vector<?> v = listStyles != null ? new Vector<RemoteWMSStyle>(listStyles) : null; 
589
		wmsStatus.setStyles(v);
590
		wmsStatus.setDimensions(p.getDimensions());
591
		wmsStatus.setTransparency(p.isWmsTransparent());
592
		wmsStatus.setOnlineResource((String) p.getOnlineResource().get("GetMap"));
593
		if(p.isSizeFixed()) {
594
			wmsStatus.setExtent(getExtent().toRectangle2D());
595
		} else
596
			wmsStatus.setExtent(bBox);
597
		wmsStatus.setHeight(p.getHeight());
598
		wmsStatus.setWidth(p.getWidth());
599
		wmsStatus.setXyAxisOrder(p.isXyAxisOrder());
600
		IProjection proj = getProjection();
601
		if(proj != null)
602
			wmsStatus.setProjected(proj.isProjected());
603
		return wmsStatus;
604
	}
605
	
606
	/**
607
	 * This function downloads the file and creates the georeferencing file
608
	 * @param wmsStatus
609
	 * @param ulx
610
	 * @param uly
611
	 * @param lrx
612
	 * @param lry
613
	 * @param w
614
	 * @param h
615
	 * @return
616
	 * @throws RasterDriverException
617
	 */
618
	private File downloadFile(WMSStatus wmsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
619
		WMSDataParameters p = (WMSDataParameters)parameters;
620
		try {
621
			lastRequest = getConnector().getMap(wmsStatus, ((WMSDataParameters)parameters).getCancellable());
622
		} catch (RemoteServiceException e) {
623
			throw new RasterDriverException(e.getMessage(), e);
624
		}
625
		
626
		if(lastRequest == null)
627
			return null;
628
		
629
		String nameWorldFile = getWorldFile(lastRequest.getPath());
630
		try {
631
			if(p.isSizeFixed()) {
632
				Extent e = getExtent();
633
				fileUtil.createWorldFile(nameWorldFile, e, p.getWidth(), p.getHeight());
634
			} else {
635
				fileUtil.createWorldFile(nameWorldFile, new ExtentImpl(ulx, uly, lrx, lry), w, h);
636
			}
637
		} catch (IOException e) {
638
			throw new RasterDriverException("Error creating world file", e);
639
		}
640

  
641
		return lastRequest;
642
	}
643
	
644
	@Override
645
	public void loadBuffer(SpiRasterQuery q) 
646
			throws ProcessInterruptedException, RasterDriverException {
647
		Extent bbox = q.getRequestBoundingBox();
648
		lastWidthRequest = q.getBufWidth();
649
		lastHeightRequest = q.getBufHeight();
650
		WMSStatus wmsStatus = loadWMSStatus(bbox.toRectangle2D());
651
		
652
		lastRequest = downloadFile(wmsStatus, 
653
				bbox.getULX(), 
654
				bbox.getULY(), 
655
				bbox.getLRX(), 
656
				bbox.getLRY(), 
657
				q.getBufWidth(), 
658
				q.getBufHeight());
659
		
660
		if (lastRequest == null) {
661
			return;
662
		}
663
		
664
		Buffer b = null;
665
		try {
666
			b = getDownloadedRaster(lastRequest);
667
		} catch (QueryException e) {
668
			throw new RasterDriverException("Error building GdalDriver", e);
669
		} catch (ProviderNotRegisteredException e) {
670
			throw new RasterDriverException("Error building GdalDriver", e);
671
		} catch (InitializeException e) {
672
			throw new RasterDriverException("Error building GdalDriver", e);
673
		}
674
		q.setBufferResult(b);
675
	}
676
	
677
	private Buffer getDownloadedRaster(File f) throws ProcessInterruptedException, QueryException, ProviderNotRegisteredException, InitializeException {
678
		AbstractRasterProvider provider = DefaultProviderServices.loadProvider(new File(f.getPath()));
679
		setColorTable(provider.getColorTable());
680
		return getDownloadedRaster(provider);
681
	}
682
	
683
	private Buffer getDownloadedRaster(AbstractRasterProvider provider) throws ProcessInterruptedException, QueryException, ProviderNotRegisteredException, InitializeException {
684
		DefaultRasterStore store = new DefaultRasterStore();
685
		store.setProvider(provider);
686

  
687
		RasterQuery q = RasterLocator.getManager().createQuery();
688
		q.setAreaOfInterest();
689
		if(getColorInterpretation() != null)
690
			q.setDrawableBands(getColorInterpretation().buildRenderBands());
691
		if(store.getBandCount() > 3)
692
			q.forceARGBRequest();
693
		else 
694
			q.forceRGBRequest();
695
		
696
		Buffer buf = store.query(q);
697

  
698
		store.close();
699
		return buf;
700
	}
701
	
702
	/**
703
	 * Assigns the list of bands RGB and read a window of data
704
	 * @param rasterBuf
705
	 * @param bandList
706
	 * @param lastFile
707
	 * @param ulx
708
	 * @param uly
709
	 * @param lrx
710
	 * @param lry
711
	 * @return
712
	 * @throws RasterDriverException
713
	 * @throws ProcessInterruptedException
714
	 */
715
	/*public Buffer getBuffer(Buffer rasterBuf, BandList bandList, File lastFile, 
716
			double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
717
		try {
718
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
719
			String serverName = bandList.getBand(0).getFileName();
720
			for (int i = 0; i < bandList.getBandCount(); i++) {
721
				bandList.getBand(i).setFileName(lastFile.getPath());
722
			}
723
			
724
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
725
			setColorTable(driver.getColorTable());
726
			
727
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
728
			q.setAreaOfInterest(new ExtentImpl(ulx, uly, lrx, lry));
729
			q.setBandList(bandList);
730
			q.setBuffer(rasterBuf);
731
			Buffer buf = driver.getDataSet(q);
732
			
733
			for (int i = 0; i < bandList.getBandCount(); i++) {
734
				bandList.getBand(i).setFileName(serverName);
735
			}
736
			
737
			return buf;
738
		} catch (ProviderNotRegisteredException e) {
739
			throw new RasterDriverException("Error building GdalDriver", e);
740
		} catch (InitializeException e) {
741
			throw new RasterDriverException("Error building GdalDriver", e);
742
		}
743
	}*/
744
	
745
	/*public void getWindow(Extent ex, int bufWidth, int bufHeight, 
746
			BandList bandList, TileListener listener, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
747

  
748
		Buffer raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], bufWidth, bufHeight, 3, true);
749
		getWindow(ex, bufWidth, bufHeight, bandList, raster, true, null);
750
		raster.setDataExtent(ex.toRectangle2D());
751

  
752
		TileCacheManager m = TileCacheLocator.getManager();
753
		org.gvsig.raster.cache.tile.Tile t = m.createTile(-1, 0, 0);
754
		t.setData(new Object[]{raster});
755
		t.setUl(new Point2D.Double(ex.getULX(), ex.getULY()));
756
		t.setLr(new Point2D.Double(ex.getLRX(), ex.getLRY()));
757
		t.setDownloaderParams("AffineTransform", getAffineTransform());
758
		t.setDownloaderParams("Tiling", new Boolean(false));
759
		try {
760
			listener.tileReady(t);
761
		} catch (TileGettingException e) {
762
			throw new RasterDriverException("Error throwing a tile", e);
763
		}
764

  
765
		//listener.nextBuffer(raster, null, new ExtentImpl(minX, minY, maxX, maxY), getAffineTransform(), null, false);
766
		listener.endReading();
767
	}*/
768

  
769
	/*public Buffer getWindow(Extent ex, BandList bandList, Buffer rasterBuf, TaskStatus status) 
770
		throws ProcessInterruptedException, RasterDriverException {
771
		Rectangle2D bBox = ex.toRectangle2D();
772
		lastWidthRequest = rasterBuf.getWidth();
773
		lastHeightRequest = rasterBuf.getHeight();
774
		WMSStatus wmsStatus = loadWMSStatus(bBox);
775
		
776
		lastRequest = downloadFile(wmsStatus, ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), rasterBuf.getWidth(), rasterBuf.getHeight());
777
		
778
		if (lastRequest == null) {
779
			return rasterBuf;
780
		}
781
		
782
		try {
783
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
784
			String serverName = bandList.getBand(0).getFileName();
785
			for (int i = 0; i < bandList.getBandCount(); i++) {
786
				bandList.getBand(i).setFileName(lastRequest.getPath());
787
			}
788
			
789
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
790
			setColorTable(driver.getColorTable());
791
			
792
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
793
			q.setAreaOfInterest(ex);
794
			q.setBandList(bandList);
795
			q.setBuffer(rasterBuf);
796
			Buffer buf = driver.getDataSet(q);
797
			
798
			for (int i = 0; i < bandList.getBandCount(); i++) {
799
				bandList.getBand(i).setFileName(serverName);
800
			}
801
			driver.close();
802
			return buf;
803
		} catch (ProviderNotRegisteredException e) {
804
			throw new RasterDriverException("Error building GdalDriver", e);
805
		} catch (InitializeException e) {
806
			throw new RasterDriverException("Error building GdalDriver", e);
807
		}
808
	}*/
809

  
810
	/*public Buffer getWindow(double ulx, double uly, double w, double h, 
811
			BandList bandList, Buffer rasterBuf, boolean adjustToExtent, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
812
		Rectangle2D bBox = new Rectangle2D.Double(ulx, uly, w, h);
813
		lastWidthRequest = rasterBuf.getWidth();
814
		lastHeightRequest = rasterBuf.getHeight();
815
		WMSStatus wmsStatus = loadWMSStatus(bBox);
816
		
817
		lastRequest = downloadFile(wmsStatus, ulx, uly, ulx + w, uly - h, rasterBuf.getWidth(), rasterBuf.getHeight());
818
		
819
		if (lastRequest == null) {
820
			return rasterBuf;
821
		}
822
		
823
		try {
824
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
825
			String serverName = bandList.getBand(0).getFileName();
826
			for (int i = 0; i < bandList.getBandCount(); i++) {
827
				bandList.getBand(i).setFileName(lastRequest.getPath());
828
			}
829
			
830
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
831
			setColorTable(driver.getColorTable());
832
			
833
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
834
			q.setAreaOfInterest(ulx, uly, w, h);
835
			q.setBandList(bandList);
836
			q.setBuffer(rasterBuf);
837
			q.setAdjustToExtent(adjustToExtent);
838
			
839
			Buffer buf = driver.getDataSet(q);
840
			
841
			for (int i = 0; i < bandList.getBandCount(); i++) {
842
				bandList.getBand(i).setFileName(serverName);
843
			}
844
			
845
			return buf;
846
		} catch (ProviderNotRegisteredException e) {
847
			throw new RasterDriverException("Error building GdalDriver", e);
848
		} catch (InitializeException e) {
849
			throw new RasterDriverException("Error building GdalDriver", e);
850
		}
851
	}*/
852

  
853
	/*public Buffer getWindow(Extent extent, int bufWidth, int bufHeight, 
854
			BandList bandList, Buffer rasterBuf, boolean adjustToExtent, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
855
		Rectangle2D bBox = extent.toRectangle2D();//new Rectangle2D.Double(ulx, lry, Math.abs(lrx - ulx), Math.abs(lry - uly));
856
		lastWidthRequest = rasterBuf.getWidth();
857
		lastHeightRequest = rasterBuf.getHeight();
858
		WMSStatus wmsStatus = loadWMSStatus(bBox);
859
		lastRequest = downloadFile(wmsStatus, extent.getULX(), extent.getULY(), extent.getLRX(), extent.getLRY(), rasterBuf.getWidth(), rasterBuf.getHeight());
860
		
861
		if (lastRequest == null) {
862
			return rasterBuf;
863
		}
864
		
865
		try {
866
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
867
			String serverName = bandList.getBand(0).getFileName();
868
			for (int i = 0; i < bandList.getBandCount(); i++) {
869
				bandList.getBand(i).setFileName(lastRequest.getPath());
870
			}
871
			
872
			AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
873
			setColorTable(driver.getColorTable());
874
			
875
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
876
			q.setAreaOfInterest(extent, bufWidth, bufHeight);
877
			q.setBandList(bandList);
878
			q.setBuffer(rasterBuf);
879
			q.setAdjustToExtent(adjustToExtent);
880
			Buffer buf = driver.getDataSet(q);
881

  
882
			for (int i = 0; i < bandList.getBandCount(); i++) {
883
				bandList.getBand(i).setFileName(serverName);
884
			}
885
			
886
			return buf;
887
		} catch (ProviderNotRegisteredException e) {
888
			throw new RasterDriverException("Error building GdalDriver", e);
889
		} catch (InitializeException e) {
890
			throw new RasterDriverException("Error building GdalDriver", e);
891
		}
892
	}*/
893

  
894
//	public Buffer getWindow(int x, int y, 
895
//			BandList bandList, Buffer rasterBuf) throws ProcessInterruptedException, RasterDriverException {
896
//		int w = rasterBuf.getWidth();
897
//		int h = rasterBuf.getHeight();
898
//		Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
899
//		Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
900
//		lastWidthRequest = rasterBuf.getWidth();
901
//		lastHeightRequest = rasterBuf.getHeight();
902
//		Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p1.getX()), Math.abs(p1.getY() - p2.getY()));
903
//		WMSStatus wmsStatus = loadWMSStatus(bBox);
904
//		
905
//		lastRequest = downloadFile(wmsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), rasterBuf.getWidth(), rasterBuf.getHeight());
906
//		
907
//		if (lastRequest == null) {
908
//			return rasterBuf;
909
//		}
910
//
911
//		AbstractRasterProvider driver = null;
912
//		try {
913
//			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
914
//			String serverName = bandList.getBand(0).getFileName();
915
//			for (int i = 0; i < bandList.getBandCount(); i++) {
916
//				bandList.getBand(i).setFileName(lastRequest.getPath());
917
//			}
918
//			
919
//			driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
920
//			Buffer buf = driver.getWindow(0, 0, w, h, bandList, rasterBuf);
921
//
922
//			for (int i = 0; i < bandList.getBandCount(); i++) {
923
//				bandList.getBand(i).setFileName(serverName);
924
//			}
925
//			
926
//			return buf;
927
//		} catch (ProviderNotRegisteredException e) {
928
//			throw new RasterDriverException("Error building GdalDriver", e);
929
//		} catch (InitializeException e) {
930
//			throw new RasterDriverException("Error building GdalDriver", e);
931
//		}
932
//	}
933

  
934
	/*public Buffer getWindow(int x, int y, int w, int h, 
935
			BandList bandList, Buffer rasterBuf, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
936
		Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
937
		Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
938
		lastWidthRequest = rasterBuf.getWidth();
939
		lastHeightRequest = rasterBuf.getHeight();
940
		Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p1.getX()), Math.abs(p1.getY() - p2.getY()));
941
		WMSStatus wmsStatus = loadWMSStatus(bBox);
942
		
943
		lastRequest = downloadFile(wmsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), rasterBuf.getWidth(), rasterBuf.getHeight());
944
		
945
		if (lastRequest == null) {
946
			return rasterBuf;
947
		}
948

  
949
		AbstractRasterProvider driver = null;
950
		try {
951
			//El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
952
			String serverName = bandList.getBand(0).getFileName();
953
			for (int i = 0; i < bandList.getBandCount(); i++) {
954
				bandList.getBand(i).setFileName(lastRequest.getPath());
955
			}
956
			
957
			driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
958
			setColorTable(driver.getColorTable());
959
			
960
			DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
961
			q.setAreaOfInterest(0, 0, w, h);
962
			q.setBandList(bandList);
963
			q.setBuffer(rasterBuf);
964
			Buffer buf = driver.getDataSet(q);
965

  
966
			for (int i = 0; i < bandList.getBandCount(); i++) {
967
				bandList.getBand(i).setFileName(serverName);
968
			}
969
			
970
			return buf;
971
		} catch (ProviderNotRegisteredException e) {
972
			throw new RasterDriverException("Error building GdalDriver", e);
973
		} catch (InitializeException e) {
974
			throw new RasterDriverException("Error building GdalDriver", e);
975
		}
976
	}*/
977

  
978
	public Image getImageLegend() {
979
		try {
980
			WMSStatus wmsStatus = loadWMSStatus(getExtent().toRectangle2D());
981
			wmsStatus.setOnlineResource((String) getParameters().getOnlineResource().get("GetCapabilities"));
982
			File file = getConnector().getLegendGraphic(wmsStatus, getParameters().getLayerQuery(), null);
983
			Image img = null;
984
			if ((file != null) && (file.length() > 0)) {
985
				img = new ImageIcon(file.getAbsolutePath()).getImage();
986
			}
987
			return img;
988
		} catch (Exception e) {
989
			logger.info("Problems in GetLegendGraphic", e);
990
		}
991
		return null;
992
	}
993

  
994
	public int getBlockSize() {
995
		return 0;
996
	}
997

  
998
	public void setAffineTransform(AffineTransform t){
999
		
1000
	}
1001

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff