Revision 4431

View differences:

org.gvsig.raster.wmts/tags/org.gvsig.raster.wmts-2.2.17/org.gvsig.raster.wmts.io/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.raster.wmts.io.DefaultWMTSIOLibrary
org.gvsig.raster.wmts/tags/org.gvsig.raster.wmts-2.2.17/org.gvsig.raster.wmts.io/src/main/java/org/gvsig/raster/wmts/io/downloader/TileDownloaderForWMTS.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.wmts.io.downloader;
23

  
24
import java.io.File;
25
import java.io.IOException;
26
import java.net.ConnectException;
27
import java.net.URL;
28

  
29
import org.gvsig.compat.net.ICancellable;
30
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
31
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
32
import org.gvsig.raster.cache.tile.Tile;
33
import org.gvsig.raster.cache.tile.exception.TileGettingException;
34
import org.gvsig.raster.impl.provider.tile.BaseTileDownloader;
35
import org.gvsig.raster.wmts.io.WMTSDataParameters;
36
import org.gvsig.raster.wmts.ogc.WMTSClient;
37
import org.gvsig.raster.wmts.ogc.WMTSOGCLocator;
38
import org.gvsig.raster.wmts.ogc.WMTSStatus;
39
import org.gvsig.raster.wmts.ogc.exception.ServerErrorException;
40
import org.gvsig.raster.wmts.ogc.exception.WMTSException;
41

  
42
/**
43
 * Tile getter
44
 * @author Nacho Brodin (nachobrodin@gmail.com)
45
 */
46
public class TileDownloaderForWMTS extends BaseTileDownloader {
47
	private WMTSClient             ogcClient  = null;
48

  
49
	public TileDownloaderForWMTS(RasterDataStore store,
50
			int tilePxWidth,
51
			int tilePxHeight) {
52
		super(store, tilePxWidth, tilePxHeight);
53
	}
54

  
55
	/**
56
	 * Gets the connector from the URL
57
	 * @return
58
	 * @throws RemoteServiceException
59
	 */
60
	public WMTSClient getOGCClient() throws WMTSException {
61
		if(ogcClient == null) {
62
			WMTSDataParameters p = (WMTSDataParameters)store.getParameters();
63
			ogcClient = p.getOGCClient();
64
			if(ogcClient != null)
65
				return ogcClient;
66

  
67
			URL url = null;
68
			try {
69
				url = p.getURI().toURL();
70
			} catch (Exception e) {
71
				throw new WMTSException("Malformed URL",e);
72
			}
73
			try {
74
				ogcClient = WMTSOGCLocator.getManager().createWMTSClient(url.toString());
75
				ogcClient.connect(false, new ICancellable() {
76
					public boolean isCanceled() {
77
						return false;
78
					}
79

  
80
					public Object getID() {
81
						return null;
82
					}
83
				});
84
			} catch (ConnectException e) {
85
				throw new WMTSException("Connect exception",e);
86
			} catch (IOException e) {
87
				throw new WMTSException("Connect exception",e);
88
			}
89
		}
90
		return ogcClient;
91
	}
92

  
93
	public synchronized Tile downloadTile(Tile tile) throws TileGettingException {
94
		try {
95
			WMTSStatus status = (WMTSStatus)tile.getDownloaderParams("WMTSStatus");
96
			status.setTileRow(tile.getRow());
97
			status.setTileCol(tile.getCol());
98

  
99
			String urlFromTemplate = status.getResourceURL(tile.getRow() + "" + tile.getCol() + "");
100
			//System.out.println(urlFromTemplate);
101
			File f = null;
102
			if(urlFromTemplate != null)
103
				f = getOGCClient().getTile(urlFromTemplate, tile.getCancelled(), tile.getFile());
104
			else
105
				f = getOGCClient().getTile(status, tile.getCancelled(), tile.getFile());
106
			tile.setFile(f);
107
			//Si borramos el rmf no se puede leer la etiqueta Alpha. En caso de que se modifique jgdal para
108
			//poder guardar esta etiqueta deberiamos borrar el rmf para ahorrar ficheros
109
			//File rmf = new File(tile.getFile().getAbsolutePath() + ".rmf");
110
			//if(rmf.exists())
111
				//rmf.delete();
112
		} catch (WMTSException e) {
113
			throw new TileGettingException(e);
114
		} catch (ServerErrorException e) {
115
			throw new TileGettingException(e);
116
		}
117
		readTileFromDisk(tile);
118
		return tile;
119
	}
120

  
121
}
0 122

  
org.gvsig.raster.wmts/tags/org.gvsig.raster.wmts-2.2.17/org.gvsig.raster.wmts.io/src/main/java/org/gvsig/raster/wmts/io/downloader/WMTSTileServer.java
1
package org.gvsig.raster.wmts.io.downloader;
2

  
3
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
4
import org.gvsig.raster.cache.tile.provider.CacheStruct;
5
import org.gvsig.raster.cache.tile.provider.Downloader;
6
import org.gvsig.raster.cache.tile.provider.TileServer;
7
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrix;
8
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrixSetLink;
9

  
10
/** 
11
* Data server for the tile cache in a WMTSProvider 
12
* @author Nacho Brodin (nachobrodin@gmail.com)
13
*/
14
public class WMTSTileServer implements TileServer {
15
	private CacheStruct                struct               = null;
16
	private Downloader                 downloader           = null;
17
	private RasterDataStore            store                = null;
18
	private String                     suffix               = ".tif";
19
	private WMTSTileMatrixSetLink      tileMatrixSetLink    = null;
20
	
21
	public WMTSTileServer(RasterDataStore store, 
22
			WMTSTileMatrixSetLink tileMatrixSetLink) {
23
		this.store = store;
24
		this.tileMatrixSetLink = tileMatrixSetLink;
25
	}
26
	
27
	public Downloader getDownloader() {
28
		//if(downloader == null) {
29
			int tileWidth = ((WMTSTileMatrix)tileMatrixSetLink.getTileMatrixSet().getTileMatrix().get(0)).getTileWidth();
30
			int tileHeight = ((WMTSTileMatrix)tileMatrixSetLink.getTileMatrixSet().getTileMatrix().get(0)).getTileHeight();
31
			downloader = new TileDownloaderForWMTS(store, tileWidth, tileHeight);
32
		//}
33
		return downloader;
34
	}
35

  
36
	public CacheStruct getStruct() {
37
		if(struct == null) {
38
			struct = new WMTSCacheStruct(store, tileMatrixSetLink);
39
		}
40
		return struct;
41
	}
42
	
43
	public void setStruct(CacheStruct struct) {
44
		//La structura de cache es proporcionada por el servidor
45
	}
46
	
47
	public String getFileSuffix() {
48
		return suffix;
49
	}
50
	
51
	public void setFileSuffix(String extension) {
52
		this.suffix = extension;
53
	}
54
}
0 55

  
org.gvsig.raster.wmts/tags/org.gvsig.raster.wmts-2.2.17/org.gvsig.raster.wmts.io/src/main/java/org/gvsig/raster/wmts/io/downloader/WMTSCacheStruct.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.wmts.io.downloader;
23

  
24
import java.awt.geom.Point2D;
25
import java.awt.geom.Rectangle2D;
26
import java.io.File;
27
import java.net.URL;
28
import java.util.ArrayList;
29
import java.util.List;
30

  
31
import org.gvsig.fmap.dal.coverage.RasterLocator;
32
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
33
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
34
import org.gvsig.fmap.dal.coverage.util.MathUtils;
35
import org.gvsig.raster.cache.tile.Tile;
36
import org.gvsig.raster.cache.tile.TileCacheLocator;
37
import org.gvsig.raster.cache.tile.exception.TileBuildException;
38
import org.gvsig.raster.cache.tile.provider.CacheStruct;
39
import org.gvsig.raster.wmts.io.WMTSDataParameters;
40
import org.gvsig.raster.wmts.io.WMTSProvider;
41
import org.gvsig.raster.wmts.ogc.WMTSStatus;
42
import org.gvsig.raster.wmts.ogc.struct.WMTSTile;
43
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrix;
44
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrixLimits;
45
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrixSet;
46
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrixSetLink;
47

  
48
/**
49
 * Implementation for a structure of a cache
50
 * @author Nacho Brodin (nachobrodin@gmail.com)
51
 */
