org.infinispan.counter.impl.function.BaseCreateFunction Maven / Gradle / Ivy
Show all versions of infinispan-clustered-counter Show documentation
package org.infinispan.counter.impl.function;
import java.util.function.Function;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.functional.EntryView;
/**
* A base function to update a counter, even if it doesn't exist.
*
* If the counter doesn't exist, it is created based on the configuration.
*
* @author Pedro Ruivo
* @since 9.2
*/
abstract class BaseCreateFunction implements
Function, R> {
final CounterConfiguration configuration;
BaseCreateFunction(CounterConfiguration configuration) {
this.configuration = configuration;
}
@Override
public final R apply(EntryView.ReadWriteEntryView entryView) {
return entryView.find().isPresent() ?
checkMetadataAndApply(entryView) :
createAndApply(entryView);
}
private R checkMetadataAndApply(EntryView.ReadWriteEntryView entryView) {
CounterConfigurationMetaParam metadata = entryView.findMetaParam(CounterConfigurationMetaParam.class)
.orElseGet(this::createMetadata);
return apply(entryView, entryView.get(), metadata);
}
private R createAndApply(EntryView.ReadWriteEntryView entryView) {
CounterValue value = CounterValue.newCounterValue(configuration);
return apply(entryView, value, createMetadata());
}
abstract R apply(EntryView.ReadWriteEntryView entryView, CounterValue currentValue,
CounterConfigurationMetaParam metadata);
private CounterConfigurationMetaParam createMetadata() {
return new CounterConfigurationMetaParam(configuration);
}
}