public void onAppendEntriesRequest(AppendEntriesRequest request) throws StateMachineException {

    handleLargerTerm(request.getTerm());

    if (request.getEntriesList().isEmpty()) {
      this.resetTimer();
    } else if (request.getTerm() < this.currentTerm) {
      this.communicator.sendTo(request.getLeaderId(), Messages.AppendEntriesResponse,
              newErrorAppendEntriesResponse().toByteArray());
    } else if (isLogEntryTermMisMatch(request)) {
      for (int i=this.getLastLogIndex(); i >= request.getPrevLogIndex(); --i) {
        entries.remove(i);
      }
      this.communicator.sendTo(request.getLeaderId(), Messages.AppendEntriesResponse,
              newErrorAppendEntriesResponse().toByteArray());
    } else {
      // Now append entries
      entries.addAll(request.getEntriesList());
      if (request.getLeaderCommitIndex() > this.commmitIndex) {
        this.commmitIndex = Math.min(request.getLeaderCommitIndex(), getLastLogIndex());
      }

      while (this.lastApplied < this.commmitIndex) {
        this.lastApplied++;
        this.stateMachine.commit(this.entries.get(this.lastApplied));
      }

      this.communicator.sendTo(request.getLeaderId(), Messages.AppendEntriesResponse,
              newSuccessAppendEntriesResponse().toByteArray());
    }
  }