52
public class WMTSCacheStruct implements CacheStruct {
53
    private String                        layerName           = null;
54
	private String                        serverURL           = null;
55
	private WMTSTileMatrixSet             tileMatrixSet       = null;
56
	private List<WMTSTileMatrixLimits>    tileMatrixSetLimits = null;
57
	private double[]                      pixelSize           = null;
58
    private RasterDataStore               store               = null;
59

  
60
    public WMTSCacheStruct(RasterDataStore store, WMTSTileMatrixSetLink tileMatrixSetLink) {
61
    	this.store = store;
62
    	this.tileMatrixSet = tileMatrixSetLink.getTileMatrixSet();
63
		this.tileMatrixSetLimits = tileMatrixSetLink.getTileMatrixLimits();
64
		pixelSize = ((WMTSProvider)store.getProvider()).getPixelSizeByLevel();
65
		serverURL = ((WMTSProvider)store.getProvider()).getURIOfFirstProvider().getPath();
66
		layerName = ((WMTSDataParameters)store.getParameters()).getLayer().getTitle();
67
    }
68

  
69
	public int getNumberOfLevels() {
70
		return tileMatrixSet.getTileMatrix().size();
71
	}
72

  
73
	public String getLayerName() {
74
		return layerName;
75
	}
76

  
77
	public String getServerURL() {
78
		return serverURL + getDimension();
79
	}
80

  
81
	public int[] getTileSizeByLevel(int level) {
82
		return new int[] {
83
			((WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level)).getTileWidth(),
84
			((WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level)).getTileHeight()
85
		};
86
	}
87

  
88
	public int getLayerWidthOfTileMatrixByLevel(int level) {
89
		if(tileMatrixSetLimits != null && tileMatrixSetLimits.size() > level) {
90
			WMTSTileMatrixLimits l = (WMTSTileMatrixLimits)tileMatrixSetLimits.get(level);
91
			return l.getMaxTileRow() - l.getMinTileRow();
92
		} else {
93
			WMTSTileMatrix tm = (WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level);
94
			return (int)tm.getMatrixWidth();
95
		}
96
	}
97

  
98
	public int getLayerHeightOfTileMatrixByLevel(int level) {
99
		if(tileMatrixSetLimits != null && tileMatrixSetLimits.size() > level) {
100
			WMTSTileMatrixLimits l = (WMTSTileMatrixLimits)tileMatrixSetLimits.get(level);
101
			return l.getMaxTileCol() - l.getMinTileCol();
102
		} else {
103
			WMTSTileMatrix tm = (WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level);
104
			return (int)tm.getMatrixHeight();
105
		}
106
	}
107

  
108
	public int getLayerInitXTilePositionByLevel(int level) {
109
		if(tileMatrixSetLimits != null && tileMatrixSetLimits.size() > level) {
110
			WMTSTileMatrixLimits l = (WMTSTileMatrixLimits)tileMatrixSetLimits.get(level);
111
			return l.getMinTileCol();
112
		} else
113
			return 0;
114
	}
115

  
116
	public int getLayerInitYTilePositionByLevel(int level) {
117
		if(tileMatrixSetLimits != null && tileMatrixSetLimits.size() > level) {
118
			WMTSTileMatrixLimits l = (WMTSTileMatrixLimits)tileMatrixSetLimits.get(level);
119
			return l.getMinTileRow();
120
		} else
121
			return 0;
122
	}
123

  
124
	public long getWorldHeightOfTileMatrixByLevel(int level) {
125
		return ((WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level)).getMatrixWidth();
126
	}
127

  
128
	public long getWorldWidthOfTileMatrixByLevel(int level) {
129
		return ((WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level)).getMatrixHeight();
130
	}
131

  
132
	public double getPixelSizeByLevel(int level) {
133
		if(level < pixelSize.length)
134
			return pixelSize[level];
135
		else
136
			return pixelSize[pixelSize.length - 1];
137
	}
138

  
139
	public Point2D[] getTileExtent(Tile tile) {
140
		return getTileExtent(tile.getLevel(), tile.getCol(), tile.getRow());
141
	}
142

  
143
	public Point2D[] getTileExtent(int level, int col, int row) {
144
		double[] ul = tileMatrixSet.getBoundingBox().getUpperCorner();
145
		long tileWidth = ((WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level)).getTileWidth();
146
		long tileHeight = ((WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level)).getTileHeight();
147
		double mtsWidthTile = tileWidth * pixelSize[level];
148
		double mtsHeightTile = tileHeight * pixelSize[level];
149
		double ulx = ul[0] + (col * mtsWidthTile);
150
		double uly = ulx + mtsWidthTile;
151
		double lrx = ul[1] - (row * mtsHeightTile);
152
		double lry = lrx - mtsHeightTile;
153
		return new Point2D[]{new Point2D.Double(ulx, uly), new Point2D.Double(lrx, lry)};
154
	}
155

  
156
	public Tile getTileStructure(int level, int tileCol, int tileRow, Point2D ul, Point2D lr) throws TileBuildException  {
157
		int[] size = getTileSizeByLevel(level);
158
		Tile tile = TileCacheLocator.getManager().createTile(level, tileRow, tileCol);
159
		tile.setUl(ul);
160
		tile.setLr(lr);
161
		tile.setWidthPx(size[0]);
162
		tile.setHeightPx(size[1]);
163

  
164
		Rectangle2D r = new Rectangle2D.Double(Math.min(ul.getX(), lr.getX()),
165
				Math.min(ul.getY(), lr.getY()),
166
				Math.abs(ul.getX() - lr.getX()),
167
				Math.abs(ul.getY() - lr.getY()));
168
		int bufWidth = (int)(r.getWidth() / getPixelSizeByLevel(level));
169
		int bufHeight = (int)(r.getHeight() / getPixelSizeByLevel(level));
170
		try {
171
			WMTSStatus status = ((WMTSProvider)store.getProvider()).buildWMTSStatus(r, bufWidth, bufHeight);
172
			tile.setDownloaderParams("WMTSStatus", status);
173
		} catch (RasterDriverException e) {
174
			throw new TileBuildException(e);
175
		}
176

  
177
		return tile;
178
	}
179

  
180
	public List<Tile> getTileList(Point2D ul, Point2D lr, double mtsPixelRequest) throws TileBuildException {
181
		Rectangle2D r = new Rectangle2D.Double(Math.min(ul.getX(), lr.getX()),
182
				Math.min(ul.getY(), lr.getY()),
183
				Math.abs(ul.getX() - lr.getX()),
184
				Math.abs(ul.getY() - lr.getY()));
185
		int bufWidth = (int)(r.getWidth() / mtsPixelRequest);
186
		int bufHeight = (int)(r.getHeight() / mtsPixelRequest);
187
		try {
188
			WMTSStatus status = ((WMTSProvider)store.getProvider()).buildWMTSStatus(r, bufWidth, bufHeight);
189

  
190
			//Conversi?n a tiles de la librer?a
191
			List<WMTSTile> tiles = status.getTileList();
192
			List<Tile> tileList = new ArrayList<Tile>();
193
			for (int i = 0; i < tiles.size(); i++) {
194
				WMTSTile tOrigin = (WMTSTile) tiles.get(i);
195
				Tile t = TileCacheLocator.getManager().createTile(status.getLevel(), tOrigin.getCol(), tOrigin.getRow());
196
				t.setUl(new Point2D.Double(tOrigin.getULX(), tOrigin.getULY()));
197
				t.setLr(new Point2D.Double(tOrigin.getLRX(), tOrigin.getLRY()));
198
				t.setWidthPx(tOrigin.getWidthPx());
199
				t.setHeightPx(tOrigin.getHeightPx());
200
				t.setDownloaderParams("WMTSStatus", status.cloneStatus());
201
				tileList.add(t);
202
			}
203
			return tileList;
204
		} catch (RasterDriverException e) {
205
			throw new TileBuildException(e);
206
		}
207
	}
208

  
209
	public double[] getTileSizeInRealCoordsByLevel(int level) {
210
		return new double[] {
211
				getPixelSizeByLevel(level) * getTileSizeByLevel(level)[0],
212
				getPixelSizeByLevel(level) *  getTileSizeByLevel(level)[1]
213
			};
214
	}
215

  
216
	public String getFileSuffix() {
217
		return ((WMTSProvider)store.getProvider()).getFileSuffix();
218
	}
219

  
220
	public boolean compare(CacheStruct struct) {
221
		MathUtils mu = RasterLocator.getManager().getMathUtils();
222
		//Compara: n?mero de niveles, tama?o de tile,
223
		//anchoXalto de la matriz, tama?o de pixel por nivel,
224
		//coordenadas de al menos un tile de la matriz
225
		if(struct.getNumberOfLevels() == getNumberOfLevels()) {
226
			for (int i = 0; i < getNumberOfLevels(); i++) {
227
				if(	struct.getTileSizeByLevel(i)[0] == getTileSizeByLevel(i)[0] &&
228
					struct.getTileSizeByLevel(i)[1] == getTileSizeByLevel(i)[1] &&
229
					struct.getWorldHeightOfTileMatrixByLevel(i) == getWorldHeightOfTileMatrixByLevel(i) &&
230
					struct.getWorldWidthOfTileMatrixByLevel(i) == getWorldWidthOfTileMatrixByLevel(i) &&
231
					mu.clipDecimals(struct.getPixelSizeByLevel(i), 2) == mu.clipDecimals(getPixelSizeByLevel(i), 2) &&
232
					compareExtents(struct.getTileExtent(i, 0, 0), getTileExtent(i, 0, 0))) {
233
					return true;
234
				}
235
			}
236
		}
237
		return false;
238
	}
239

  
240
	private boolean compareExtents(Point2D[] p, Point2D[] p1) {
241
		return (p[0].getX() == p1[0].getX() && p[0].getY() == p1[0].getY() &&
242
				p[1].getX() == p1[1].getX() && p[1].getY() == p1[1].getY());
243
	}
244

  
245
	public String getEPSG() {
246
		/*IProjection proj = provider.getProjection();
247
		if(proj != null)
248
			return proj.getAbrev();
249
		return null;*/
250
		return ((WMTSProvider)store.getProvider()).getSRSCode();
251
	}
252

  
253
	private String getDimension() {
254
		WMTSDataParameters p = (WMTSDataParameters)(((WMTSProvider)store.getProvider()).getDataParameters());
255
		String dimension = p.getDimension();
256
		String dimensionValue = p.getDimensionSelectedValue();
257
		if(dimension != null && dimensionValue != null)
258
			return dimension + "_" + dimensionValue;
259
		return "";
260
	}
261

  
262
	public String getFileSize() {
263
		return "0";
264
	}
265

  
266
	public List<Tile> getTileList(int x, int y, int w, int h) {
267
		return null;
268
	}
269

  
270
	public ArrayList<Tile> getTileList(Rectangle2D r) {
271
		return null;
272
	}
273
}
0 274

  
org.gvsig.raster.wmts/tags/org.gvsig.raster.wmts-2.2.17/org.gvsig.raster.wmts.io/src/main/java/org/gvsig/raster/wmts/io/package.html
1
<?xml version="1.0" encoding="UTF-8" ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
<html xmlns="http://www.w3.org/1999/xhtml">
4
<head>
5
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6
<title>org.gvsig.raster.wmts.io package documentation</title>
7
</head>
8
<body>
9

  
10
	<p>WMTS provider</p>
