Revision 6296

View differences:

org.gvsig.raster.wms/tags/org.gvsig.raster.wms-2.2.45/org.gvsig.raster.wms.io/src/main/java/org/gvsig/raster/wms/io/WMSServerExplorer.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.wms.io;
29

  
30
import java.awt.geom.Rectangle2D;
31
import java.io.IOException;
32
import java.io.InputStream;
33
import java.net.MalformedURLException;
34
import java.net.URI;
35
import java.net.URISyntaxException;
36
import java.net.URL;
37
import java.net.URLConnection;
38
import java.util.ArrayList;
39
import java.util.Hashtable;
40
import java.util.List;
41
import java.util.Vector;
42

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

  
60
import org.slf4j.Logger;
61
import org.slf4j.LoggerFactory;
62

  
63
/**
64
 * Explorer for a WMS server
65
 * @author Nacho Brodin (nachobrodin@gmail.com)
66
 */
67
public class WMSServerExplorer extends AbstractDataServerExplorer implements RasterDataServerExplorer, DataServerExplorerProvider {
68
	public static final String          NAME                     = WMSProvider.NAME;
69
	private WMSConnector                connector                = null;
70
//	private WMSServerExplorerParameters parameters               = null;
71
	private Logger                      log                      = LoggerFactory.getLogger(WMSServerExplorer.class);
72

  
73
	public WMSServerExplorer(
74
			WMSServerExplorerParameters parameters,
75
			DataServerExplorerProviderServices services)
76
			throws InitializeException {
77
                super(parameters, services);
78
//		this.parameters = parameters;
79
	}
80

  
81
	/**
82
	 * Gets the provider's name
83
	 * @return
84
	 */
85
	public String getDataStoreProviderName() {
86
		return WMSProvider.NAME;
87
	}
88

  
89
	public String getDescription() {
90
		return WMSProvider.DESCRIPTION;
91
	}
92

  
93
	public boolean add(String provider, NewDataStoreParameters parameters,
94
			boolean overwrite) throws DataException {
95
		return false;
96
	}
97

  
98
	public boolean canAdd() {
99
		return false;
100
	}
101

  
102
	public boolean canAdd(String storeName) throws DataException {
103
		return false;
104
	}
105

  
106
	public NewDataStoreParameters getAddParameters(String storeName)
107
			throws DataException {
108
		return null;
109
	}
110

  
111
	public List<?> getDataStoreProviderNames() {
112
		return null;
113
	}
114

  
115
	public WMSServerExplorerParameters getParameters() {
116
		return (WMSServerExplorerParameters) super.getParameters();
117
	}
118

  
119
	public List<?> list() throws DataException {
120
		return null;
121
	}
122

  
123
	public List<?> list(int mode) throws DataException {
124
		return null;
125
	}
126

  
127
	public void remove(DataStoreParameters parameters) throws DataException {
128

  
129
	}
130

  
131
	public String getProviderName() {
132
		return null;
133
	}
134

  
135
	//**********************************************
136
	//Connector
137
	//**********************************************
138

  
139
	public DataStoreParameters getStoredParameters() {
140
		DataManager manager = DALLocator.getDataManager();
141
		WMSDataParameters params = null;
142
		try {
143
			params = (WMSDataParameters) manager.createStoreParameters(this.getDataStoreProviderName());
144
			params.setURI(new URI(getParameters().getHost()));
145

  
146
			/*if(WMSProvider.TILED) {
147
				TileDataParameters tileParams = (TileDataParameters) manager.createStoreParameters("Tile Store");
148
				tileParams.setDataParameters(params);
149
				return tileParams;
150
			} */
151
		} catch (InitializeException e) {
152
			log.debug("Error initializating parameters", e);
153
		} catch (ProviderNotRegisteredException e) {
154
			log.debug("Error getting parameters", e);
155
		} catch (URISyntaxException e) {
156
            log.debug("Can't create URI from "+getParameters().getHost(), e);
157
        }
158

  
159
		return params;
160
	}
161

  
162
	public void connect(ICancellable cancellable) throws ConnectException {
163
		connect(cancellable, false);
164
	}
165

  
166
	/**
167
	 * Connects to the server and throws a getCapabilities. This loads
168
	 * the basic information to make requests.
169
	 * @throws RemoteServiceException
170
	 */
171
	public void connect(ICancellable cancellable, boolean updateCache) throws ConnectException {
172
		URL url = null;
173

  
174
		try {
175
			url = new URL(getParameters().getHost());
176
		} catch (Exception e) {
177
			throw new ConnectException(Messages.getText("malformed_url"), e);
178
		}
179
        try {
180
        	connector = WMSProvider.getConnectorFromURL(url, updateCache);
181
        	if (!connector.connect(this.getParameters(), updateCache, cancellable))
182
        		throw new ConnectException(Messages.getText("error_connecting"));
183
        } catch (IOException e) {
184
			throw new ConnectException(Messages.getText("error_connecting"), e);
185
		}
186

  
187
	}
188

  
189
	/**
190
	 * Checks if the network and host are reachable
191
	 * @param timeout for the host
192
	 * @return true if both are reachable and false if they are not
193
	 */
194
	public boolean isHostReachable(int timeout) {
195
		URL url = null;
196
		try {
197
			url = new URL(getParameters().getHost());
198
			URLConnection con = url.openConnection();
199
			if(con == null)
200
				return false;
201
			con.connect();
202
			InputStream stream = con.getInputStream();
203
			if(stream == null)
204
				return false;
205
		} catch (MalformedURLException e) {
206
			return false;
207
		} catch (IOException e) {
208
			return false;
209
		}
210

  
211
		return true;
212
	}
213

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

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

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

  
243
	/**
244
	 * Gets the list of raster formats supported by the server
245
	 * @return
246
	 */
247
	@SuppressWarnings("unchecked")
248
	public String[] getFormats() {
249
		if(connector != null) {
250
			Vector f = connector.getFormats();
251
			ArrayList formatos = new ArrayList();
252
			for (int i = 0; i < f.size(); i++) {
253
				formatos.add(f.elementAt(i));
254
			}
255
			return (String[]) formatos.toArray(new String[0]);
256
		}
257
		return null;
258
	}
259

  
260
	/**
261
	 * Gets the list of raster information formats supported by the server
262
	 * @return
263
	 */
264
	@SuppressWarnings("unchecked")
265
	public String[] getInfoFormats() {
266
		if(connector != null) {
267
			Vector f = connector.getInfoFormats();
268
			ArrayList formatos = new ArrayList();
269
			for (int i = 0; i < f.size(); i++) {
270
				formatos.add(f.elementAt(i));
271
			}
272
			return (String[]) formatos.toArray(new String[0]);
273
		}
274
		return null;
275
	}
276

  
277
	/**
278
	 * Gets a tree of nodes which represents the server information
279
	 * @return
280
	 */
281
	public WMSLayerNode getLayerTree() {
282
		if(connector != null) {
283
			return connector.getLayersTree();
284
		}
285
		return null;
286
	}
287

  
288
	/**
289
	 * Gets the server title
290
	 * @return
291
	 */
292
	public String getServerType() {
293
		if (getVersion() == null)
294
			return "WMS";
295
        return "WMS "+ getVersion();
296
	}
297

  
298
	/**
299
	 * Gets the online resources
300
	 * @return
301
	 */
302
	public Hashtable getOnlineResources() {
303
		if(connector != null) {
304
			return connector.getOnlineResources();
305
		}
306
		return null;
307
	}
308

  
309
	/**
310
	 * Gets the protocol supported by the server
311
	 * @return
312
	 */
313
	public String getVersion() {
314
		if(connector != null) {
315
			return (connector.getVersion() == null) ? "" : connector.getVersion();
316
		}
317
		return null;
318
	}
319

  
320
    public Rectangle2D getLayersExtent(String[] layerName, String srs) {
321
    	return connector.getLayersExtent(layerName, srs);
322
    }
323

  
324
    /**
325
	 * Gets a layer using its name
326
	 * @param layerName
327
	 * @return
328
	 */
329
    public WMSLayerNode getLayer(String layerName) {
330
    	return connector.getLayer(layerName);
331
    }
332

  
333
    /**
334
	 * Gets the host URI
335
	 * @return
336
	 */
337
	public String getHost() {
338
		return getParameters().getHost();
339
	}
340

  
341
	public Rectangle2D getBoundingBox(String[] layerNames, String srs) {
342
		return connector.getLayersExtent(layerNames, srs);
343
    }
344

  
345
	public boolean isQueryable() {
346
    	return connector.isQueryable();
347
    }
348

  
349
	/**
350
	 * Gets the title
351
	 * @return
352
	 */
353
	public String getTitle() {
354
		return null;
355
	}
356

  
357
    /**
358
     * @return The title of the service offered by the WMS server.
359
     */
360
    public String getServiceTitle() {
361
		return connector.getServiceTitle();
362
    }
363

  
364
	public DataServerExplorerProviderServices getServerExplorerProviderServices() {
365
		return null;
366
	}
367
}
0 368

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

  
24
import java.awt.geom.Rectangle2D;
25
import java.io.File;
26
import java.io.IOException;
27
import java.util.List;
28
import java.util.Vector;
29

  
30
import org.cresques.cts.IProjection;
31
import org.gvsig.fmap.dal.coverage.RasterLocator;
32
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
33
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
34
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
35
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
36
import org.gvsig.fmap.dal.coverage.exception.QueryException;
37
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
38
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
39
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
40
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
41
import org.gvsig.fmap.dal.exception.InitializeException;
42
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
43
import org.gvsig.raster.cache.tile.Tile;
44
import org.gvsig.raster.cache.tile.exception.TileGettingException;
45
import org.gvsig.raster.impl.DefaultRasterManager;
46
import org.gvsig.raster.impl.provider.RasterProvider;
47
import org.gvsig.raster.impl.provider.tile.BaseTileDownloader;
48
import org.gvsig.raster.util.DefaultProviderServices;
49
import org.gvsig.raster.wms.io.RemoteWMSStyle;
50
import org.gvsig.raster.wms.io.WMSConnector;
51
import org.gvsig.raster.wms.io.WMSDataParameters;
52
import org.gvsig.raster.wms.io.WMSProvider;
53
import org.gvsig.remoteclient.utils.Utilities;
54
import org.gvsig.remoteclient.wms.WMSStatus;
55
import org.gvsig.tools.locator.LocatorException;
56

  
57
/** 
58
 * Tile getter 
59
 * @author Nacho Brodin (nachobrodin@gmail.com)
60
 */
