Class AnnotatedImage
- All Implemented Interfaces:
RenderedImage
- Direct Known Subclasses:
StatisticsCalculator
RenderedImage
methods delegate to the wrapped
image except ImageAdapter.getSources()
and the methods for getting the property names or values.
The name of the computed property is given by getComputedPropertyName()
.
If an exception is thrown during calculation and failOnException
is false
,
then AnnotatedImage
automatically creates another property with the same name and
".warnings" suffix. That property will contain the exception encapsulated
in a LogRecord
in order to retain additional information such as the instant when
the first error occurred.
The computation results are cached by this class. The cache strategy assumes that the property value depend only on sample values, not on properties of the source image.
PixelIterator
(among others) relies
on the fact that it can unwrap this image and still get the same pixel values.- Since:
- 1.1
- Version:
- 1.2
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final class
Keys in thecache
whenareaOfInterest
is non-null. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final Shape
Pixel coordinates of the region for which to compute the values, ornull
for the whole image.protected final Rectangle
Bounds ofareaOfInterest
intersected with image bounds, ornull
for the whole image.Cache of property values computed for the ImageAdapter.source image.private static final WeakHashMap
<RenderedImage, Cache<Object, Object>> Cache of properties already computed for images.private ErrorHandler.Report
The errors that occurred while computing the result, ornull
if none or not yet determined.private final boolean
Whether errors occurring during computation should be propagated instead of wrapped in aLogRecord
.private static final Object
An arbitrary value that we use for storingnull
values in the cache.private final boolean
Whether parallel execution is authorized for the ImageAdapter.source image.static final String
The suffix to add to property name for errors that occurred during computation.Fields inherited from class org.apache.sis.image.ImageAdapter
source
Fields inherited from class org.apache.sis.image.PlanarImage
GRID_GEOMETRY_KEY, MASK_KEY, POSITIONAL_ACCURACY_KEY, SAMPLE_RESOLUTIONS_KEY, STATISTICS_KEY
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
AnnotatedImage
(RenderedImage source, Shape areaOfInterest, boolean parallel, boolean failOnException) Creates a new annotated image wrapping the given image. -
Method Summary
Modifier and TypeMethodDescription(package private) final Class
<AnnotatedImage> appendStringContent
(StringBuilder buffer) Appends the name of the computed property in theImageAdapter.toString()
representation, after the class name and before the string representation of the wrapped image.protected Object
cloneProperty
(String name, Object value) Invoked when a property of the given name has been requested and that property is cached.Returns the function to execute for computing the property value, together with other required functions (supplier of accumulator, combiner, finisher).protected Object
Invoked when the property needs to be computed.protected abstract Object
Invoked when the property needs to be computed sequentially (all computations in current thread).private boolean
equalParameters
(AnnotatedImage other) Returnstrue
if the area of interest and some other fields are equal.final boolean
Compares the given object with this image for equality.private Object
getCacheKey
(String property) Returns the key to use for entries in thecache
map.protected abstract String
Returns the name of the property which is computed by this image.(package private) Object[]
Returns an optional parameter specific to subclass.final Object
getProperty
(String name) Gets a property from this image or from its source.String[]
Returns an array of names recognized bygetProperty(String)
.final int
hashCode()
Returns a hash code value for this image.private static boolean
isErrorProperty
(String cn, String name) Returns whether the given name is the name of the error property.(package private) final void
logAndClearError
(Class<?> classe, String method, ErrorHandler handler) If an error occurred, logs the message with the specified class and method as the source.(package private) final RenderedImage
unique()
If the source image is the same operation for the same area of interest, returns that source.Methods inherited from class org.apache.sis.image.ImageAdapter
copyData, getColorModel, getData, getData, getHeight, getMinTileX, getMinTileY, getMinX, getMinY, getNumXTiles, getNumYTiles, getSampleModel, getSources, getTile, getTileGridXOffset, getTileGridYOffset, getTileHeight, getTileWidth, getWidth, prefetch, toString
Methods inherited from class org.apache.sis.image.PlanarImage
getBounds, verify
-
Field Details
-
WARNINGS_SUFFIX
The suffix to add to property name for errors that occurred during computation. A property with suffix is automatically created if an exception is thrown during computation andfailOnException
isfalse
.- See Also:
-
NULL
An arbitrary value that we use for storingnull
values in the cache. -
CACHE
Cache of properties already computed for images. That map shall contain computation results only, never theAnnotatedImage
instances that computed those results, as doing so would create memory leak (because of theImageAdapter.source
reference preventing the key to be garbage-collected). All accesses to this cache shall be synchronized on theCACHE
instance.In current implementation we cache only the values that have been computed without warnings. We do that because otherwise, an
AnnotatedImage
withfailOnException
flag set could wrongly return a partially computed value if that value has been cached by another image instance with thefailOnException
flag unset. As a consequence of this policy, if the computation failed for some tiles, that computation will be redone again for the same property every time it is requested, until it eventually fully succeeds and the result become cached. -
cache
Cache of property values computed for the ImageAdapter.source image. This is an entry from the globalCACHE
. This cache is shared by allAnnotatedImage
instances wrapping the same ImageAdapter.source image in order to avoid computing the same property many times if anAnnotatedImage
wrapper is recreated many times for the same operation on the same image.Note that
null
is a valid result. SinceCache
cannot store null values, those results are replaced byNULL
.Keys are
String
instances containing directly the property name whenareaOfInterest
andgetExtraParameter()
arenull
, orAnnotatedImage.CacheKey
instances otherwise. -
areaOfInterest
Pixel coordinates of the region for which to compute the values, ornull
for the whole image. If non-null, theShape.contains(double, double)
method may be invoked for testing if a pixel shall be included in the computation or not.This shape should not be modified, either by this class or by the caller who provided the shape. The
Shape
implementation shall be thread-safe, assuming its state stay unmodified, unless theparallel
argument specified to the constructor wasfalse
.If
areaOfInterest
isnull
, thenboundsOfInterest
is alwaysnull
. However, the converse is not necessarily true. -
boundsOfInterest
Bounds ofareaOfInterest
intersected with image bounds, ornull
for the whole image. If the area of interest fully contains those bounds, thenareaOfInterest
is set to the same reference thanboundsOfInterest
. Subclasses can useareaOfInterest == boundsOfInterest
for quickly testing if the area of interest is rectangular.If
areaOfInterest
isnull
, thenboundsOfInterest
is alwaysnull
. However, the converse is not necessarily true. -
errors
The errors that occurred while computing the result, ornull
if none or not yet determined. This field is never set iffailOnException
istrue
. -
parallel
private final boolean parallelWhether parallel execution is authorized for the ImageAdapter.source image. Iftrue
, thenRenderedImage.getTile(int, int)
implementation should be concurrent. -
failOnException
private final boolean failOnExceptionWhether errors occurring during computation should be propagated instead of wrapped in aLogRecord
.
-
-
Constructor Details
-
AnnotatedImage
protected AnnotatedImage(RenderedImage source, Shape areaOfInterest, boolean parallel, boolean failOnException) Creates a new annotated image wrapping the given image. The annotations are the additional properties computed by the subclass.- Parameters:
source
- the image to wrap for adding properties (annotations).areaOfInterest
- pixel coordinates of AOI, ornull
for the whole image.parallel
- whether parallel execution is authorized.failOnException
- whether errors occurring during computation should be propagated.
-
-
Method Details
-
getExtraParameter
Object[] getExtraParameter()Returns an optional parameter specific to subclass. This is used for caching purpose and forequals(Object)
andhashCode()
method implementations only, i.e. for distinguishing between twoAnnotatedImage
instances that are identical except for subclass-defined parameters.API note: the return value is an array because there is typically one parameter value per band. This method will not modify the returned array.- Returns:
- subclass specific extra parameter, or
null
if none.
-
unique
If the source image is the same operation for the same area of interest, returns that source. Otherwise returnsthis
or a previous instance doing the same operation thanthis
.- See Also:
-
getCacheKey
Returns the key to use for entries in thecache
map.- Parameters:
property
- value ofgetPropertyNames()
.
-
getComputedPropertyName
Returns the name of the property which is computed by this image.- Returns:
- name of property computed by this image. Shall not be null.
-
getPropertyNames
Returns an array of names recognized bygetProperty(String)
. The default implementation returns the ImageAdapter.source properties names followed bygetComputedPropertyName()
. If that property has already been computed and an error occurred, then the names returned by this method will include the property name with ".warnings" suffix.- Specified by:
getPropertyNames
in interfaceRenderedImage
- Overrides:
getPropertyNames
in classImageAdapter
- Returns:
- all recognized property names.
-
isErrorProperty
Returns whether the given name is the name of the error property. The implementation of this method avoids the creation of concatenated string.- Parameters:
cn
- name of the computed property.name
- the property name to test (may benull
).- Returns:
- whether
name
iscn
+ ".warnings".
-
getProperty
Gets a property from this image or from its source. If the given name is for the property to be computed by this class and if that property has not been computed before, then this method invokescomputeProperty()
and caches its result.- Specified by:
getProperty
in interfaceRenderedImage
- Overrides:
getProperty
in classImageAdapter
- Parameters:
name
- name of the property to get.- Returns:
- the property for the given name (
null
is a valid result), orImage.UndefinedProperty
if the given name is not a recognized property name.
-
logAndClearError
If an error occurred, logs the message with the specified class and method as the source. Theclasse
andmethod
arguments overwrite theLogRecord.getSourceClassName()
andLogRecord.getSourceMethodName()
values. The log record is cleared by this method call and will no longer be reported, unless the property is recomputed.Context of use
This method should be invoked only on images that are going to be disposed after the caller extracted the computed property value. This method should not be invoked on image accessible by the user, because clearing the error may be surprising.- Parameters:
classe
- the class to report as the source of the logging message.method
- the method to report as the source of the logging message.handler
- where to send the log message.
-
computeProperty
Invoked when the property needs to be computed. If the property cannot be computed, then the result will benull
and the exception thrown by this method will be wrapped in a property of the same name with the ".warnings" suffix.The default implementation makes the following choice:
- If
parallel
istrue
,collector()
returns a non-null value and the area of interest covers at least two tiles, then this method distributes calculation on many threads using the functions provided by the collector. Seecollector()
Javadoc for more information. - Otherwise this method delegates to
computeSequentially()
.
- Returns:
- the computed property value. Note that
null
is a valid result. - Throws:
Exception
- if an error occurred while computing the property.
- If
-
computeSequentially
Invoked when the property needs to be computed sequentially (all computations in current thread). If the property cannot be computed, then the result will benull
and the exception thrown by this method will be wrapped in a property of the same name with the ".warnings" suffix.This method is invoked when this class does not support parallel execution (
collector()
returnednull
), or when it is not worth to parallelize (image has only one tile), or when the ImageAdapter.source image may be non-thread safe (parallel
isfalse
).- Returns:
- the computed property value. Note that
null
is a valid result. - Throws:
Exception
- if an error occurred while computing the property.
-
collector
Returns the function to execute for computing the property value, together with other required functions (supplier of accumulator, combiner, finisher). Those functions allow multi-threaded property calculation. This collector is used in a way similar toStream.collect(Collector)
. A typical approach is two define 3 private methods in the subclass as below (where P is the type of the property to compute):- Returns:
- functions for multi-threaded computation of property value, or
null
if unsupported.
-
cloneProperty
Invoked when a property of the given name has been requested and that property is cached. If the property is mutable, subclasses may want to clone it before to return it to users. The default implementation returnsvalue
unchanged.- Parameters:
name
- the property name.value
- the property value (nevernull
).- Returns:
- the property value to give to user.
-
appendStringContent
Appends the name of the computed property in theImageAdapter.toString()
representation, after the class name and before the string representation of the wrapped image.- Specified by:
appendStringContent
in classImageAdapter
- Parameters:
buffer
- where to start writing content ofImageAdapter.toString()
representation.- Returns:
- name of the class to show in the
ImageAdapter.toString()
representation.
-
hashCode
public final int hashCode()Returns a hash code value for this image. This method should be quick; it should not compute the hash code from sample values.- Overrides:
hashCode
in classImageAdapter
- Returns:
- a hash code value based on a description of the operation performed by this image.
-
equals
Compares the given object with this image for equality. This method should be quick and compare how images compute their values from their sources; it should not compare the actual pixel values.Requirements for subclasses
Subclasses should overridegetExtraParameter()
instead of this method.- Overrides:
equals
in classImageAdapter
- Parameters:
object
- the object to compare with this image.- Returns:
true
if the given object is an image performing the same calculation than this image.- See Also:
-
equalParameters
Returnstrue
if the area of interest and some other fields are equal. TheboundsOfInterest
is omitted because it is derived fromareaOfInterest
. Theerrors
is omitted because it is part of computation results.
-