11

  
12
</body>
13
</html>
0 14

  
org.gvsig.raster.wmts/tags/org.gvsig.raster.wmts-2.2.17/org.gvsig.raster.wmts.io/src/main/java/org/gvsig/raster/wmts/io/WMTSServerExplorer.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
*
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
*
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
*
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
* MA  02110-1301, USA.
20
*
21
*/
22

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
package org.gvsig.raster.wmts.io;
29

  
30
import java.io.IOException;
31
import java.io.InputStream;
32
import java.net.MalformedURLException;
33
import java.net.URI;
34
import java.net.URISyntaxException;
35
import java.net.URL;
36
import java.net.URLConnection;
37
import java.util.List;
38

  
39
import org.slf4j.Logger;
40
import org.slf4j.LoggerFactory;
41

  
42
import org.gvsig.compat.net.ICancellable;
43
import org.gvsig.fmap.dal.DALLocator;
44
import org.gvsig.fmap.dal.DataManager;
45
import org.gvsig.fmap.dal.DataServerExplorerParameters;
46
import org.gvsig.fmap.dal.DataStoreParameters;
47
import org.gvsig.fmap.dal.NewDataStoreParameters;
48
import org.gvsig.fmap.dal.coverage.exception.ConnectException;
49
import org.gvsig.fmap.dal.coverage.store.RasterDataServerExplorer;
50
import org.gvsig.fmap.dal.coverage.store.parameter.TileDataParameters;
51
import org.gvsig.fmap.dal.exception.DataException;
52
import org.gvsig.fmap.dal.exception.InitializeException;
53
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
54
import org.gvsig.fmap.dal.spi.DataServerExplorerProvider;
55
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
56
import org.gvsig.raster.wmts.ogc.WMTSClient;
57
import org.gvsig.raster.wmts.ogc.WMTSOGCLocator;
58

  
59
/**
60
 * Explorer for a WMTS server
61
 * @author Nacho Brodin (nachobrodin@gmail.com)
62
 */