61
public class TileDownloaderForWMS extends BaseTileDownloader {
62
	private WMSConnector             connector  = null;
63
	private Extent                   lyrExtent  = null;
64

  
65
	
66
	
67
	public TileDownloaderForWMS(RasterDataStore store,
68
			int tilePxWidth,
69
			int tilePxHeight) throws RemoteServiceException {
70
		super(store, tilePxWidth, tilePxHeight);
71
		this.connector = ((WMSProvider)store.getProvider()).getConnector();
72
		lyrExtent = store.getExtent();
73
	}
74
	
75
	public synchronized Tile downloadTile(Tile tile) throws TileGettingException {
76
		try {
77
			Rectangle2D r = new Rectangle2D.Double(tile.getExtent().getMinX(), 
78
					tile.getExtent().getMinY() - tile.getExtent().getHeight(), 
79
					tile.getExtent().getWidth(), 
80
					tile.getExtent().getHeight());
81
			//Extent tileExtent = RasterLocator.getManager().getDataStructFactory().createExtent(r);
82
			WMSDataParameters p = (WMSDataParameters)store.getParameters();
83
			WMSStatus wmsStatus = new WMSStatus();
84
			wmsStatus.setLayerNames(Utilities.createVector(p.getLayerQuery(), ","));
85
			wmsStatus.setSrs(p.getSRSCode());
86
			wmsStatus.setFormat(p.getFormat());
87
			List<RemoteWMSStyle> listStyles = p.getStyles();
88
			Vector<?> v = listStyles != null ? new Vector<RemoteWMSStyle>(listStyles) : null;
89
			wmsStatus.setStyles(v);
90
			wmsStatus.setDimensions(p.getDimensions());
91
			wmsStatus.setTransparency(p.isWmsTransparent());
92
			wmsStatus.setOnlineResource((String) p.getOnlineResource().get("GetMap"));
93
			wmsStatus.setExtent(r);
94
			wmsStatus.setHeight(tile.getHeightPx());
95
			wmsStatus.setWidth(tile.getWidthPx());
96
			wmsStatus.setXyAxisOrder(p.isXyAxisOrder());
97

  
98
			IProjection proj = (IProjection)p.getSRS();
99
			if(proj != null)
100
				wmsStatus.setProjected(proj.isProjected());
101
			connector.getMap(wmsStatus, tile.getCancelled(), tile.getFile());
102

  
103
			//Si borramos el rmf no se puede leer la etiqueta Alpha. En caso de que se modifique jgdal para
104
			//poder guardar esta etiqueta deberiamos borrar el rmf para ahorrar ficheros
105
			//File rmf = new File(tile.getFile().getAbsolutePath() + ".rmf");
106
			//if(rmf.exists())
107
				//rmf.delete();
108
		} catch (RemoteServiceException e) {
109
			throw new TileGettingException(e);
110
		} 
111
		readTileFromDisk(tile);
112
		return tile;
113
	}
114
	
115
	@SuppressWarnings("unused")
116
	private void fuseFiles(Extent dstExtent, int dstWidth, int dstHeight, File src, File dst, double pixelSize) 
117
		throws RasterDriverException, ProcessInterruptedException, ProviderNotRegisteredException, InitializeException, LocatorException, NotSupportedExtensionException, IOException, QueryException {
118
		RasterProvider provider = DefaultProviderServices.loadProvider(src);
119
		
120
		RasterQuery q = RasterLocator.getManager().createQuery();
121
		Buffer bufInput = store.query(q);
122
		
123
		Buffer bufDst = DefaultRasterManager.getInstance().createMemoryBuffer(provider.getDataType()[0], dstWidth, dstHeight, provider.getBandCount(), true);
124
		String extension = RasterLocator.getManager().getFileUtils().getExtensionFromFileName(src.getAbsolutePath());
125
		RasterLocator.getManager().getRasterUtils().copyToBuffer(
126
				bufDst, 
127
				dstExtent, 
128
				bufInput, 
129
				lyrExtent, 
130
				pixelSize, 
131
				provider.getColorInterpretation().hasAlphaBand());
132
		RasterLocator.getManager().getProviderServices().exportBufferToFile(
133
				bufDst, 
134
				provider.getCellSize(), 
135
				extension, 
136
				provider.getColorInterpretation().hasAlphaBand(), 
137
				dst, 
138
				dstExtent, 
139
				provider.getColorInterpretation());
140
	}
141
	
142
}
0 143

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

  
24
import org.cresques.cts.IProjection;
25
import org.gvsig.fmap.dal.coverage.RasterLibrary;
26
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
27
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
28
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
29
import org.gvsig.raster.cache.tile.TileCacheLibrary;
30
import org.gvsig.raster.cache.tile.TileCacheLocator;
31
import org.gvsig.raster.cache.tile.TileCacheManager;
32
import org.gvsig.raster.cache.tile.provider.CacheStruct;
33
import org.gvsig.raster.cache.tile.provider.Downloader;
34
import org.gvsig.raster.cache.tile.provider.TileServer;
35
import org.gvsig.raster.impl.provider.RasterProvider;
36
import org.gvsig.raster.wms.io.WMSProvider;
37
import org.slf4j.Logger;
38
import org.slf4j.LoggerFactory;
39

  
40
/**
41
* Data server for the tile cache in a WMSProvider
42
* @author Nacho Brodin (nachobrodin@gmail.com)
43
*/
44
public class WMSTileServer implements TileServer {
45
	private static Logger              logger               = LoggerFactory.getLogger(WMSTileServer.class);
46
	private CacheStruct                struct               = null;
47
	private Downloader                 downloader           = null;
48
	private RasterDataStore            store                = null;
49
	private String                     suffix               = ".tif";
50

  
51
	public WMSTileServer(RasterDataStore store) {
52
		this.store = store;
53
		this.suffix = ((RasterProvider)store.getProvider()).getFileSuffix();
54
	}
55

  
56
	public Downloader getDownloader() {
57
		if(downloader == null ||
58
		   ((TileDownloaderForWMS)downloader).getTileSize()[0] != TileCacheLibrary.ALTERNATIVE_TILESIZE ||
59
		   ((TileDownloaderForWMS)downloader).getTileSize()[1] != TileCacheLibrary.ALTERNATIVE_TILESIZE) {
60
			try {
61
				downloader = new TileDownloaderForWMS(
62
						store,
63
						TileCacheLibrary.ALTERNATIVE_TILESIZE,
64
						TileCacheLibrary.ALTERNATIVE_TILESIZE);
65
			} catch (RemoteServiceException e) {
66
				return null;
67
			}
68
		}
69
		return downloader;
70
	}
71

  
72
	public CacheStruct getStruct() {
73
		if(struct == null) {
74
			TileCacheManager  manager = TileCacheLocator.getManager();
75

  
76
			int coordinates = CacheStruct.FLAT;
77
			if(store.getProjection() != null)
78
				coordinates = (store.getProjection() != null && store.getProjection().isProjected()) ? CacheStruct.FLAT : CacheStruct.GEOGRAFIC;
79
			else {
80
				Extent e = store.getExtent();
81
				if(e.getULX() >= -180 && e.getULX() <= 180 && e.getLRX() >= -180 && e.getLRX() <= 180 &&
82
					e.getULY() >= -90 && e.getULY() <= 90 && e.getLRY() >= -90 && e.getLRY() <= 90) {
83
					coordinates = CacheStruct.GEOGRAFIC;
84
				}
85
			}
86

  
87
			String epsg = null;
88
			IProjection proj = store.getProjection();
89
			if(proj != null)
90
				epsg = proj.getAbrev();
91

  
92
			struct = manager.createCacheStructure(coordinates,
93
					TileCacheLibrary.DEFAULT_LEVELS,
94
					store.getExtent().toRectangle2D(),
95
					Double.POSITIVE_INFINITY,//provider.getCellSize(),
96
					TileCacheLibrary.ALTERNATIVE_TILESIZE,
97
					TileCacheLibrary.ALTERNATIVE_TILESIZE,
98
					((RasterProvider)store.getProvider()).getURIOfFirstProvider().getPath(),
99
					((WMSProvider)store.getProvider()).getParameters().getLayerQuery(),
100
					TileCacheLibrary.DEFAULT_STRUCTURE,
101
					RasterLibrary.pathTileCache,
102
					getFileSuffix(),
103
					epsg,
104
					0);
105
		}
106
		return struct;
107
	}
108

  
109
	public void setStruct(CacheStruct struct) {
110
		if(struct != null) {
111
			this.struct = struct;
112
			if(struct.getTileSizeByLevel(0) != null) {
113
				try {
114
					downloader = new TileDownloaderForWMS(store,
115
							struct.getTileSizeByLevel(0)[0],
116
							struct.getTileSizeByLevel(0)[1]);
117
				} catch (RemoteServiceException ex) {
118
					logger.error("Constructing TileDownloaderForWCS: " + ex.getMessage());
119
				}
120
			}
121
		}
122
	}
123

  
124
	public String getFileSuffix() {
125
		return suffix;
126
	}
127

  
128
	public void setFileSuffix(String extension) {
129
		this.suffix = extension;
130
	}
131
}
0 132

  
org.gvsig.raster.wms/tags/org.gvsig.raster.wms-2.2.45/org.gvsig.raster.wms.io/src/main/java/org/gvsig/raster/wms/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.wms.io package documentation</title>
7
</head>
8
<body>
9

  
10
	<p>WMS provider</p>
