Class TiledGridCoverageResource
- All Implemented Interfaces:
DataSet, GridCoverageResource, Resource, TiledResource
GridCoverageResource.getGridGeometry()GridCoverageResource.getSampleDimensions()getTileSize()getSampleModel(int[])(optional but recommended)getColorModel(int[])(optional but recommended)read(Subset)
- Since:
- 1.7
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceDescription of aTileMatrixSetimplemented as an image pyramid.classParameters that describe the resource subset to be accepted by theTiledGridCoverageconstructor.Nested classes/interfaces inherited from interface Resource
Resource.FileSetModifier and TypeInterfaceDescriptionstatic classPaths to the files potentially used by the enclosing resource. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static final intNumber of dimensions in a two-dimensional slice of data represented as a rendered image.Fields inherited from class AbstractResource
listenersModifier and TypeFieldDescriptionprotected final StoreListenersThe set of registeredStoreListeners for this resources. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedTiledGridCoverageResource(Resource parent) Creates a new resource. -
Method Summary
Modifier and TypeMethodDescriptionprotected booleancanReadTruncatedTiles(int dim, boolean suggested) Returnstrueif the reader can load truncated tiles.protected booleanReturnstrueif the reader can load only the requested bands and skip the other bands, orfalseif the reader must load all bands.protected TiledGridCoverageResource.PyramidchoosePyramid(GridGeometry domain, int[] ranges) Chooses the pyramid to use for reading the specified subset from this resource.protected voidClears all data cached in this resource, forcing the data to be reloaded when needed again.protected TiledGridCoverageResource.SubsetdescribeSubset(GridGeometry domain, int[] range) Prepares a description of the resource subset to be accepted by theTiledGridCoverageconstructor.protected intgetAtomSize(int dim) Returns the number of sample values in an indivisible element of a tile.List<double[]> Returns the preferred resolutions (in units of CRS axes) for read operations in this data store.protected ColorModelgetColorModel(int[] bands) Returns the Java2D color model for rendering images, ornullif none.protected Number[]getFillValues(int[] bands) Returns the values to use for filling empty spaces in rasters, with one value per band.protected GridGeometryReturns the grid geometry with missing properties defaulting to the properties of a grid CRS.Returns an indication about when the "physical" loading of raster data will happen.protected List<TiledGridCoverageResource.Pyramid> Returns information about theTileMatrixSetinstances to create.protected SampleModelgetSampleModel(int[] bands) Returns the Java2D sample model describing pixel type and layout for the specified bands.Collection<? extends TileMatrixSet> Returns the collection of all available tile matrix sets in this resource.protected abstract int[]Returns the size of tiles in the grid coverages read by this resource.read(GridGeometry domain, int... ranges) Loads a subset of the grid coverage represented by this resource.protected abstract TiledGridCoverageCreates a coverage which will read the specified subset from this resource when first requested.booleansetLoadingStrategy(RasterLoadingStrategy strategy) Sets the preferred strategy about when to do the "physical" loading of raster data.protected voidsetRasterSubspaceDimensions(int xDimension, int yDimension) Sets the mapping from grid dimensions to image axes.protected booleansupportsVirtualTileSize(long[] virtualTileSize) Returns whether this resource can read a tiled image as if the tiles had the specified size.Methods inherited from class AbstractGridCoverageResource
canNotRead, convertResolutionOf, createMetadata, getEnvelope, logReadOperationModifier and TypeMethodDescriptionprotected DataStoreExceptioncanNotRead(String filename, GridGeometry request, Throwable cause) Creates an exception for a failure to load data.protected double[]convertResolutionOf(GridGeometry domain) Returns the resolution of the given grid geometry as a resolution in units of this coverage CRS.protected MetadataInvoked in a synchronized block the first time thatgetMetadata()is invoked.Returns the envelope of the grid geometry if known.protected voidlogReadOperation(Object file, GridGeometry domain, long startTime) Logs the execution of aGridCoverageResource.read(GridGeometry, int...)operation.Methods inherited from class AbstractResource
addListener, getMetadata, getSynchronizationLock, removeListenerModifier and TypeMethodDescription<T extends StoreEvent>
voidaddListener(Class<T> eventType, StoreListener<? super T> listener) Registers a listener to notify when the specified kind of event occurs in this resource or in children.final MetadataReturns a description of this resource.protected ObjectReturns the object on which to perform synchronizations for thread-safety.<T extends StoreEvent>
voidremoveListener(Class<T> eventType, StoreListener<? super T> listener) Unregisters a listener previously added to this resource for the given type of events.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface GridCoverageResource
getGridGeometry, getResolutions, getSampleDimensions, subsetModifier and TypeMethodDescriptionReturns the valid extent of grid coordinates together with the conversion from those grid coordinates to real world coordinates.default List<double[]> Deprecated, for removal: This API element is subject to removal in a future version.Returns the ranges of sample values together with the conversion from samples to real values.default GridCoverageResourceRequests a subset of the coverage.Methods inherited from interface Resource
getFileSet, getIdentifierModifier and TypeMethodDescriptiondefault Optional<Resource.FileSet> Gets the paths to the files potentially used by this resource.default Optional<GenericName> Returns the resource persistent identifier.
-
Field Details
-
BIDIMENSIONAL
protected static final int BIDIMENSIONALNumber of dimensions in a two-dimensional slice of data represented as a rendered image. This constant can be used for making easier to identify codes where a two-dimensional slice is assumed.- See Also:
-
-
Constructor Details
-
TiledGridCoverageResource
Creates a new resource.- Parameters:
parent- the parent resource, ornullif none.
-
-
Method Details
-
getTileSize
Returns the size of tiles in the grid coverages read by this resource. The length of the returned array is the number of dimensions, which must be 2 or greater.- Returns:
- the size of tiles (in pixels) in the
RenderedImages created by this resource. - Throws:
DataStoreException- if an error occurred while fetching the tile size.
-
getAtomSize
Returns the number of sample values in an indivisible element of a tile. An element is a primitive type such asbyte,intorfloat. This value is usually 1 when each sample value is stored in a separated element. However, in multi-pixels packed sample model (e.g. bilevel image with 8 pixels per byte), it is difficult to start reading an image at x location other than a byte boundary. By declaring an "atom" size of 8 sample values in dimension 0 (x), theTiledGridCoverageResource.Subsetconstructor will ensure that the sub-region to read starts at a byte boundary when reading a bilevel image.The default implementation returns the number of pixels per data element for dimension 0 and returns 1 for all other dimensions.
- Parameters:
dim- the dimension: 0 for x, 1 for y, etc.- Returns:
- indivisible number of sample values to read in the specified dimension. Must be ≥ 1. This is in units of sample values (may be bits, bytes, floats, etc).
- Throws:
DataStoreException- if an error occurred while fetching the sample model.
-
supportsVirtualTileSize
Returns whether this resource can read a tiled image as if the tiles had the specified size. This method is invoked whenTiledGridCoverageResourcewishes to create an image with tiles that are larger or smaller than the real tile size returned bygetTileSize(). A return value oftruemeans that the subclass can use the given tile size easily. It is the case, for example, if the subclass delegates its work to another library such as GDAL which answers to arbitrary requests with its own tile management. If this method returnsfalse, thenTiledGridCoverageResourcemay try a different tile size or use a fallback simulating the desired tiling.Tile size amendment
If the subclass does not support exactly the given size but would support a slightly different size, then this method can modify the givenvirtualTileSizearray in-place and returntrue. The updated values will be used by the caller as the new virtual tile size.Use cases
TiledGridCoverageResourcemay want to read many tiles as if they were a single tile. Such coalescing can be useful for avoiding that a read operation produces tiles that become too small after subsampling. In such case, virtual tile sizes are larger than real tile sizes.Conversely,
TiledGridCoverageResourcemay want to apply an artificial tiling on an untiled image, or re-tile an image having unreasonably large tiles (with "unreasonable" defined by an arbitrary threshold). This is done by using a virtual tile size which is smaller than the real tile size. Note that this artificial tiling is applied only if the loading strategy isRasterLoadingStrategy.AT_GET_TILE_TIMEor, to a lesser extent,AT_RENDER_TIME.Note for implementers
Except in untiled cases,TiledGridCoveragealigns theGridExtents requested by users on the boundaries of real tiles, not on the boundaries of virtual tiles. Therefore, a subclass should returntruefor arbitrary virtual tile sizes only if that subclass can read fractions of the areas covered by real tiles and assemble these areas in a singleRaster. If the subclass can assemble only whole real tiles, then this method should accept only virtual tile sizes that are multiple of the real tile size.This method is not invoked for the values returned by
getTileSize(). It may not be invoked neither for untiled image. Therefore, this method does not need to handle those special cases. The default implementation unconditionally returnsfalse.- Parameters:
virtualTileSize- the size of virtual tiles. Can be amended in-place.- Returns:
- whether this resource can pretend that tiles have the given size.
- Throws:
DataStoreException- if an error occurred while verifying the tile size.- See Also:
-
canReadTruncatedTiles
protected boolean canReadTruncatedTiles(int dim, boolean suggested) Returnstrueif the reader can load truncated tiles. Truncated tiles may happen in the last row and last column of a tile matrix when the image size is not a multiple of the tile size. Some file formats, such as GeoTIFF, unconditionally store full tiles, in which case this method should returnfalse. At the opposite, some implementations, such as GDAL, accept only requests over the valid area, in which case this method should returntrue.Suggested value
Thesuggestedargument is a value computed by the caller based on common usages. The default implementation ofTiledGridCoveragesuggeststrueif the read operation is inside a single big tile, orfalseotherwise. The default implementation of this method returnssuggestedunchanged.Note that even for subclasses that generally do not support the reading of truncated tiles, it is often safe to return
truefor the last dimension (for example, y in a two-dimensional image), because there is no data after that dimension. Therefore, it is often safe to stop the reading process in that dimension.- Parameters:
dim- the dimension: 0 for x, 1 for y, etc.suggested- suggested response to return (see above heuristic rules).- Returns:
- whether the reader can load truncated tiles along the specified dimension.
-
canSeparateBands
Returnstrueif the reader can load only the requested bands and skip the other bands, orfalseif the reader must load all bands. This value controls the amount of data to be loaded byread(GridGeometry, int...):- If
false, thenTiledGridCoverage.modelwill expect the sameDataBufferthan the one expected by the sample model of this resource. All bands will be loaded but the coverage sample model will ignore the bands that were not enumerated in therangeargument. This strategy is convenient when skipping bands at reading time is difficult. - If
true, thenTiledGridCoverage.modelwill have its band indices and bit masks "compressed" for making them consecutive. For example if therangeargument specifies that the bands to read are {1, 3, 4, 6}, then after "compression" band indices become {0, 1, 2, 3}. This strategy is efficient when the reader is capable to skip bands at reading time.
The default implementation returns
trueif the sample model is aComponentSampleModelandfalsein all other cases, because skipping bands in a packed sample model is more difficult to implement.- Returns:
trueif the reader can load only the requested bands and skip other bands, orfalseif the reader needs to load all bands regardless therangesubset.- Throws:
DataStoreException- if an error occurred while fetching the sample model.- See Also:
- If
-
getSampleModel
Returns the Java2D sample model describing pixel type and layout for the specified bands. The raster size shall be the two first dimensions of the tile size. This is the size of tiles as stored in the resource, i.e. ignoring sub-sampling.If the
bandsargument isnull, then this method shall return the sample model for all bands and cannot returnnull. If thebandsargument is non-null, then this method may compute the sample model for the specified bands, or returnnullfor instructing the caller to derive the sample model fromgetSampleModel(null).Implementation note
The default implementation creates a sample model compatible with the color model if available, or otherwise defaults to aBandedSampleModelwhich stores samples as floating point values. This is okay for prototyping, but it is recommended to override this method with a simple model that better matches the data. A simple implementation can be as below:private SampleModel sampleModel; @Override protected SampleModel getSampleModel(int[] bands) throws DataStoreException { if (bands != null) { return null; } synchronized (getSynchronizationLock()) { if (sampleModel == null) { sampleModel = ...; // Compute and cache, because requested many times. } return sampleModel; } }- Parameters:
bands- indices (not necessarily in increasing order) of desired bands, ornullfor all bands.- Returns:
- the sample model for tiles at full resolution with the specified bands.
Shall be non-null if
bandsis null (i.e. the caller is requesting the main sample model). - Throws:
DataStoreException- if an error occurred during sample model construction.
-
getColorModel
Returns the Java2D color model for rendering images, ornullif none. The color model shall be compatible with the sample model returned bygetSampleModel(int[]).The default implementation returns a gray scale color model if there is only one band to show and the range of the sample dimension is known. OTherwise, this method returns
null. This is okay for prototyping, but it is recommended to override.- Parameters:
bands- indices (not necessarily in increasing order) of desired bands, ornullfor all bands.- Returns:
- a color model compatible with
getSampleModel(int[]), ornullif none. - Throws:
DataStoreException- if an error occurred during color model construction.
-
getFillValues
Returns the values to use for filling empty spaces in rasters, with one value per band. The returned array can benullif there is no fill value, or if the fill values are not different than zero, or are not valid for the image data type.Fill values are used when a tile contains less pixels than expected. A null array is a shortcut for skipping the filling of new tiles, because new tiles are already initialized with zero values by default.
The default implementation returns an array of
DataType.fillValue()except for the transparent pixel if any. If the array would contain only zero values, the default implementation returns null.- Parameters:
bands- indices (not necessarily in increasing order) of desired bands, ornullfor all bands.- Returns:
- the value to use for filling empty spaces in each band, or
nullfor defaulting to zero. - Throws:
DataStoreException- if an error occurred while fetching filling information.
-
getAvailableResolutions
Returns the preferred resolutions (in units of CRS axes) for read operations in this data store. The list elements are ordered from coarsest (largest numerical values) to finest (smallest numerical values).The default implementation uses information in the first element returned by
getPyramids(). It is generally easier for subclasses to overridegetPyramids()instead of this method.This returned list may defer the calculations of resolutions until first requested. If a
DataStoreExceptionoccurs during the invocation of aListmethod, the exception will be wrapped in aBackingStoreException.- Specified by:
getAvailableResolutionsin interfaceGridCoverageResource- Returns:
- resolutions at all levels in the default pyramid.
- Throws:
DataStoreException- if an error occurred while fetching the resolution.- See Also:
-
getTileMatrixSets
Returns the collection of all available tile matrix sets in this resource. The returned collection typically contains exactly one instance, which describes a pyramid in the same CRS as this Grid Coverage Resource.The default implementation uses the information provided by
getPyramids()for creating defaultTileMatrixSetinstances. It is generally easier for subclasses to overridegetPyramids()instead of this method.- Specified by:
getTileMatrixSetsin interfaceTiledResource- Returns:
- all available
TileMatrixSetinstances, or an empty collection if none. - Throws:
DataStoreException- if an error occurred while fetching the tile matrix sets.
-
describeSubset
protected TiledGridCoverageResource.Subset describeSubset(GridGeometry domain, int[] range) throws DataStoreException Prepares a description of the resource subset to be accepted by theTiledGridCoverageconstructor. This method is invoked by the default implementation ofread(GridGeometry, int...)for computing the argument given toread(Subset). The default implementation is as below:Thereturn new Subset(domain, range, ImageLayout.DEFAULT);ImageLayout.DEFAULTargument is a provider of virtual tile size suggestions. See theSubsetconstructor for more information. The suggested virtual tile sizes are submitted to thesupportsVirtualTileSize(long[])method and, if accepted, used by theTiledGridCoverageconstructor.Usage
This method is invoked by the default implementation ofread(GridGeometry, int...). This method should generally not be invoked by user's code. It is rather for overriding in subclasses. The caller is responsible for holding the synchronization lock.- Parameters:
domain- the domain argument specified by user in a call toGridCoverageResource.read(…).range- the range argument specified by user in a call toGridCoverageResource.read(…).- Returns:
- descriptions of the grid coverage subset identified by the given domain and range.
- Throws:
DataStoreException- if an error occurred while computing the subset description.RuntimeException- in case of arithmetic error, Java2D error or other errors.- See Also:
-
read
protected abstract TiledGridCoverage read(TiledGridCoverageResource.Subset subset) throws DataStoreException Creates a coverage which will read the specified subset from this resource when first requested. This method is invoked (indirectly) by the default implementation ofread(GridGeometry, int...). This method creates a subclass ofTiledGridCoveragewhich will read tiles later, when first requested. The implementation of this method does not need to care about synchronization, immediate (rather than deferred) loading of tiles, logging of loading time and handling ofRuntimeException. Those tasks should be handled by the caller.- Parameters:
subset- desired grid extent, resolution and sample dimensions to read.- Returns:
- the grid coverage for the specified domain, resolution and ranges.
- Throws:
DataStoreException- if the coverage cannot be created.RuntimeException- if the coverage cannot be created for a reason not handled as a data store exception.- See Also:
-
read
Loads a subset of the grid coverage represented by this resource. While this method name suggests an immediate reading, the actual reading may be deferred. This method performs the following steps:- Selects a
TiledGridCoverageResourceinstance for the pyramid level which is considered the best fit for the resolution of the specifieddomain. The selected instance may bethis. - Invokes the
describeSubset(GridGeometry, int[])method on the instance selected in above step. The createdTiledGridCoverageResource.Subsetcontains tiling and subsampling information adapted to the pyramid level. - Invokes the
TiledGridCoverageResource.Subset.createCoverage()method on theSubsetcreated in above step. - Above
createCoverage()method may callbackread(Subset)immediately, or may defer that callback to a later time. That callback is done on the sameTiledGridCoverageResourceinstance as the one that created theSubset(i.e., the instance selected in the first step as the best fit for the pyramid level). - If the current loading strategy is
RasterLoadingStrategy.AT_READ_TIME, forces the immediate reading of tiles and logs the time required for this operation.
- Specified by:
readin interfaceGridCoverageResource- Parameters:
domain- desired grid extent and resolution, ornullfor reading the whole domain.ranges- 0-based indices of sample dimensions to read, ornullor an empty sequence for reading them all.- Returns:
- the grid coverage for the specified domain and ranges.
- Throws:
DataStoreException- if an error occurred while reading the grid coverage data.- See Also:
- Selects a
-
choosePyramid
protected TiledGridCoverageResource.Pyramid choosePyramid(GridGeometry domain, int[] ranges) throws DataStoreException Chooses the pyramid to use for reading the specified subset from this resource. This method should return an element of the list returned bygetPyramids(). The chosen pyramid should be a best match, but does not need to be an exact match.The current implementation returns the first pyramid returned by
getPyramids(). Future versions of Apache SIS may improve this algorithm for taking in account at least the CRS.- Parameters:
domain- desired grid extent and resolution, ornullfor reading the whole domain.ranges- 0-based indices of sample dimensions to read, ornullor an empty sequence for reading them all.- Returns:
- the pyramid to use, or
nullif no pyramid can satisfy the given request. - Throws:
DataStoreException- if an error occurred while reading the grid coverage data.
-
getLoadingStrategy
Returns an indication about when the "physical" loading of raster data will happen.- Specified by:
getLoadingStrategyin interfaceGridCoverageResource- Returns:
- current raster data loading strategy for this resource.
- Throws:
DataStoreException- if an error occurred while fetching data store configuration.
-
setLoadingStrategy
Sets the preferred strategy about when to do the "physical" loading of raster data.- Specified by:
setLoadingStrategyin interfaceGridCoverageResource- Parameters:
strategy- the desired strategy for loading raster data.- Returns:
trueif the given strategy has been accepted, orfalseif this implementation replaced the given strategy by an alternative.- Throws:
DataStoreException- if an error occurred while setting data store configuration.
-
setRasterSubspaceDimensions
protected void setRasterSubspaceDimensions(int xDimension, int yDimension) throws DataStoreException Sets the mapping from grid dimensions to image axes. This method specifies the dimensions of the slices obtained when reading tiles. The values specified to this method are used, directly or indirectly, atTiledGridCoverageResource.Subsetcreation time. Therefore, calls to this method have an effect on the nextTiledGridCoverageinstances to be read, but not on the instances that are already read.If this method is never invoked, then by default the dimension 0 of the grid is mapped to the image x axis and the dimension 1 of the grid is mapped to the image y axis.
- Parameters:
xDimension- dimension of the grid which is mapped to the x axis (column indexes) in rendered images.yDimension- dimension of the grid which is mapped to the y axis (row indexes) in rendered images.- Throws:
IllegalArgumentException- ifxDimensionoryDimensionis negative, or the two values are equal.DataStoreException- if another error occurred while setting the mapping from grid dimensions to image axes.- See Also:
-
getPyramids
Returns information about theTileMatrixSetinstances to create. If the returned list is non-empty, then the first element shall be the default pyramid using the same Coordinate Reference System (CRS) as this Grid Coverage Resource. Other elements, if any, can use any CRS.This method is invoked by the default implementation of
getTileMatrixSets()when first needed. By default, this method returns an empty list if this resource is untiled, or otherwise a list of exactly one element describing a pyramid of only one level. This single level describes aTileMatrixat the resolution of thisTiledGridCoverageResource.- Returns:
- information about the tile matrix sets to create.
- Throws:
DataStoreException- if an error occurred while fetching information about the pyramid.- See Also:
-
getGridGeometryWithDefaults
Returns the grid geometry with missing properties defaulting to the properties of a grid CRS. This method usually returnsGridCoverageResource.getGridGeometry()unchanged, except in the following rare circumstance: if the grid geometry has no resolution, no "grid to CRS" transform and no CRS, then this method returns a grid geometry with the resolution set to 1, i.e. the resolution is defined as one unit of grid cell.This method can be invoked for computing the grid geometry of
TiledGridCoverage. This is particularly important in the context of pyramids because the levels are selected on the basis of their resolution. Implementations ofTiledGridCoverageResource.Pyramid.forPyramidLevel(int)are encouraged to use this method for the base level, and only that level.- Returns:
- grid geometry potentially completed with the addition of resolution and engineering CRS.
- Throws:
DataStoreException- if an error occurred while reading definitions from the underlying data store.
-
clearCache
protected void clearCache()Clears all data cached in this resource, forcing the data to be reloaded when needed again.- Overrides:
clearCachein classAbstractResource
-
GridCoverageResource.getAvailableResolutions()but with opposite order.