63
public class WMTSServerExplorer implements RasterDataServerExplorer, DataServerExplorerProvider {
64
	public static final String           NAME                     = WMTSProvider.NAME;
65
	private WMTSClient                   ogcClient                = null;
66
	private WMTSServerExplorerParameters parameters               = null;
67
	private static final Logger         logger                    = LoggerFactory.getLogger(WMTSServerExplorer.class);
68

  
69
	public WMTSServerExplorer(
70
			WMTSServerExplorerParameters parameters,
71
			DataServerExplorerProviderServices services)
72
			throws InitializeException {
73
		this.parameters = parameters;
74
	}
75

  
76
	public String getDataStoreProviderName() {
77
		return WMTSProvider.NAME;
78
	}
79

  
80
	public String getDescription() {
81
		return WMTSProvider.DESCRIPTION;
82
	}
83

  
84
	public boolean add(String provider, NewDataStoreParameters parameters,
85
			boolean overwrite) throws DataException {
86
		return false;
87
	}
88

  
89
	public boolean canAdd() {
90
		return false;
91
	}
92

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

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

  
102
	public List<?> getDataStoreProviderNames() {
103
		return null;
104
	}
105

  
106
	public DataServerExplorerParameters getParameters() {
107
		return parameters;
108
	}
109

  
110
	public List<?> list() throws DataException {
111
		return null;
112
	}
113

  
114
	public List<?> list(int mode) throws DataException {
115
		return null;
116
	}
117

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

  
120
	}
121

  
122
	public void dispose() {
123

  
124
	}
125

  
126
	public String getProviderName() {
127
		return WMTSProvider.NAME;
128
	}
129

  
130
	//**********************************************
131
	//Connector
132
	//**********************************************
133

  
134
	public DataStoreParameters getStoredParameters() {
135
		DataManager manager = DALLocator.getDataManager();
136
		WMTSDataParameters wmtsParams = null;
137
		try {
138
			wmtsParams = (WMTSDataParameters) manager.createStoreParameters(this.getDataStoreProviderName());
139
			String host = parameters.getHost();
140
            try {
141
                wmtsParams.setURI(new URI(host));
142
            } catch (URISyntaxException e) {
143
                logger.warn("Can't create URI from "+host, e);
144
            }
145
			wmtsParams.setOGCClient(getOGCClient());
146

  
147
			if(WMTSProvider.TILED) {
148
				TileDataParameters tileParams = (TileDataParameters) manager.createStoreParameters("Tile Store");
149
				tileParams.setDataParameters(wmtsParams);
150
				return tileParams;
151
			}
152
		} catch (InitializeException e) {
153
            logger.warn("Can't get DataStoreParameters from WMTSServerExplorer", e);
154
		} catch (ProviderNotRegisteredException e) {
155
            logger.warn("Can't get DataStoreParameters from WMTSServerExplorer", e);
156
		}
157
		return wmtsParams;
158
	}
159

  
160
	public void connect(ICancellable cancellable) throws ConnectException {
161
		URL url = null;
162
		boolean override = false;
163

  
164
		try {
165
			url = new URL(parameters.getHost());
166
		} catch (Exception e) {
167
			throw new ConnectException("Malformed URL",e);
168
		}
169
        try {
170
        	ogcClient = WMTSOGCLocator.getManager().createWMTSClient(url.toString());
171
        	ogcClient.setForceChangeAxisOrder(parameters.isLongitudeFirst());
172
        	if (!ogcClient.connect(override, cancellable))
173
        		throw new ConnectException("Error connecting");
174
        } catch (IOException e) {
175
			throw new ConnectException(e.getMessage(), e);
176
		}
177
	}
178

  
179
	public boolean isHostReachable(int timeout) {
180
		URL url = null;
181
		URLConnection con = null;
182
		try {
183
			url = new URL(parameters.getHost());
184
			con = url.openConnection();
185
			if(con == null)
186
				return false;
187
			con.connect();
188
		} catch (MalformedURLException e) {
189
			return false;
190
		} catch (IOException e) {
191
			return false;
192
		}
193

  
194
		InputStream stream = null;
195
		try {
196
			stream = con.getInputStream();
197
			if(stream == null)
198
				return false;
199
		} catch (IOException e) {
200
		}
201

  
202
		return true;
203
	}
204

  
205
	/**
206
	 * Checks if the network and host are reachable
207
	 * @return true if both are reachable and false if they are not
208
	 */
209
	public boolean isHostReachable() {
210
		return isHostReachable(RasterDataServerExplorer.TIME);
211
	}
212

  
213
	public boolean isConnected() {
214
		if(ogcClient != null)
215
			return true;
216
		return false;
217
	}
218

  
219
	public WMTSClient getOGCClient() {
220
		return ogcClient;
221
	}
222

  
223
	public String getHost() {
224
		return parameters.getHost();
225
	}
226

  
227
	public DataServerExplorerProviderServices getServerExplorerProviderServices() {
228
		return null;
229
	}