11

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

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

  
24
import java.util.ArrayList;
25
import java.util.Calendar;
26
import java.util.GregorianCalendar;
27
import java.util.List;
28

  
29
import org.gvsig.tools.ToolsLocator;
30
import org.gvsig.tools.dynobject.DynStruct;
31
import org.gvsig.tools.persistence.PersistenceManager;
32
import org.gvsig.tools.persistence.PersistentState;
33
import org.gvsig.tools.persistence.exception.PersistenceException;
34

  
35
/**
36
 * Class for WMS TIME dimension from a WMS. It allows you to handle the correct
37
 * values for this kind of dimension.
38
 * <br>
39
 * <p>
40
 * At the moment this class was written the WMS TIME dimension is defined as the
41
 * ISO8601 standard for expressing times.
42
 * </p>
43
 * <br>
44
 * <p>
45
 * As far as this class implements IFMapWMSDimension it uses the same interface
46
 * and documentation.
47
 * </p>
48
 *
49
 * @author jaume dominguez faus - jaume.dominguez@iver.es
50
 */
51
public class TimeDimension implements RemoteTimeDimension {
52
	static private final byte   YEAR_FORMAT           = 1;
53
	static private final byte   YEAR_TO_MONTH_FORMAT  = 2;
54
	static private final byte   YEAR_TO_DAY_FORMAT    = 3;
55
	static private final byte   FULL_FORMAT           = 4;
56

  
57
    static private final long   millisXsec            = 1000;
58
    static private final long   millisXminute         = 60 * millisXsec;
59
    static private final long   millisXhour           = 60 * millisXminute;
60
    static private final long   millisXday            = 24 * millisXhour;
61
    static private final long   millisXmonth          = 30 * millisXday;
62
    //(1 year = 365 days 6 hours 9 minutes 9,7 seconds)
63
    static private final long   millisXyear           = (365*millisXday) + (6*millisXhour) + (9*millisXminute) + 9700;
64

  
65
    static private final String digit                 = "[0-9]";
66
    static private final String nonZeroDigit          = "[1-9]";
67
    static private final String seconds               = "([0-5]" + digit + "((\\.|,)" + digit + digit+ "?" + digit + "?" + ")?)";
68
    static private final String minutes               = "([0-5]" + digit + ")";
69
    static private final String hours                 = "(0" + digit + "|1" + digit + "|2[0-3])";
70
    static private final String time                  = hours + ":" + minutes + "(:" + seconds + ")?";
71
    static private final String days                  = "(0?" + nonZeroDigit + "|1" + digit + "|2" + digit + "|30|31)";
72
    static private final String months                = "(0?" + nonZeroDigit + "|10|11|12)";
73
    static private final String year                  = "(" + digit + digit + ")";
74
    static private final String century               = "(" + digit + digit + ")";
75
    static private final String floatingPointNumber   = "(" + digit + "+(\\." + digit + "+)?)";
76

  
77
    private String              unit;
78
	private String              unitSymbol;
79
	private List<GregorianCalendar>   
80
	                            valueList;
81
	private boolean             compiled;
82
	private boolean             isGeologic;
83
	private String              expression;
84
	private int                 type;
85
	private byte                format               = 0;
86

  
87
    static private final String regexDateExtendedForBCE1 = "B?"+century+year;
88
    static private final String regexDateExtendedForBCE2 = "B?"+century+year+"-"+months;
89
    static private final String regexDateExtendedForBCE3 = "B?"+century+year+"-"+months+"-"+days;
90
    static private final String regexDateExtendedForBCE4 = "B?"+century+year+"-"+months+"-"+days+"(T| )"+time+"Z";
91
    // Note: in WMS 1.1.0 the suffix Z is optional
92

  
93
    static private final String regexDateExtendedForBCE =
94
        "(" +  regexDateExtendedForBCE1  + "|"
95
            +  regexDateExtendedForBCE2  + "|"
96
            +  regexDateExtendedForBCE3  + "|"
97
            +  regexDateExtendedForBCE4  +      ")";
98

  
99
    static private final String periodMagnitude = "(Y|M|D)";
100
    static private final String p1 = "(("+digit+")+"+periodMagnitude+")";
101

  
102
    static private final String timeMagnitude = "(H|M|S)";
103
    static private final String p2 = "("+floatingPointNumber+timeMagnitude+")";
104
    static private final String regexPeriod = "P(("+p1+"+"+"(T"+p2+")*)|("+p1+"*"+"(T"+p2+")+))";
105

  
106
    static private final String regexIntervalTimeDimension =
107
        "("+regexDateExtendedForBCE+")/("+regexDateExtendedForBCE+")/("+regexPeriod+")";
108

  
109
    static private final String geologicDatasets = "(K|M|G)";
110
    static private final String regexDateForGeologicDatasets = geologicDatasets+floatingPointNumber;
111

  
112
	@SuppressWarnings("unchecked")
113
	public void loadFromState(PersistentState state) throws PersistenceException {
114
		this.unit = state.getString("unit");
115
		this.unitSymbol = state.getString("unitSymbol");
116
		
117
		List<String> list = (List<String>)state.getList("valueList");
118
		valueList = convertStringListToGregorianCalendarList(list);
119
		
120
		this.compiled = state.getBoolean("compiled");
121
		this.isGeologic = state.getBoolean("isGeologic");
122
		this.expression = state.getString("expression");
123
		this.type = state.getInt("type");
124
		this.format = (byte)state.getInt("format");
125
	}
126
	
127
	public void saveToState(PersistentState state) throws PersistenceException {
128
		state.set("unit", unit);
129
		state.set("unitSymbol", unitSymbol);
130
		state.set("valueList", convertGregorianCalendarListToStringList(valueList));
131
		state.set("compiled", compiled);
132
		state.set("isGeologic", isGeologic);
133
		state.set("expression", expression);
134
		state.set("type", type);
135
		state.set("format", format);
136
	}	
137
	
138
	private List<String> convertGregorianCalendarListToStringList(List<GregorianCalendar> gList) {
139
		List<String> l = new ArrayList<String>();
140
		for (int i = 0; i < gList.size(); i++) {
141
			l.add(toString(gList.get(i)));
142
		}
143
		return l;
144
	}
145
	
146
	private List<GregorianCalendar> convertStringListToGregorianCalendarList(List<String> sList) {
147
		List<GregorianCalendar> l = new ArrayList<GregorianCalendar>();
148
		for (int i = 0; i < sList.size(); i++) {
149
			l.add(valueOf(sList.get(i)));
150
		}
151
		return l;
152
	}
153
	
154
	public static void registerPersistent() {
155
		PersistenceManager manager = ToolsLocator.getPersistenceManager();
156
		DynStruct definition = manager.getDefinition("TimeDimension_Persistent");
157
		if( definition == null ) {
158
			definition = manager.addDefinition(
159
					TimeDimension.class,
160
					"TimeDimension_Persistent",
161
					"TimeDimension Persistence",
162
					null, 
163
					null
164
			);
165
		}
166
		
167
		definition.addDynFieldString("unit").setMandatory(false);
168
		definition.addDynFieldString("unitSymbol").setMandatory(false);
169
		definition.addDynFieldList("valueList").setClassOfItems(String.class).setMandatory(false);
170
		definition.addDynFieldBoolean("compiled").setMandatory(false);
171
		definition.addDynFieldBoolean("isGeologic").setMandatory(false);
172
		definition.addDynFieldString("expression").setMandatory(false);
173
		definition.addDynFieldInt("type").setMandatory(false);
174
		definition.addDynFieldInt("format").setMandatory(false);
175
	}
176
	
177
	public TimeDimension() {}
178
	
179
    /**
180
     * Creates a new instance of TimeDimension.
181
     * @param units
182
     * @param unitSymbol
183
     * @param expression
184
     */
185
    public TimeDimension(String _units, String _unitSymbol, String _dimensionExpression) {
186
        this.unit = _units;
187
        this.unitSymbol = _unitSymbol;
188
        setExpression(_dimensionExpression);
189
    }
190

  
191
	public String getName() {
192
        return "TIME";
193
    }
194

  
195
    public String getUnit() {
196
        return unit;
197
    }
198

  
199
    public String getUnitSymbol() {
200
        return unitSymbol;
201
    }
202

  
203
	public String getLowLimit() {
204
		return valueAt(0);
205
	}
206

  
207
	public String getHighLimit() {
208
		return valueAt(valueList.size() - 1);
209
	}
210

  
211

  
212
	public String getResolution() {
213
		return null;
214
	}
215

  
216
	public boolean isValidValue(String value) {
217
		return (value.matches(regexDateForGeologicDatasets) || value.matches(regexDateExtendedForBCE));
218
	}
219

  
220
	public GregorianCalendar valueOf(String value) throws IllegalArgumentException {
221
		if (compiled) {
222
    		String myValue = value.toUpperCase();
223
    		if (isValidValue(myValue)) {
224
    			GregorianCalendar val = null;
225
    			if (!isGeologic){
226
    				// This is a normal date
227
    				int myYear;
228
    				int myMonth;
229
    				int myDay;
230
    				int myHour;
231
    				int myMinute;
232
    				float mySecond;
233
    				String[] s = myValue.split("-");
234
    				myYear = (s[0].charAt(0)=='B') ? -Integer.parseInt(s[0].substring(1, 5)) : Integer.parseInt(s[0].substring(0, 4));
235
    				myMonth = (s.length>1) ? Integer.parseInt(s[1])-1 : 0;
236
    				if (myValue.matches(regexDateExtendedForBCE4)){
237
    					if (s[2].endsWith("Z"))
238
    						s[2] = s[2].substring(0,s[2].length()-1);
239
    					s = (s[2].indexOf('T')!=-1) ? s[2].split("T") : s[2].split(" ");
240
    					myDay = Integer.parseInt(s[0]);
241

  
242
    					// Go with the time
243
    					s = s[1].split(":");
244
    					myHour = Integer.parseInt(s[0]);
245
    					myMinute = (s.length>1) ? Integer.parseInt(s[1]) : 0;
246
    					mySecond = (s.length>2) ? Float.parseFloat(s[2]) : 0;
247
    				} else {
248
    					myDay = (s.length>2) ? Integer.parseInt(s[2]) : 1;
249

  
250
    					myHour = 0;
251
    					myMinute = 0;
252
    					mySecond = 0;
253
    				}
254
    				GregorianCalendar cal = new GregorianCalendar(myYear, myMonth, myDay, myHour, myMinute, (int)mySecond);
255
    				val = cal;
256
    			} else{
257
    				// this is a geological date >:-(
258
    			}
259
    			return val;
260
    		} else throw new IllegalArgumentException(myValue);
261
    	}
262
    	return null;
263
	}
264

  
265
	public String valueAt(int pos) throws ArrayIndexOutOfBoundsException {
266
		return toString((GregorianCalendar) valueList.get(pos));
267
	}
268

  
269
	public int valueCount() {
270
		return valueList.size();
271
	}
272

  
273
	public String getExpression() {
274
		return expression;
275
	}
276

  
277
	public void setExpression(String expr) {
278
		this.expression = expr;
279
	}
280

  
281
	public int getType() {
282
		return type;
283
	}
284

  
285
	public void compile() throws IllegalArgumentException {
286
		compiled = true;
287
		valueList = new ArrayList<GregorianCalendar>();
288
		String[] items = expression.split(",");
289
		for (int i = 0; i < items.length; i++) {
290
			// Each iteration is a value of a comma-separated list
291
			// which can be a single date or even an expression defining
292
			// an interval.
293
			items[i] = items[i].trim();
294
			if (items[i].matches(regexDateExtendedForBCE1)) {
295
				upgradeFormat(YEAR_FORMAT);
296
				valueList.add(valueOf(items[i]));
297
			} else if (items[i].matches(regexDateExtendedForBCE2)) {
298
				upgradeFormat(YEAR_TO_MONTH_FORMAT);
299
				valueList.add(valueOf(items[i]));
300
			} else if (items[i].matches(regexDateExtendedForBCE3)) {
301
				upgradeFormat(YEAR_TO_DAY_FORMAT);
302
				valueList.add(valueOf(items[i]));
303
			} else if (items[i].matches(regexDateExtendedForBCE4)) {
304
				upgradeFormat(FULL_FORMAT);
305
				valueList.add(valueOf(items[i]));
306
			} else if (items[i].matches(regexIntervalTimeDimension)) {
307
				// Analyze and transform this interval expression to a list
308
				// of values.
309

  
310
				// min value
311
				String[] s = items[i].split("/");
312
				if (s[0].matches(regexDateExtendedForBCE1)) {
313
					upgradeFormat(YEAR_FORMAT);
314
				} else if (s[0].matches(regexDateExtendedForBCE2)) {
315
					upgradeFormat(YEAR_TO_MONTH_FORMAT);
316
				} else if (s[0].matches(regexDateExtendedForBCE3)) {
317
					upgradeFormat(YEAR_TO_DAY_FORMAT);
318
				} else if (s[0].matches(regexDateExtendedForBCE4)) {
319
					upgradeFormat(FULL_FORMAT);
320
				}
321
				GregorianCalendar minValue = valueOf(s[0]);
322

  
323
				// max value
324
				if (s[0].matches(regexDateExtendedForBCE1)) {
325
					upgradeFormat(YEAR_FORMAT);
326
				} else if (s[1].matches(regexDateExtendedForBCE2)) {
327
					upgradeFormat(YEAR_TO_MONTH_FORMAT);
328
				} else if (s[1].matches(regexDateExtendedForBCE3)) {
329
					upgradeFormat(YEAR_TO_DAY_FORMAT);
330
				} else if (s[1].matches(regexDateExtendedForBCE4)) {
331
					upgradeFormat(FULL_FORMAT);
332
				}
333
				GregorianCalendar maxValue = valueOf(s[1]);
334

  
335
				String period = s[2];
336

  
337
				if (period == null) {
338
					valueList.add(minValue);
339
					valueList.add(maxValue);
340
					continue;
341
				}
342

  
343
				long x1 = ((GregorianCalendar) maxValue).getTimeInMillis();
344
				long x0 = ((GregorianCalendar) minValue).getTimeInMillis();
345
				long distance = x1-x0;
346
				long step = 0;
347

  
348
				boolean isTimeField = false;
349
				String val = "";
350

  
351
				for (int j = 0; j < period.length(); j++) {
352
					if (period.charAt(j) == 'P')
353
						continue;
354
					if (period.charAt(j) == 'T') {
355
						isTimeField = true;
356
						continue;
357
					}
358
					switch (period.charAt(j)) {
359
					case 'Y':
360
						step += Integer.parseInt(val) * millisXyear;
361
						val = "";
362
						break;
363
					case 'M':
364
						if (isTimeField)
365
							step += Integer.parseInt(val) * millisXminute;
366
						else
367
							step += Integer.parseInt(val) * millisXmonth;
368
						val = "";
369
						break;
370
					case 'D':
371
						step += Integer.parseInt(val) * millisXday;
372
						val = "";
373
						break;
374
					case 'H':
375
						step += Integer.parseInt(val) * millisXhour;
376
						val = "";
377
						break;
378
					case 'S':
379
						step += Integer.parseInt(val) * 1000;
380
						val = "";
381
						break;
382
					default:
383
						val += period.charAt(j);
384
						break;
385
					}
386
				}
387
				// Now that we know the earliest and the latest date and the period
388
				// between two dates, I'm going to populate the list of values
389
				// considering these values.
390
				int valueCount = (int)(distance/step) + 1; // + 1 for the initial point
391
				valueList.add(minValue);
392
				for (int pos = 1; pos < valueCount; pos++) {
393
					long newTime = ((GregorianCalendar) minValue).getTimeInMillis();
394
	    			newTime += (step*pos);
395
	    			GregorianCalendar cal = new GregorianCalendar();
396
	    			cal.setTimeInMillis(newTime);
397
	    			if (cal.after(maxValue) || cal.before(minValue))
398
	    				continue;
399

  
400
	    			valueList.add(cal);
401
				}
402
				valueList.add(maxValue);
403
			} else {
404
				compiled = false;
405
				throw new IllegalArgumentException();
406
			}
407
		}
408
    }
409

  
410
	/**
411
	 * Prints a GregorianCalendar value in WMS1.1.1 format.
412
	 * @param cal
413
	 * @return
414
	 */
415
	private String toString(GregorianCalendar cal) {
416
		int iYear   = cal.get(Calendar.YEAR);
417
		int iMonth  = cal.get(Calendar.MONTH) + 1;
418
		int iDay    = cal.get(Calendar.DAY_OF_MONTH);
419
		int iHour   = cal.get(Calendar.HOUR_OF_DAY);
420
		int iMinute = cal.get(Calendar.MINUTE);
421
		int iSecond = cal.get(Calendar.SECOND);
422
		String myYear;
423
		if (iYear<10)
424
			myYear = "200"+iYear;
425
		else if (iYear<100)
426
			myYear = "20"+iYear;
427
		else if (iYear<1000)
428
			myYear = "2"+iYear;
429
		else
430
			myYear = ""+iYear;
431
		String myMonth       = (iMonth<10) ? "0"+iMonth  : ""+iMonth;
432
		String myDay         = (iDay<10)   ? "0"+iDay    : ""+iDay;
433
		String myHour        = (iHour<10)  ? "0"+iHour   : ""+iHour;
434
		String myMinute      = (iMinute<10)? "0"+iMinute : ""+iMinute;
435
		String mySecond      = (iSecond<10)? "0"+iSecond : ""+iSecond;
436
		int myMilliSecond = cal.get(Calendar.MILLISECOND);
437

  
438

  
439
		String s = null;
440
		if (format == YEAR_FORMAT)
441
			s = myYear+"";
442
		else if (format == YEAR_TO_MONTH_FORMAT)
443
			s = myYear+"-"+myMonth;
444
		else if (format == YEAR_TO_DAY_FORMAT)
445
			s = myYear+"-"+myMonth+"-"+myDay;
446
		else if (format == FULL_FORMAT)
447
			s = myYear+"-"+myMonth+"-"+myDay+"T"+myHour+":"+myMinute+":"+mySecond+"."+(myMilliSecond/10)+"Z";
448
		if (iYear<0)
449
			s = "B"+s;
450
		return s;
451
	}
452

  
453
	private void upgradeFormat(byte sFormat) {
454
		switch (sFormat) {
455
		case YEAR_FORMAT:
456
			if (format < YEAR_FORMAT)
457
				format = YEAR_FORMAT;
458
			break;
459
		case YEAR_TO_MONTH_FORMAT:
460
			if (format < YEAR_TO_MONTH_FORMAT)
461
				format = YEAR_TO_MONTH_FORMAT;
462
			break;
463
		case YEAR_TO_DAY_FORMAT:
464
			if (format < YEAR_TO_DAY_FORMAT)
465
				format = YEAR_TO_DAY_FORMAT;
466
			break;
467
		case FULL_FORMAT:
468
			if (format < FULL_FORMAT)
469
				format = FULL_FORMAT;
470
			break;
471
		}
472
	}
473
}
474

  
475

  
0 476

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

  
24
import org.gvsig.tools.ToolsLocator;
25
import org.gvsig.tools.dynobject.DynStruct;
26
import org.gvsig.tools.persistence.PersistenceManager;
27
import org.gvsig.tools.persistence.PersistentState;
28
import org.gvsig.tools.persistence.exception.PersistenceException;
29

  
30

  
31
/**
32
 * This class instances a regular WMS dimension. It handles single, multiple and
33
 * interval values and uses them as they were a point, a list or a regularly
34
 * split line, respectivelly.<br>
35
 * <p>
36
 * As far as it implements RemoteTimeDimension it uses the same interface and
37
 * documentation.
38
 * </p>
39
 * @author jaume dominguez faus (jaume.dominguez@iver.es)
40
 *
41
 */
