Class MockProcessorContext
- All Implemented Interfaces:
org.apache.kafka.streams.processor.internals.RecordCollector.Supplier,ProcessorContext
MockProcessorContext is a mock of ProcessorContext for users to test their
ValueTransformer implementations.
The tests for this class (org.apache.kafka.streams.MockProcessorContextTest) include several behavioral tests that serve as example usage.
Note that this class does not take any automated actions (such as firing scheduled punctuators). It simply captures any data it witnesses.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classDeprecated.static classDeprecated.MockProcessorContext.CapturedPunctuatorholds captured punctuators, along with their scheduling information. -
Constructor Summary
ConstructorsConstructorDescriptionDeprecated.MockProcessorContext(Properties config) Deprecated.MockProcessorContext(Properties config, TaskId taskId, File stateDir) Deprecated.Create aMockProcessorContextwith a specified taskId and null stateDir. -
Method Summary
Modifier and TypeMethodDescriptionDeprecated.Return all the application config properties as key/value pairs.appConfigsWithPrefix(String prefix) Deprecated.Return all the application config properties with the given key prefix, as key/value pairs stripping the prefix.Deprecated.Return the application id.voidcommit()Deprecated.Request a commit.booleanDeprecated.WhetherProcessorContext.commit()has been called in this context.longDeprecated.Return the current stream-time in milliseconds.longDeprecated.Return the current system timestamp (also called wall-clock time) in milliseconds.<K,V> void forward(K key, V value) Deprecated.Forward a key/value pair to all downstream processors.<K,V> void Deprecated.Forward a key/value pair to the specified downstream processors.Deprecated.Get all the forwarded data this context has observed.Deprecated.Get all the forwarded data this context has observed for a specific child by name.<S extends StateStore>
SgetStateStore(String name) Deprecated.Get the state store given the store name.headers()Deprecated.Returns the headers of the current input record; could benullif it is not available.Serde<?> keySerde()Deprecated.Return the default key serde.metrics()Deprecated.Return Metrics instance.longoffset()Deprecated.Return the offset of the current input record; could be-1if it is not available.intDeprecated.Return the partition id of the current input record; could be-1if it is not available.org.apache.kafka.streams.processor.internals.RecordCollectorDeprecated.voidregister(StateStore store, StateRestoreCallback stateRestoreCallbackIsIgnoredInMock) Deprecated.Register and possibly restores the specified storage engine.voidDeprecated.Reset the commit capture tofalse(whether or not it was previouslytrue).voidDeprecated.Clear the captured forwarded data.schedule(Duration interval, PunctuationType type, Punctuator callback) Deprecated.Schedule a periodic operation for processors.Deprecated.Get the punctuators scheduled so far.voidsetCurrentStreamTimeMs(long currentStreamTimeMs) Deprecated.voidsetCurrentSystemTimeMs(long currentSystemTimeMs) Deprecated.voidsetHeaders(Headers headers) Deprecated.The context exposes this metadata for use in the processor.voidsetOffset(long offset) Deprecated.The context exposes this metadata for use in the processor.voidsetPartition(int partition) Deprecated.The context exposes this metadata for use in the processor.voidsetRecordMetadata(String topic, int partition, long offset, Headers headers, long timestamp) Deprecated.The context exposes these metadata for use in the processor.voidsetRecordTimestamp(long recordTimestamp) Deprecated.The context exposes this metadata for use in the processor.voidDeprecated.The context exposes this metadata for use in the processor.stateDir()Deprecated.Return the state directory for the partition.taskId()Deprecated.Return the task id.longDeprecated.Return the current timestamp.topic()Deprecated.Return the topic name of the current input record; could benullif it is not available.Serde<?> Deprecated.Return the default value serde.
-
Constructor Details
-
MockProcessorContext
public MockProcessorContext()Deprecated.Create aMockProcessorContextwith dummyconfigandtaskIdandnullstateDir. Most unit tests using this mock won't need to know the taskId, and most unit tests should be able to get by with theInMemoryKeyValueStore, so the stateDir won't matter. -
MockProcessorContext
Deprecated.Create aMockProcessorContextwith dummytaskIdandnullstateDir. Most unit tests using this mock won't need to know the taskId, and most unit tests should be able to get by with theInMemoryKeyValueStore, so the stateDir won't matter.- Parameters:
config- a Properties object, used to configure the context and the processor.
-
MockProcessorContext
Deprecated.Create aMockProcessorContextwith a specified taskId and null stateDir.- Parameters:
config- aPropertiesobject, used to configure the context and the processor.taskId- aTaskId, which the context makes available viataskId().stateDir- aFile, which the context makes available viwstateDir().
-
-
Method Details
-
applicationId
Deprecated.Description copied from interface:ProcessorContextReturn the application id.- Specified by:
applicationIdin interfaceProcessorContext- Returns:
- the application id
-
taskId
Deprecated.Description copied from interface:ProcessorContextReturn the task id.- Specified by:
taskIdin interfaceProcessorContext- Returns:
- the task id
-
appConfigs
Deprecated.Description copied from interface:ProcessorContextReturn all the application config properties as key/value pairs.The config properties are defined in the
StreamsConfigobject and associated to the ProcessorContext.The type of the values is dependent on the
typeof the property (e.g. the value ofDEFAULT_KEY_SERDE_CLASS_CONFIGwill be of typeClass, even if it was specified as a String toStreamsConfig(Map)).- Specified by:
appConfigsin interfaceProcessorContext- Returns:
- all the key/values from the StreamsConfig properties
-
appConfigsWithPrefix
Deprecated.Description copied from interface:ProcessorContextReturn all the application config properties with the given key prefix, as key/value pairs stripping the prefix.The config properties are defined in the
StreamsConfigobject and associated to the ProcessorContext.- Specified by:
appConfigsWithPrefixin interfaceProcessorContext- Parameters:
prefix- the properties prefix- Returns:
- the key/values matching the given prefix from the StreamsConfig properties.
-
currentSystemTimeMs
public long currentSystemTimeMs()Deprecated.Description copied from interface:ProcessorContextReturn the current system timestamp (also called wall-clock time) in milliseconds.Note: this method returns the internally cached system timestamp from the Kafka Stream runtime. Thus, it may return a different value compared to
System.currentTimeMillis().- Specified by:
currentSystemTimeMsin interfaceProcessorContext- Returns:
- the current system timestamp in milliseconds
-
currentStreamTimeMs
public long currentStreamTimeMs()Deprecated.Description copied from interface:ProcessorContextReturn the current stream-time in milliseconds.Stream-time is the maximum observed
record timestampso far (including the currently processed record), i.e., it can be considered a high-watermark. Stream-time is tracked on a per-task basis and is preserved across restarts and during task migration.Note: this method is not supported for global processors (cf.
Topology.addGlobalStore(...)andStreamsBuilder.addGlobalStore(...)), because there is no concept of stream-time for this case. Calling this method in a global processor will result in anUnsupportedOperationException.- Specified by:
currentStreamTimeMsin interfaceProcessorContext- Returns:
- the current stream-time in milliseconds
-
keySerde
Deprecated.Description copied from interface:ProcessorContextReturn the default key serde.- Specified by:
keySerdein interfaceProcessorContext- Returns:
- the key serializer
-
valueSerde
Deprecated.Description copied from interface:ProcessorContextReturn the default value serde.- Specified by:
valueSerdein interfaceProcessorContext- Returns:
- the value serializer
-
stateDir
Deprecated.Description copied from interface:ProcessorContextReturn the state directory for the partition.- Specified by:
stateDirin interfaceProcessorContext- Returns:
- the state directory
-
metrics
Deprecated.Description copied from interface:ProcessorContextReturn Metrics instance.- Specified by:
metricsin interfaceProcessorContext- Returns:
- StreamsMetrics
-
setRecordMetadata
public void setRecordMetadata(String topic, int partition, long offset, Headers headers, long timestamp) Deprecated.The context exposes these metadata for use in the processor. Normally, they are set by the Kafka Streams framework, but for the purpose of driving unit tests, you can set them directly.- Parameters:
topic- A topic namepartition- A partition numberoffset- A record offsettimestamp- A record timestamp
-
setTopic
Deprecated.The context exposes this metadata for use in the processor. Normally, they are set by the Kafka Streams framework, but for the purpose of driving unit tests, you can set it directly. Setting this attribute doesn't affect the others.- Parameters:
topic- A topic name
-
setPartition
public void setPartition(int partition) Deprecated.The context exposes this metadata for use in the processor. Normally, they are set by the Kafka Streams framework, but for the purpose of driving unit tests, you can set it directly. Setting this attribute doesn't affect the others.- Parameters:
partition- A partition number
-
setOffset
public void setOffset(long offset) Deprecated.The context exposes this metadata for use in the processor. Normally, they are set by the Kafka Streams framework, but for the purpose of driving unit tests, you can set it directly. Setting this attribute doesn't affect the others.- Parameters:
offset- A record offset
-
setHeaders
Deprecated.The context exposes this metadata for use in the processor. Normally, they are set by the Kafka Streams framework, but for the purpose of driving unit tests, you can set it directly. Setting this attribute doesn't affect the others.- Parameters:
headers- Record headers
-
setRecordTimestamp
public void setRecordTimestamp(long recordTimestamp) Deprecated.The context exposes this metadata for use in the processor. Normally, they are set by the Kafka Streams framework, but for the purpose of driving unit tests, you can set it directly. Setting this attribute doesn't affect the others.- Parameters:
recordTimestamp- A record timestamp
-
setCurrentSystemTimeMs
public void setCurrentSystemTimeMs(long currentSystemTimeMs) Deprecated. -
setCurrentStreamTimeMs
public void setCurrentStreamTimeMs(long currentStreamTimeMs) Deprecated. -
topic
Deprecated.Description copied from interface:ProcessorContextReturn the topic name of the current input record; could benullif it is not available.For example, if this method is invoked within a
punctuation callback, or while processing a record that was forwarded by a punctuation callback, the record won't have an associated topic. Another example isKTable.transformValues(ValueTransformerWithKeySupplier, String...)(and siblings), that do not always guarantee to provide a valid topic name, as they might be executed "out-of-band" due to some internal optimizations applied by the Kafka Streams DSL.- Specified by:
topicin interfaceProcessorContext- Returns:
- the topic name
-
partition
public int partition()Deprecated.Description copied from interface:ProcessorContextReturn the partition id of the current input record; could be-1if it is not available.For example, if this method is invoked within a
punctuation callback, or while processing a record that was forwarded by a punctuation callback, the record won't have an associated partition id. Another example isKTable.transformValues(ValueTransformerWithKeySupplier, String...)(and siblings), that do not always guarantee to provide a valid partition id, as they might be executed "out-of-band" due to some internal optimizations applied by the Kafka Streams DSL.- Specified by:
partitionin interfaceProcessorContext- Returns:
- the partition id
-
offset
public long offset()Deprecated.Description copied from interface:ProcessorContextReturn the offset of the current input record; could be-1if it is not available.For example, if this method is invoked within a
punctuation callback, or while processing a record that was forwarded by a punctuation callback, the record won't have an associated offset. Another example isKTable.transformValues(ValueTransformerWithKeySupplier, String...)(and siblings), that do not always guarantee to provide a valid offset, as they might be executed "out-of-band" due to some internal optimizations applied by the Kafka Streams DSL.- Specified by:
offsetin interfaceProcessorContext- Returns:
- the offset
-
headers
Deprecated.Returns the headers of the current input record; could benullif it is not available.Note, that headers should never be
nullin the actual Kafka Streams runtime, even if they could be empty. However, this mock does not guarantee non-nullheaders. Thus, you either need to add anullcheck to your production code to use this mock for testing, or you always need to set headers manually viasetHeaders(Headers)to avoid aNullPointerExceptionfrom yourValueTransformerimplementation.- Specified by:
headersin interfaceProcessorContext- Returns:
- the headers
-
timestamp
public long timestamp()Deprecated.Description copied from interface:ProcessorContextReturn the current timestamp.If it is triggered while processing a record streamed from the source processor, timestamp is defined as the timestamp of the current input record; the timestamp is extracted from
ConsumerRecordbyTimestampExtractor. Note, that an upstreamProcessormight have set a new timestamp by callingProcessorContext.forward(org.apache.kafka.streams.processor.api.Record). In particular, some Kafka Streams DSL operators set result record timestamps explicitly, to guarantee deterministic results.If it is triggered while processing a record generated not from the source processor (for example, if this method is invoked from the punctuate call), timestamp is defined as the current task's stream time, which is defined as the largest timestamp of any record processed by the task.
- Specified by:
timestampin interfaceProcessorContext- Returns:
- the timestamp
-
register
Deprecated.Description copied from interface:ProcessorContextRegister and possibly restores the specified storage engine.- Specified by:
registerin interfaceProcessorContext- Parameters:
store- the storage enginestateRestoreCallbackIsIgnoredInMock- the restoration callback logic for log-backed state stores upon restart
-
getStateStore
Deprecated.Description copied from interface:ProcessorContextGet the state store given the store name.The returned state store represent one shard of the overall state, which belongs to the current task. The returned shard of the state store may only be used by the current
Transformer,ValueTransformer, orValueTransformerWithKeyinstance. Sharing a shard across different transformers (ie, from different "sibling" tasks; same sub-topology but different partition) may lead to data corruption and/or data loss.- Specified by:
getStateStorein interfaceProcessorContext- Type Parameters:
S- The type or interface of the store to return- Parameters:
name- The store name- Returns:
- The state store instance
-
schedule
public Cancellable schedule(Duration interval, PunctuationType type, Punctuator callback) throws IllegalArgumentException Deprecated.Description copied from interface:ProcessorContextSchedule a periodic operation for processors. A processor may call this method during aKTable.transformValues(ValueTransformerWithKeySupplier, String...)'sinitializationorprocessingto schedule a periodic callback — called a punctuation — toPunctuator.punctuate(long). The type parameter controls what notion of time is used for punctuation:PunctuationType.STREAM_TIME— uses "stream time", which is advanced by the processing of messages in accordance with the timestamp as extracted by theTimestampExtractorin use. The first punctuation will be triggered by the first record that is processed. NOTE: Only advanced if messages arrivePunctuationType.WALL_CLOCK_TIME— uses system time (the wall-clock time), which is advanced independent of whether new messages arrive. The first punctuation will be triggered after interval has elapsed. NOTE: This is best effort only as its granularity is limited by how long an iteration of the processing loop takes to complete
- with
PunctuationType.STREAM_TIME, when stream time advances more than interval - with
PunctuationType.WALL_CLOCK_TIME, on GC pause, too short interval, ...
- Specified by:
schedulein interfaceProcessorContext- Parameters:
interval- the time interval between punctuations (supported minimum is 1 millisecond)type- one of:PunctuationType.STREAM_TIME,PunctuationType.WALL_CLOCK_TIMEcallback- a function consuming timestamps representing the current stream or system time- Returns:
- a handle allowing cancellation of the punctuation schedule established by this method
- Throws:
IllegalArgumentException- if the interval is not representable in milliseconds
-
scheduledPunctuators
Deprecated.Get the punctuators scheduled so far. The returned list is not affected by subsequent calls toschedule(...).- Returns:
- A list of captured punctuators.
-
forward
public <K,V> void forward(K key, V value) Deprecated.Description copied from interface:ProcessorContextForward a key/value pair to all downstream processors. Used the input record's timestamp as timestamp for the output record.If this method is called with
Punctuator.punctuate(long)the record that is sent downstream won't have any associated record metadata like topic, partition, or offset.- Specified by:
forwardin interfaceProcessorContext- Parameters:
key- keyvalue- value
-
forward
Deprecated.Description copied from interface:ProcessorContextForward a key/value pair to the specified downstream processors. Can be used to set the timestamp of the output record.If this method is called with
Punctuator.punctuate(long)the record that is sent downstream won't have any associated record metadata like topic, partition, or offset.- Specified by:
forwardin interfaceProcessorContext- Parameters:
key- keyvalue- valueto- the options to use when forwarding
-
forwarded
Deprecated.Get all the forwarded data this context has observed. The returned list will not be affected by subsequent interactions with the context. The data in the list is in the same order as the calls toforward(...).- Returns:
- A list of key/value pairs that were previously passed to the context.
-
forwarded
Deprecated.Get all the forwarded data this context has observed for a specific child by name. The returned list will not be affected by subsequent interactions with the context. The data in the list is in the same order as the calls toforward(...).- Parameters:
childName- The child name to retrieve forwards for- Returns:
- A list of key/value pairs that were previously passed to the context.
-
resetForwards
public void resetForwards()Deprecated.Clear the captured forwarded data. -
commit
public void commit()Deprecated.Description copied from interface:ProcessorContextRequest a commit.- Specified by:
commitin interfaceProcessorContext
-
committed
public boolean committed()Deprecated.WhetherProcessorContext.commit()has been called in this context.- Returns:
trueiffProcessorContext.commit()has been called in this context since construction or reset.
-
resetCommit
public void resetCommit()Deprecated.Reset the commit capture tofalse(whether or not it was previouslytrue). -
recordCollector
public org.apache.kafka.streams.processor.internals.RecordCollector recordCollector()Deprecated.- Specified by:
recordCollectorin interfaceorg.apache.kafka.streams.processor.internals.RecordCollector.Supplier
-
MockProcessorContextinstead.