230
}
0 231

  
org.gvsig.raster.wmts/tags/org.gvsig.raster.wmts-2.2.17/org.gvsig.raster.wmts.io/src/main/java/org/gvsig/raster/wmts/io/WMTSProvider.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.wmts.io;
23

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

  
39
import javax.swing.ImageIcon;
40

  
41
import org.gvsig.compat.net.ICancellable;
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.DatasetBand;
49
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
50
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
51
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
52
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
53
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
54
import org.gvsig.fmap.dal.coverage.exception.InfoByPointException;
55
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
56
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
57
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
58
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
59
import org.gvsig.fmap.dal.coverage.exception.QueryException;
60
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
61
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
62
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
63
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
64
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
65
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
66
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
67
import org.gvsig.fmap.dal.coverage.util.MathUtils;
68
import org.gvsig.fmap.dal.exception.CloseException;
69
import org.gvsig.fmap.dal.exception.InitializeException;
70
import org.gvsig.fmap.dal.exception.OpenException;
71
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
72
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
73
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
74
import org.gvsig.metadata.MetadataLocator;
75
import org.gvsig.raster.cache.tile.TileCacheLocator;
76
import org.gvsig.raster.cache.tile.TileCacheManager;
77
import org.gvsig.raster.cache.tile.exception.TileGettingException;
78
import org.gvsig.raster.cache.tile.provider.CacheStruct;
79
import org.gvsig.raster.cache.tile.provider.TileListener;
80
import org.gvsig.raster.cache.tile.provider.TileServer;
81
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
82
import org.gvsig.raster.impl.datastruct.BandListImpl;
83
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
84
import org.gvsig.raster.impl.datastruct.ExtentImpl;
85
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
86
import org.gvsig.raster.impl.provider.MemoryTileMatrixBuffer;
87
import org.gvsig.raster.impl.provider.RasterProvider;
88
import org.gvsig.raster.impl.provider.RemoteRasterProvider;
89
import org.gvsig.raster.impl.provider.TiledRasterProvider;
90
import org.gvsig.raster.impl.store.DefaultRasterStore;
91
import org.gvsig.raster.impl.store.DefaultStoreFactory;
92
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
93
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
94
import org.gvsig.raster.impl.store.properties.RemoteStoreHistogram;
95
import org.gvsig.raster.util.DefaultProviderServices;
96
import org.gvsig.raster.wmts.io.downloader.WMTSTileServer;
97
import org.gvsig.raster.wmts.ogc.WMTSClient;
98
import org.gvsig.raster.wmts.ogc.WMTSOGCLocator;
99
import org.gvsig.raster.wmts.ogc.WMTSStatus;
100
import org.gvsig.raster.wmts.ogc.exception.DownloadException;
101
import org.gvsig.raster.wmts.ogc.exception.ServerErrorException;
102
import org.gvsig.raster.wmts.ogc.exception.WMTSException;
103
import org.gvsig.raster.wmts.ogc.struct.WMTSLayer;
104
import org.gvsig.raster.wmts.ogc.struct.WMTSTile;
105
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrix;
106
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrixLimits;
107
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrixSet;
108
import org.gvsig.raster.wmts.ogc.struct.WMTSTileMatrixSetLink;
109
import org.gvsig.tools.ToolsLocator;
110

  
111
import org.apache.commons.io.FilenameUtils;
112
import org.cresques.cts.IProjection;
113
import org.slf4j.Logger;
114
import org.slf4j.LoggerFactory;
115
/**
116
 * Provider for WMTS service
117
 *
118
 * @author Nacho Brodin (nachobrodin@gmail.com)
119
 */
120
public class WMTSProvider extends AbstractRasterProvider implements RemoteRasterProvider, TiledRasterProvider {
121
	public static String                NAME                     = "Wmts Store";
122
	public static String                DESCRIPTION              = "Wmts Raster file";
123
	public static final String          METADATA_DEFINITION_NAME = "WmtsStore";
124
	private static Logger               logger                   = LoggerFactory.getLogger(WMTSProvider.class);
125
	public static boolean               TILED                    = true;
126

  
127
	//Los tiles se piden de forma secuencial y sin lanzar threads para ello (+Lento)
128
	public static int                   SEQUENTIAL               = 0;
129
	//Los tiles se piden en threads y hay un thread manager para gestionar que no se pidan m?s de cierto n?mero
130
	public static int                   LIMITED_THREADS          = 1;
131
	//Los tiles se piden en threads y se lanzan tantos threads como tiles haya
132
	public static int                   UNLIMITED_THREADS        = 2;
133
	private int                         requestType              = LIMITED_THREADS;
134

  
135
	private static final double         MTS_X_GRADO              = 111319.490793274;
136

  
137
	private Extent                      viewRequest              = null;
138
	private WMTSClient                  ogcClient                = null;
139
	//private static Hashtable<URL, WMTSConnector>
140
	//                                    drivers                  = new Hashtable<URL, WMTSConnector> ();
141
	private boolean                     open                     = false;
142
	private File                        lastRequest              = null;
143
	private DataStoreTransparency       lastFileTransparency     = null;
144
	private int                         lastWidthRequest         = 0;
145
	private int                         lastHeightRequest        = 0;
146
	private WMTSStatus                  lastStatus               = null;
147
	private boolean                     gridSubsets              = true;
148
	private Extent[]                    extentByLevel            = null; //Only for layers without gridSubsets
149
	private Extent                      bbox                     = null;
150
	private MathUtils                   math                     = RasterLocator.getManager().getMathUtils();
151

  
152
	/**
153
	 * This thread manages the number of tiles that have been thrown.
154
	 * This number is controlled by the NTHREADS_QUEUE variable.
155
	 *
156
	 * @author Nacho Brodin (nachobrodin@gmail.com)
157
	 */
158
	public class RequestThreadManager extends Thread {
159
		private TilePipe               pipe           = null;
160
		private List<WMTSTile>         tiles          = null;
161
		private WMTSStatus             status         = null;
162

  
163
		public RequestThreadManager(TilePipe pipe, List<WMTSTile> tiles, WMTSStatus status) {
164
			this.pipe = pipe;
165
			this.tiles = tiles;
166
			this.status = status;
167
		}
168

  
169
		public void run() {
170
			for (int i = 0; i < tiles.size(); i++) {
171
				WMTSTile tile = tiles.get(i);
172
				WMTSStatus statusCopy = status.cloneStatus();
173
				statusCopy.setTileRow(tile.getRow());
174
				statusCopy.setTileCol(tile.getCol());
175
				if (pipe.getSize() > TilePipe.NTHREADS_QUEUE) {
176
					try {
177
						synchronized (this) {
178
							wait();
179
						}
180
					} catch( InterruptedException e ) {
181
					}
182
				}
183
				new RequestTileLauncher(pipe, statusCopy, tile).start();
184
			}
185
		}
186
	}
187

  
188
	/**
189
	 * Thread to download a tile
190
	 * @author Nacho Brodin (nachobrodin@gmail.com)
191
	 */
192
	class RequestTileLauncher extends Thread {
193
		private TilePipe      pipe    = null;
194
		private WMTSStatus    status  = null;
195
		private WMTSTile      tile    = null;
196

  
197
		public RequestTileLauncher(TilePipe pipe, WMTSStatus status, WMTSTile tile) {
198
			this.pipe = pipe;
199
			this.status = status;
200
			this.tile = tile;
201
		}
202

  
203
		public void run() {
204
			try {
205
				//File file = getConnector().getTile(status, null);
206
				URL url = getOGCClient().getTileURL(status);
207
				tile.setFile(getOGCClient().downloadFile(url, null));
208
				pipe.setTile(tile);
209
			} catch (DownloadException e) {
210
				logger.info("Error downloading files", e);
211
			} catch (MalformedURLException e) {
212
				logger.info("Malformed URL", e);
213
			} catch (WMTSException e) {
214
				logger.info("", e);
215
			}
216
		}
217
	}
218

  
219
	/**
220
	 * Point information
221
	 * @author Nacho Brodin (nachobrodin@gmail.com)
222
	 */
223
	public class PointInfo {
224
		public Point2D worldCoord;
225
		public Point2D tile;
226
		public Point2D pixelInTile;
227
		public int     level;
228

  
229
		public PointInfo(Point2D worldCoord) {
230
			this.worldCoord = worldCoord;
231
		}
232
	}
233

  
234
	public static void register() {
235
		DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
236
		if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
237
			dataman.registerStoreProvider(NAME,
238
					WMTSProvider.class, WMTSDataParametersImpl.class);
239
		}
240

  
241
		if (!dataman.getExplorerProviders().contains(WMTSServerExplorer.NAME)) {
242
			dataman.registerExplorerProvider(WMTSServerExplorer.NAME, WMTSServerExplorer.class, WMTSServerExplorerParameters.class);
243
		}
244
		dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
245
	}