42
public class DefaultDimension implements RemoteTimeDimension {
43
	static private final String digit = "[0-9]";
44
    static private final String nonZeroDigit = "[1-9]";
45
    static private final String letter = "[_$%a-zA-Z]";
46
    static private final String word = letter+"("+letter+"|"+digit+")+"; // TODO Should be * instead of + ??
47
    static private final String floatingPointNumber = "("+digit+"+(\\."+digit+"+)?)";
48
    static private final String integerNumber = nonZeroDigit+digit+"+";
49
    static private final String dimensionItem = "("+floatingPointNumber+"|"+word+")";
50
    /**
51
     * regular expression for matching dimensions.
52
     */
53
    static private final String regexpDefaultDimensionExpression =
54
    	"("+floatingPointNumber+"/"+floatingPointNumber+"/"+floatingPointNumber+"|"+
55
    	    dimensionItem+"(,"+dimensionItem+")*)";
56
    
57
	private String name;
58
    private String unit;
59
    private String unitSymbol;
60
    private String expression;
61
    private String period;
62
    private Object minValue;
63
    private Object maxValue;
64
	private int type;
65
	private boolean compiled = false;
66
	
67
	public void loadFromState(PersistentState state) throws PersistenceException {
68
		this.name = state.getString("name");
69
		this.unit = state.getString("unit");
70
		this.unitSymbol = state.getString("unitSymbol");
71
		this.expression = state.getString("expression");
72
		this.period = state.getString("period");
73
		this.minValue = state.getString("minValue");
74
		this.maxValue = state.getString("maxValue");
75
		this.type = state.getInt("type");
76
		this.compiled = state.getBoolean("compiled");
77
	}
78
	
79
	public void saveToState(PersistentState state) throws PersistenceException {
80
		state.set("name", name);
81
		state.set("unit", unit);
82
		state.set("unitSymbol", unitSymbol);
83
		state.set("expression", expression);
84
		state.set("period", period);
85
		state.set("minValue", minValue);
86
		state.set("maxValue", maxValue);
87
		state.set("type", type);
88
		state.set("compiled", compiled);
89
	}	
90
	
91
	public static void registerPersistent() {
92
		PersistenceManager manager = ToolsLocator.getPersistenceManager();
93
		DynStruct definition = manager.getDefinition("DefaultDimension_Persistent");
94
		if( definition == null ) {
95
			definition = manager.addDefinition(
96
					DefaultDimension.class,
97
					"DefaultDimension_Persistent",
98
					"DefaultDimension Persistence",
99
					null, 
100
					null
101
			);
102
		}
103

  
104
		definition.addDynFieldString("name").setMandatory(false);
105
		definition.addDynFieldString("unit").setMandatory(false);
106
		definition.addDynFieldString("unitSymbol").setMandatory(false);
107
		definition.addDynFieldString("expression").setMandatory(false);
108
		definition.addDynFieldString("period").setMandatory(false);
109
		definition.addDynFieldString("minValue").setMandatory(false);
110
		definition.addDynFieldString("maxValue").setMandatory(false);
111
		definition.addDynFieldInt("type").setMandatory(false);
112
		definition.addDynFieldBoolean("compiled").setMandatory(false);
113
	}
114
	
115
	public DefaultDimension() {}
116
	 
117
    /**
118
     * Creates a new instance of DefaultDimension.
119
     * @param _name
120
     * @param _units
121
     * @param _unitSymbol
122
     * @param _dimensionExpression
123
     */
124
    public DefaultDimension(String _name, String _units, String _unitSymbol, String _dimensionExpression) {
125
    	this.name = _name;
126
    	this.unit = _units;
127
    	this.unitSymbol = _unitSymbol;
128
    	setExpression(_dimensionExpression);
129
    }
130
    
131
    public String getName() {
132
		return name;
133
	}
134

  
135
	public String getUnit() {
136
		return unit;
137
	}
138

  
139
	public String getUnitSymbol() {
140
		return unitSymbol;
141
	}
142

  
143
	public String getLowLimit() {
144
		return (String) minValue;
145
	}
146

  
147
	public String getHighLimit() {
148
		return (String) maxValue;
149
	}
150

  
151
	public String getResolution() {
152
		if (type == INTERVAL) {
153
    		String[] s = expression.split("/");
154
    		return (s.length == 1) ? s[3] : null;
155
    	} else return null;
156
	}
157

  
158
	public boolean isValidValue(String value) {
159
		return value.matches(word) || value.matches(floatingPointNumber);
160
	}
161

  
162
	public Object valueOf(String value) throws IllegalArgumentException {
163
		if (compiled) {
164
			if (value.matches(word)) {
165
				return (String) value;
166
			} else if (value.matches(integerNumber)){
167
				return new Integer(value);
168
			}
169
			else if (value.matches(floatingPointNumber)) {
170
				return new Float(value);
171
			}
172
		}
173
		return null;
174
	}
175

  
176
	public String valueAt(int pos) throws ArrayIndexOutOfBoundsException {
177
		if (compiled) {
178
			if (pos<0 || pos>valueCount())
179
				throw new ArrayIndexOutOfBoundsException(pos+"(must be >= 0 and <="+valueCount()+")");
180
			
181
			if (type == SINGLE_VALUE)
182
				return expression;
183
			
184
			if (type == MULTIPLE_VALUE)
185
				return expression.split(",")[pos];
186
			
187
			if (type == INTERVAL) {
188
				double minPos = Double.parseDouble((String) minValue);
189
				double maxPos = Double.parseDouble((String) maxValue);
190
				double step = Double.parseDouble(period);
191
				double newPos = minPos + (step*pos);
192
				if (newPos < minPos)
193
					return minPos+"";
194
				
195
				if (newPos > maxPos)
196
					return maxPos+"";
197
				return newPos+"";
198
			}
199
		}
200
        return null;
201
	}
202

  
203
	public int valueCount() {
204
		if (compiled) {
205
			if (type == MULTIPLE_VALUE) {
206
				return expression.split(",").length;
207
			} else if (type == INTERVAL) {
208
				int count;
209
				double min = Double.parseDouble((String) minValue);
210
				double max = Double.parseDouble((String) maxValue);
211
				double step = Double.parseDouble(period);
212
				double distance = max - min;
213
				count = (int) (distance/step);
214
				return count;
215
			} else {
216
				return 1;
217
			}
218
		}
219
		return -1;
220
	}
221

  
222
	public String getExpression() {
223
		return expression;
224
	}
225

  
226
	public void setExpression(String expr) {
227
		expression = expr.toUpperCase();
228
        
229
	}
230

  
231
	public int getType() {
232
		return type;
233
	}
234

  
235
	public void compile() throws IllegalArgumentException {
236
		if (expression.matches(regexpDefaultDimensionExpression)){
237

  
238
        } else {
239
            //System.err.println("Invalid dimension expression: "+expr+" (for "+this.getName()+")");
240
            throw new IllegalArgumentException();
241
        }
242
		
243

  
244
        String separator;
245
        if (expression.indexOf("/")!=-1) {
246
        	separator = "/";
247
        	type = INTERVAL;
248
        } else if (expression.indexOf(",")!=-1) {
249
        	separator = ",";
250
        	type = MULTIPLE_VALUE;
251
        } else {
252
        	separator = ",";
253
        	type = SINGLE_VALUE;
254
        }
255
        compiled = true;
256
        String[] s = expression.split(separator);
257
        minValue = valueOf(s[0]);
258
        if (type == INTERVAL) {
259
        	maxValue = (s.length>1) ? valueOf(s[1]) : valueOf(s[0]);
260
        	period = (s.length>2) ? s[2] : null;
261
        } else if (type == MULTIPLE_VALUE) {
262
        	maxValue = valueOf(s[s.length-1]);
263
        } else {
264
        	maxValue = valueOf(s[0]);
265
        }
266
        
267
	}
268

  
269
}
0 270

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

  
24
import org.gvsig.tools.persistence.Persistent;
25

  
26

  
27
/**
28
 * 
29
 * @author jaume
30
 *
31
 */
32
public interface RemoteTimeDimension extends Persistent {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff