<commit_before>/*
 * Copyright 2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.kuujo.copycat.internal;

import net.kuujo.copycat.*;
import net.kuujo.copycat.cluster.Cluster;
import net.kuujo.copycat.util.serializer.Serializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Default state machine implementation.
 *
 * @author <a href="http://github.com/kuujo"><NAME></a>
 */
public class DefaultStateMachine<T> implements StateMachine<T> {
  private final Serializer serializer = Serializer.serializer();
  private final Class<T> stateType;
  private T state;
  private final StateLog<List<Object>> log;
  private final InvocationHandler handler = new StateProxyInvocationHandler();
  private Map<String, Object> data = new HashMap<>(1024);
  private final StateContext<T> context = new StateContext<T>() {
    @Override
    public T state() {
      return state;
    }

    @Override
    public StateContext<T> put(String key, Object value) {
      data.put(key, value);
      return this;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <U> U get(String key) {
      return (U) data.get(key);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <U> U remove(String key) {
      return (U) data.remove(key);
    }

    @Override
    public StateContext<T> clear() {
      data.clear();
      return this;
    }

    @Override
    public StateContext<T> transition(T state) {
      DefaultStateMachine.this.state = state;
      return this;
    }
  };

  public DefaultStateMachine(Class<T> stateType, T state, StateLog<List<Object>> log) {
    if (!stateType.isInterface()) {
      throw new IllegalArgumentException("State type must be an interface");
    }
    this.stateType = stateType;
    this.state = state;
    this.log = log;
    registerCommands();
  }

  @Override
  public String name() {
    return log.name();
  }

  @Override
  public Cluster cluster() {
    return log.cluster();
  }

  @Override
  public CopycatState state() {
    return log.state();
  }

  @Override
  @SuppressWarnings("unchecked")
  public <U> U createProxy(Class<U> type) {
    return (U) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{type}, handler);
  }

  @Override
  public <U> CompletableFuture<U> submit(String command, Object... args) {
    return log.submit(command, Arrays.asList(args));
  }

  /**
   * Takes a snapshot of the state machine state.
   */
  private ByteBuffer snapshot() {
    return serializer.writeObject(data);
  }

  /**
   * Installs a snapshot of the state machine state.
   */
  private void install(ByteBuffer snapshot) {
    data = serializer.readObject(snapshot);
  }

  @Override
  public CompletableFuture<Void> open() {
    return log.open().whenComplete((result, error) -> {
      if (error == null) {
        log.snapshotter(this::snapshot);
      }
    });
  }

  @Override
  public CompletableFuture<Void> close() {
    return log.close().whenComplete((result, error) -> {
      log.installer(this::install);
    });
  }

  @Override
  public CompletableFuture<Void> delete() {
    return log.delete();
  }

  /**
   * Registers commands on the state log.
   */
  private void registerCommands() {
    for (Method method : stateType.getMethods()) {
      CommandInfo info = method.getAnnotation(CommandInfo.class);
      if (info == null) {
        log.register(method.getName(), createCommand(method));<commit_msg>Set snapshot installer in StateMachine.open.<commit_after>/*
 * Copyright 2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.kuujo.copycat.internal;

import net.kuujo.copycat.*;
import net.kuujo.copycat.cluster.Cluster;
import net.kuujo.copycat.util.serializer.Serializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Default state machine implementation.
 *
 * @author <a href="http://github.com/kuujo"><NAME></a>
 */
public class DefaultStateMachine<T> implements StateMachine<T> {
  private final Serializer serializer = Serializer.serializer();
  private final Class<T> stateType;
  private T state;
  private final StateLog<List<Object>> log;
  private final InvocationHandler handler = new StateProxyInvocationHandler();
  private Map<String, Object> data = new HashMap<>(1024);
  private final StateContext<T> context = new StateContext<T>() {
    @Override
    public T state() {
      return state;
    }

    @Override
    public StateContext<T> put(String key, Object value) {
      data.put(key, value);
      return this;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <U> U get(String key) {
      return (U) data.get(key);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <U> U remove(String key) {
      return (U) data.remove(key);
    }

    @Override
    public StateContext<T> clear() {
      data.clear();
      return this;
    }

    @Override
    public StateContext<T> transition(T state) {
      DefaultStateMachine.this.state = state;
      return this;
    }
  };

  public DefaultStateMachine(Class<T> stateType, T state, StateLog<List<Object>> log) {
    if (!stateType.isInterface()) {
      throw new IllegalArgumentException("State type must be an interface");
    }
    this.stateType = stateType;
    this.state = state;
    this.log = log;
    registerCommands();
  }

  @Override
  public String name() {
    return log.name();
  }

  @Override
  public Cluster cluster() {
    return log.cluster();
  }

  @Override
  public CopycatState state() {
    return log.state();
  }

  @Override
  @SuppressWarnings("unchecked")
  public <U> U createProxy(Class<U> type) {
    return (U) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{type}, handler);
  }

  @Override
  public <U> CompletableFuture<U> submit(String command, Object... args) {
    return log.submit(command, Arrays.asList(args));
  }

  /**
   * Takes a snapshot of the state machine state.
   */
  private ByteBuffer snapshot() {
    return serializer.writeObject(data);
  }

  /**
   * Installs a snapshot of the state machine state.
   */
  private void install(ByteBuffer snapshot) {
    data = serializer.readObject(snapshot);
  }

  @Override
  public CompletableFuture<Void> open() {
    return log.open().whenComplete((result, error) -> {
      if (error == null) {
        log.snapshotter(this::snapshot);
        log.installer(this::install);
      }
    });
  }

  @Override
  public CompletableFuture<Void> close() {
    return log.close().whenComplete((result, error) -> {
      log.snapshotter(null);
      log.installer(null);
    });
  }

  @Override
  public CompletableFuture<Void> delete() {
    return log.delete();
  }

  /**
   * Registers commands on the state log.
   */
  private void registerCommands() {
    for (Method method : stateType.getMethods()) {
      CommandInfo info = method.getAnnotation(CommandInfo.class);
      if (info == null) {
        log.register(method.getName(), createCommand(method));
{'fraction_non_alphanumeric': 0.11823577330385197, 'fraction_numerical': 0.002792971022925637, 'mean_word_length': 3.441343669250646, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 61, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6037785', 'n_tokens_mistral': 2537, 'n_tokens_neox': 2522, 'n_words': 709}