246

  
247
	public WMTSProvider() throws NotSupportedExtensionException {
248
		super();
249
	}
250

  
251
	/**
252
	 * Constructor. Abre el dataset.
253
	 * @param proj Proyecci?n
254
	 * @param fName Nombre del fichero
255
	 * @throws NotSupportedExtensionException
256
	 * @throws OpenException
257
     * @deprecated use {@link #WMTSProvider(URI)}, this constructor will be removed in gvSIG 2.5
258
	 */
259
	public WMTSProvider(String params) throws NotSupportedExtensionException, OpenException {
260
		super(params);
261
        logger.info("Deprecated use of WMTSProvider constructor");
262
		if(params instanceof String) {
263
			WMTSDataParameters p = new WMTSDataParametersImpl();
264
            try {
265
                p.setURI(new URI((String) params));
266
            } catch (URISyntaxException e) {
267
                throw new OpenException("Can't create URI from" + (String) params, e);
268
            }
269
			super.init(p, null, ToolsLocator.getDynObjectManager()
270
					.createDynObject(
271
							MetadataLocator.getMetadataManager().getDefinition(
272
									DataStore.METADATA_DEFINITION_NAME)));
273
			init(p, null);
274
		}
275
	}
276

  
277
	 /**
278
     * Constructor. Abre el dataset.
279
     * @param uri URI del fichero
280
     * @throws NotSupportedExtensionException
281
     */
