All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.infinispan.counter.impl.function.InitializeCounterFunction Maven / Gradle / Ivy

The newest version!
package org.infinispan.counter.impl.function;

import static org.infinispan.counter.impl.entries.CounterValue.newCounterValue;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;

import org.infinispan.functional.EntryView;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;

/**
 * Function that initializes the {@link CounterValue} and {@link CounterConfigurationMetaParam} if they don't exists.
 *
 * @author Pedro Ruivo
 * @since 9.0
 */
public class InitializeCounterFunction implements
      Function, CounterValue> {

   public static final AdvancedExternalizer EXTERNALIZER = new Externalizer();
   private final CounterConfiguration counterConfiguration;

   public InitializeCounterFunction(CounterConfiguration counterConfiguration) {
      this.counterConfiguration = counterConfiguration;
   }

   @Override
   public CounterValue apply(EntryView.ReadWriteEntryView entryView) {
      Optional currentValue = entryView.find();
      if (currentValue.isPresent()) {
         return currentValue.get();
      }
      CounterValue newValue = newCounterValue(counterConfiguration);
      entryView.set(newValue, new CounterConfigurationMetaParam(counterConfiguration));
      return newValue;
   }

   @Override
   public String toString() {
      return "InitializeCounterFunction{" +
            "counterConfiguration=" + counterConfiguration +
            '}';
   }

   private static class Externalizer implements AdvancedExternalizer {

      @Override
      public void writeObject(ObjectOutput output, InitializeCounterFunction object) throws IOException {
         output.writeObject(object.counterConfiguration);
      }

      @Override
      public InitializeCounterFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
         return new InitializeCounterFunction<>((CounterConfiguration) input.readObject());
      }

      @Override
      public Set> getTypeClasses() {
         return Collections.singleton(InitializeCounterFunction.class);
      }

      @Override
      public Integer getId() {
         return ExternalizerIds.INITIALIZE_FUNCTION;
      }
   }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy