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 classKeys in thecachewhenareaOfInterestis non-null. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final ShapePixel coordinates of the region for which to compute the values, ornullfor the whole image.protected final RectangleBounds ofareaOfInterestintersected with image bounds, ornullfor 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.ReportThe errors that occurred while computing the result, ornullif none or not yet determined.private final booleanWhether errors occurring during computation should be propagated instead of wrapped in aLogRecord.private static final ObjectAn arbitrary value that we use for storingnullvalues in the cache.private final booleanWhether parallel execution is authorized for the ImageAdapter.source image.static final StringThe suffix to add to property name for errors that occurred during computation.Fields inherited from class org.apache.sis.image.ImageAdapter
sourceFields inherited from class org.apache.sis.image.PlanarImage
GRID_GEOMETRY_KEY, MASK_KEY, POSITIONAL_ACCURACY_KEY, SAMPLE_RESOLUTIONS_KEY, STATISTICS_KEY -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedAnnotatedImage(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 ObjectcloneProperty(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 ObjectInvoked when the property needs to be computed.protected abstract ObjectInvoked when the property needs to be computed sequentially (all computations in current thread).private booleanequalParameters(AnnotatedImage other) Returnstrueif the area of interest and some other fields are equal.final booleanCompares the given object with this image for equality.private ObjectgetCacheKey(String property) Returns the key to use for entries in thecachemap.protected abstract StringReturns the name of the property which is computed by this image.(package private) Object[]Returns an optional parameter specific to subclass.final ObjectgetProperty(String name) Gets a property from this image or from its source.String[]Returns an array of names recognized bygetProperty(String).final inthashCode()Returns a hash code value for this image.private static booleanisErrorProperty(String cn, String name) Returns whether the given name is the name of the error property.(package private) final voidlogAndClearError(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 RenderedImageunique()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, toStringMethods 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 andfailOnExceptionisfalse.- See Also:
-
NULL
An arbitrary value that we use for storingnullvalues in the cache. -
CACHE
Cache of properties already computed for images. That map shall contain computation results only, never theAnnotatedImageinstances that computed those results, as doing so would create memory leak (because of theImageAdapter.sourcereference preventing the key to be garbage-collected). All accesses to this cache shall be synchronized on theCACHEinstance.In current implementation we cache only the values that have been computed without warnings. We do that because otherwise, an
AnnotatedImagewithfailOnExceptionflag set could wrongly return a partially computed value if that value has been cached by another image instance with thefailOnExceptionflag 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 allAnnotatedImageinstances wrapping the same ImageAdapter.source image in order to avoid computing the same property many times if anAnnotatedImagewrapper is recreated many times for the same operation on the same image.Note that
nullis a valid result. SinceCachecannot store null values, those results are replaced byNULL.Keys are
Stringinstances containing directly the property name whenareaOfInterestandgetExtraParameter()arenull, orAnnotatedImage.CacheKeyinstances otherwise. -
areaOfInterest
Pixel coordinates of the region for which to compute the values, ornullfor 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
Shapeimplementation shall be thread-safe, assuming its state stay unmodified, unless theparallelargument specified to the constructor wasfalse.If
areaOfInterestisnull, thenboundsOfInterestis alwaysnull. However, the converse is not necessarily true. -
boundsOfInterest
Bounds ofareaOfInterestintersected with image bounds, ornullfor the whole image. If the area of interest fully contains those bounds, thenareaOfInterestis set to the same reference thanboundsOfInterest. Subclasses can useareaOfInterest == boundsOfInterestfor quickly testing if the area of interest is rectangular.If
areaOfInterestisnull, thenboundsOfInterestis alwaysnull. However, the converse is not necessarily true. -
errors
The errors that occurred while computing the result, ornullif none or not yet determined. This field is never set iffailOnExceptionistrue. -
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, ornullfor 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 twoAnnotatedImageinstances 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
nullif none.
-
unique
If the source image is the same operation for the same area of interest, returns that source. Otherwise returnsthisor a previous instance doing the same operation thanthis.- See Also:
-
getCacheKey
Returns the key to use for entries in thecachemap.- 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:
getPropertyNamesin interfaceRenderedImage- Overrides:
getPropertyNamesin 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
nameiscn+ ".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:
getPropertyin interfaceRenderedImage- Overrides:
getPropertyin classImageAdapter- Parameters:
name- name of the property to get.- Returns:
- the property for the given name (
nullis a valid result), orImage.UndefinedPropertyif 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. Theclasseandmethodarguments 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 benulland 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
parallelistrue,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
nullis 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 benulland 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 (parallelisfalse).- Returns:
- the computed property value. Note that
nullis 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
nullif 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 returnsvalueunchanged.- 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:
appendStringContentin 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:
hashCodein 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:
equalsin classImageAdapter- Parameters:
object- the object to compare with this image.- Returns:
trueif the given object is an image performing the same calculation than this image.- See Also:
-
equalParameters
Returnstrueif the area of interest and some other fields are equal. TheboundsOfInterestis omitted because it is derived fromareaOfInterest. Theerrorsis omitted because it is part of computation results.
-