282
    public WMTSProvider(URI uri) throws NotSupportedExtensionException {
283
        super(uri);
284
        WMTSDataParameters p = new WMTSDataParametersImpl();
285
        p.setURI(uri);
286
        super.init(
287
            p,
288
            null,
289
            ToolsLocator.getDynObjectManager().createDynObject(
290
                MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
291
        init(p, null);
292
    }
293

  
294
    public WMTSProvider(WMTSDataParameters params,
295
			DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
296
		super(params, storeServices, ToolsLocator.getDynObjectManager()
297
				.createDynObject(
298
						MetadataLocator.getMetadataManager().getDefinition(
299
								DataStore.METADATA_DEFINITION_NAME)));
300
		init(params, storeServices);
301
	}
302

  
303
	/**
304
	 * Gets the connector from the URL
305
	 * @return
306
	 * @throws RemoteServiceException
307
	 */
308
	public WMTSClient getOGCClient() throws WMTSException {
309
		if(ogcClient == null) {
310
			WMTSDataParameters p = (WMTSDataParameters)parameters;
311
			ogcClient = p.getOGCClient();
312
			if(ogcClient != null)
313
				return ogcClient;
314

  
315
			URL url = null;
316
			try {
317
				url = p.getURI().toURL();
318
			} catch (Exception e) {
319
				throw new WMTSException("Malformed URL",e);
320
			}
321
			try {
322
				ogcClient = WMTSOGCLocator.getManager().createWMTSClient(url.toString());
323
				ogcClient.connect(true, new ICancellable() {
324

  
325
					public boolean isCanceled() {
326
						return false;
327
					}
328

  
329
					public Object getID() {
330
						return null;
331
					}
332
				});
333
			} catch (ConnectException e) {
334
				throw new WMTSException("Connect exception",e);
335
			} catch (IOException e) {
336
				throw new WMTSException("Connect exception",e);
337
			}
338
		}
339
		return ogcClient;
340
	}
341

  
342
	/**
343
	 * Crea las referencias al fichero y carga
344
	 * las estructuras con la informaci?n y los metadatos.
345
	 * @param proj Proyecci?n
346
	 * @param param Parametros de carga
347
	 * @throws NotSupportedExtensionException
348
	 */
349
	public void init (DataStoreParameters params,
350
			DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
351
		setParam(storeServices, params);
352
		if(((WMTSDataParameters)params).getImageFormat().compareTo("image/gif") == 0) {
353
			setDataType(new int[]{Buffer.TYPE_BYTE});
354
			bandCount = 1;
355
		} else {
356
			setDataType(new int[]{Buffer.TYPE_BYTE, Buffer.TYPE_BYTE, Buffer.TYPE_BYTE, Buffer.TYPE_BYTE});
357
			bandCount = 4;
358
		}
359

  
360
		if(!(param instanceof WMTSDataParameters))
361
			return;
362

  
363
		gridSubsets = hasGridSubsets((WMTSDataParameters)param);
364
		open = true;
365
	}
366

  
367
	/**
368
	 * Returns true if this layer has grid subsets
369
	 * @return
370
	 */
371
	public boolean hasGridSubsets() {
372
		return gridSubsets;
373
	}
374

  
375
	/**
376
	 * Checks if this layer has grid subsets or doesn't
377
	 * @param p
378
	 * @return
379
	 */
380
	private boolean hasGridSubsets(WMTSDataParameters p) {
381
		List<WMTSTileMatrixLimits> tileMatrixSetLimits = null;
382
		List<WMTSTileMatrixSetLink> tileMatrixSetLinkList = p.getLayer().getTileMatrixSetLink();
383
		String srs = p.getSRSCode();
384
		for (int i = 0; i < tileMatrixSetLinkList.size(); i++) {
385
			WMTSTileMatrixSetLink tileMatrixSetLink = (WMTSTileMatrixSetLink)tileMatrixSetLinkList.get(i);
386
			WMTSTileMatrixSet tms = tileMatrixSetLink.getTileMatrixSet();
387
			List<WMTSTileMatrixLimits> tmsl = tileMatrixSetLink.getTileMatrixLimits();
388
			String srsTileSet = tms.getSupportedCRS();
389
			if(areSrsEquals(srsTileSet, srs)) {
390
				tileMatrixSetLimits = tmsl;
391
			}
392
		}
393

  
394
		return (tileMatrixSetLimits == null || tileMatrixSetLimits.size() <= 0) ? false : true;
395
	}
396

  
397
	private boolean areSrsEquals(String sourceSrs, String appSrs) {
398
		if(sourceSrs.compareTo(appSrs) == 0)
399
			return true;
400
		if(sourceSrs.contains("CRS:84") || sourceSrs.contains("CRS84")) {
401
			if(appSrs.equals("EPSG:4326"))
402
				return true;
403
		}
404
		return false;
405
	}
406

  
407
	/*public static final WMTSConnector getConnectorFromURL(URL url) throws IOException {
408
		WMTSConnector drv = (WMTSConnector) drivers.get(url);
409
		if (drv == null) {
410
			drv = new WMTSConnector(url);
411
			drivers.put(url, drv);
412
		}
413
		return drv;
414
	}*/
415

  
416
	/**
417
	 * Obtiene el objeto que contiene que contiene la interpretaci?n de
418
	 * color por banda
419
	 * @return
420
	 */
421
	public ColorInterpretation getColorInterpretation() {
422
		if(super.getColorInterpretation() == null) {
423
			ColorInterpretation colorInterpretation = new DataStoreColorInterpretation(getBandCount());
424

  
425
			if(getBandCount() == 1)
426
				colorInterpretation = DataStoreColorInterpretation.createGrayInterpretation();
427

  
428
			if(getBandCount() == 3)
429
				colorInterpretation = DataStoreColorInterpretation.createRGBInterpretation();
430

  
431
			if(getBandCount() == 4)
432
				colorInterpretation = DataStoreColorInterpretation.createRGBAInterpretation();
433

  
434
			if(getBandCount() > 4 || getBandCount() == 2) {
435
				for (int i = 0; i < getBandCount(); i++) {
436
					colorInterpretation.setColorInterpValue(i, DataStoreColorInterpretation.UNDEF_BAND);
437
				}
438
			}
439
			setColorInterpretation(colorInterpretation);
440
		}
441
		return super.getColorInterpretation();
442
	}
443

  
444
	public boolean isTiled() {
445
		return true;
446
	}
447

  
448
	public AffineTransform getAffineTransform() {
449
		WMTSDataParameters p = (WMTSDataParameters)parameters;
450
		Extent e = getExtent();
451
		double psX = e.width() / (lastWidthRequest <= 0 ? p.getWidth() : lastWidthRequest);
452
		double psY = -(e.height() / (lastHeightRequest <= 0 ? p.getHeight() : lastHeightRequest));
453
		ownTransformation = new AffineTransform(
454
				psX,
455
				0,
456
				0,
457
				psY,
458
				e.getULX() - (psX / 2),
459
				e.getULY() - (psY / 2));
460
		externalTransformation = (AffineTransform) ownTransformation.clone();
461
		return ownTransformation;
462
	}
463

  
464
	/**
465
	 * <p>
466
	 * Gets the bounding box in world coordinates.
467
	 * If the layer has defined the BoundingBox tag, we will take this bounding box as entire
468
	 * extension of this layer, else we'll see if the tag WGS84BoundingBox is defined (it can be approximated).
469
	 * In this case we'll take WGS84BoundingBox as entire extension.
470
	 * </p>
471
	 * <br>
472
	 * Note:
473
	 * <br>
474
	 * <p>
475
	 * If the layer has grid subsets (TileMatrixLimits) then
476
	 * this will have a only extent but if the layer doesn't have grid subsets then this will have a different
477
	 * extent in each level resolution. In this case we need to know the extent for each level.
478
	 * </p>
479
	 * @return Extent
480
	 */
481
	public Extent getExtent() {
482
		WMTSDataParameters p = (WMTSDataParameters)parameters;
483
		WMTSLayer layer = p.getLayer();
484

  
485
		if(layer.getBBox() != null)
486
			return new ExtentImpl(layer.getBBox().toRectangle2D());
487

  
488
		if(layer.getWGS84BBox() != null) {
489
			String crsCode = p.getSRSCode();
490
			Rectangle2D r = layer.getWGS84BBoxTransformed(crsCode);
491
			if(r != null)
492
				return new ExtentImpl(r);
493
		}
494

  
495
		if(bbox == null)
496
			getExtentByResolutionLevel();
497
		return bbox;
498

  
499
		/*if(gridSubsets) {
500
			WMTSBoundingBox bbox = layer.getWGS84BBox();
501
			return new ExtentImpl(bbox.toRectangle2D());
502
		} else {
503
			if(bbox == null)
504
				getExtentByResolutionLevel();
505
			return bbox;
506
		}*/
507
	}
508

  
509
	/**
510
	 * Gets the suffix of the downloaded image
511
	 * @return
512
	 */
513
	public String getFileSuffix() {
514
		WMTSDataParameters p = (WMTSDataParameters)parameters;
515
		String format = p.getImageFormat();
516
		if (format == null){
517
			return "xml";
518
		}
519
		if (format.indexOf("png") >= 0){
520
	        return "png";
521
		}
522
	    if (format.indexOf("xml") >= 0){
523
	        return "xml";
524
	    }
525
	    if (format.indexOf("gif") >= 0){
526
	        return "gif";
527
	    }
528
	    if (format.indexOf("tif") >= 0){
529
	        return "tif";
530
	    }
531
	    if (format.indexOf("bmp") >= 0){
532
	        return "bmp";
533
	    }
534
	    if (format.indexOf("jpg") >= 0
535
	        || format.indexOf("jpeg") >= 0){
536
	        return "jpg";
537
	    }
538
		return "xml";
539
	}
540

  
541
	/**
542
	 * When a layer doesn't have grid subsets this will have a different bounding
543
	 * box by resolution level. This function calculates and returns the array of
544
	 * extents, one by resolution level.
545
	 * @return
546
	 */
547
	public Extent[] getExtentByResolutionLevel() {
548
		if(extentByLevel == null) {
549
			WMTSDataParameters p = (WMTSDataParameters)parameters;
550
			WMTSTileMatrixSetLink tileMatrixSetLink = getTileMatrixSetLink();
551
			WMTSTileMatrixSet tileMatrixSet = tileMatrixSetLink.getTileMatrixSet();
552

  
553
	    	double widthMtsTile = 0;
554
	    	double heightMtsTile = 0;
555
			List<WMTSTileMatrix> tileMatrixList = tileMatrixSet.getTileMatrix();
556
			extentByLevel = new ExtentImpl[tileMatrixList.size()];
557
			double minX = 0;
558
			double minY = 0;
559
			double maxX = 0;
560
			double maxY = 0;
561
			for (int i = 0; i < tileMatrixList.size(); i++) {
562
				WMTSTileMatrix tileMatrix = (WMTSTileMatrix)tileMatrixList.get(i);
563
		    	if(!p.isProjected()) {
564
		    		widthMtsTile = (tileMatrix.getScaleDenominator() * tileMatrix.getTileWidth() * 0.28) / (MTS_X_GRADO * 1000);
565
		    		heightMtsTile = (tileMatrix.getScaleDenominator() * tileMatrix.getTileHeight() * 0.28) / (MTS_X_GRADO * 1000);
566
		    	} else {
567
		    		widthMtsTile = (tileMatrix.getScaleDenominator() * tileMatrix.getTileWidth() * 0.28) / 1000;
568
		    		heightMtsTile = (tileMatrix.getScaleDenominator() * tileMatrix.getTileHeight() * 0.28) / 1000;
569
		    	}
570

  
571
		    	//TODO: Revisar!!! Creo que el top left sale al rev?s en el de la nasa
572

  
573
		    	double h = Math.abs(tileMatrix.getTopLeftCorner()[1] - (tileMatrix.getTopLeftCorner()[1] - (tileMatrix.getMatrixHeight() * heightMtsTile)));
574
		    	Rectangle2D r = new Rectangle2D.Double(
575
		    			tileMatrix.getTopLeftCorner()[0],
576
		    			tileMatrix.getTopLeftCorner()[1] - h,
577
		    			Math.abs(tileMatrix.getTopLeftCorner()[0] - (tileMatrix.getTopLeftCorner()[0] + (tileMatrix.getMatrixWidth() * widthMtsTile))),
578
		    			h);
579
		    	extentByLevel[i] = new ExtentImpl(r);
580
		    	if(i == 0) {
581
		    		minX = extentByLevel[i].getMin().getX();
582
		    		minY = extentByLevel[i].getMin().getY();
583
		    		maxX = extentByLevel[i].getMax().getX();
584
		    		maxY = extentByLevel[i].getMax().getY();
585
		    	} else {
586
		    		minX = Math.min(minX, extentByLevel[i].getMin().getX());
587
		    		minY = Math.min(minY, extentByLevel[i].getMin().getY());
588
		    		maxX = Math.max(maxX, extentByLevel[i].getMax().getX());
589
		    		maxY = Math.max(maxY, extentByLevel[i].getMax().getY());
590
		    	}
591
			}
592
			bbox = new ExtentImpl(minX, maxY, maxX, minY);
593
		}
594
		return extentByLevel;
595
	}
596

  
597
	public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
598
		return null;
599
	}
600

  
601
	public RasterProvider load() {
602
		return this;
603
	}
604

  
605
	public boolean isOpen() {
606
		return open;
607
	}
608

  
609
	public void close() {
610
		open = false;
611
	}
612

  
613
	public Transparency getTransparency() {
614
		if(lastFileTransparency == null) {
615
			lastFileTransparency = new DataStoreTransparency(getColorInterpretation());
616
			lastFileTransparency.setTransparencyBand(3);
617
		}
618
		return lastFileTransparency;
619
	}
620

  
621
	public NoData getNoDataValue() {
622
		NoData nodata = super.getNoDataValue();
623
		if(nodata != null)
624
			nodata.setNoDataTransparent(false);
625
		return noData;
626
	}
627

  
628
	public URI translateURI(URI uri) {
629
		return uri;
630
	}
631

  
632
	public void setView(Extent e) {
633
		viewRequest = e;
634
	}
635

  
636
	public Extent getView() {
637
		return viewRequest;
638
	}
639

  
640
	public double getWidth() {
641
		WMTSDataParameters p = (WMTSDataParameters)parameters;
642
		if (lastWidthRequest <= 0)
643
			return p.getWidth();
644
		return lastWidthRequest;
645
	}
646

  
647
	public double getHeight() {
648
		WMTSDataParameters p = (WMTSDataParameters)parameters;
649
		if (lastHeightRequest <= 0)
650
			return p.getHeight();
651
		return lastHeightRequest;
652
	}
653

  
654
	public Object readCompleteLine(int line, int band)
655
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
656
		return null;
657
	}
658

  
659
	/**
660
	 * When the remote layer has fixed size this method downloads the file and return its reference.
661
	 * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
662
	 * useful to build an histogram or calculate statistics. This represents a sample of data.
663
	 * @return
664
	 * @throws RasterDriverException
665
	 */
666
	public File getFileLayer() throws RasterDriverException {
667
		return null;
668
	}
669

  
670
	/**
671
	 * Reads a complete block of data and returns an tridimensional array of the right type. This function is useful
672
	 * to read a file very fast without setting a view. In a WMTS service when the size is fixed then it will read the
673
	 * entire image but when the source hasn't pixel size it will read a sample of data. This set of data will have
674
	 * the size defined in FIXED_SIZE.
675
	 *
676
	 * @param pos Posici?n donde se empieza  a leer
677
	 * @param blockHeight Altura m?xima del bloque leido
678
	 * @return Object que es un array tridimendional del tipo de datos del raster. (Bandas X Filas X Columnas)
679
	 * @throws InvalidSetViewException
680
	 * @throws FileNotOpenException
681
	 * @throws RasterDriverException
682
	 */
683
	public Object readBlock(int pos, int blockHeight, double scale)
684
	throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
685
		return null;
686
	}
687

  
688
	public Object getData(int x, int y, int band)
689
		throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
690
		return null;
691
	}
692

  
693
	/**
694
	 * Assigns the list of bands RGB and read a window of data
695
	 * @param rasterBuf
696
	 * @param bandList
697
	 * @param lastFile
698
	 * @param ulx
699
	 * @param uly
700
	 * @param lrx
701
	 * @param lry
702
	 * @return
703
	 * @throws RasterDriverException
704
	 * @throws ProcessInterruptedException
705
	 */
706
	public Buffer getBuffer(Buffer rasterBuf, BandList bandList, File lastFile,
707
			double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
708
		return null;
709
	}
710

  
711
	/**
712
	 * Gets the tile matrix from the selected level
713
	 * @param level
714
	 * @return
715
	 */
716
	private WMTSTileMatrix getTileMatrixByLevel(int level) {
717
		level = adjustLevel(level);
718

  
719
		WMTSTileMatrixSetLink tileMatrixSetLink = getTileMatrixSetLink();
720
		WMTSTileMatrixSet tileMatrixSet = tileMatrixSetLink.getTileMatrixSet();
721
		List<WMTSTileMatrixLimits> tileMatrixSetLimits = tileMatrixSetLink.getTileMatrixLimits();
722

  
723
		WMTSTileMatrixLimits tileMatrixLimits = null;
724
		WMTSTileMatrix tileMatrix = (WMTSTileMatrix)tileMatrixSet.getTileMatrix().get(level);
725
		if(hasGridSubsets()) {
726
			tileMatrixLimits = (WMTSTileMatrixLimits)tileMatrixSetLimits.get(level);
727
			tileMatrix = tileMatrixLimits.getTileMatrix();
728
		}
729
		return tileMatrix;
730
	}
731

  
732
	/**
733
	 * Returns the number of levels
734
	 * @return
735
	 */
736
	public int getZoomLevels() {
737
		WMTSTileMatrixSetLink tileMatrixSetLink = getTileMatrixSetLink();
738
		WMTSTileMatrixSet tileMatrixSet = tileMatrixSetLink.getTileMatrixSet();
739
		if(hasGridSubsets()) {
740
			List<WMTSTileMatrixLimits> tileMatrixSetLimits = tileMatrixSetLink.getTileMatrixLimits();
741
			return Math.min(tileMatrixSet.getTileMatrix().size(), tileMatrixSetLimits.size());
742
		}
743
		return tileMatrixSet.getTileMatrix().size();
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff