/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.master.journal;

import alluxio.Constants;
import alluxio.proto.journal.Journal.JournalEntry;

import com.google.protobuf.CodedInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Reads and writes protocol buffer journal entries. The entries contain headers describing their
 * length. This framing is handled entirely by {@link JournalEntry#writeDelimitedTo(OutputStream)}
 * and {@link JournalEntry#parseDelimitedFrom(InputStream)}. This class is thread-safe.
 */
@ThreadSafe
public final class ProtoBufJournalFormatter implements JournalFormatter {
  private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);

  /**
   * Constructs a new {@link ProtoBufJournalFormatter}.
   */
  public ProtoBufJournalFormatter() {}

  @Override
  public void serialize(JournalEntry entry, OutputStream outputStream) throws IOException {
    entry.writeDelimitedTo(outputStream);
  }

  @Override
  public JournalInputStream deserialize(final InputStream inputStream) throws IOException {
    return new JournalInputStream() {
      private final byte[] mBuffer = new byte[1024];
      private long mLatestSequenceNumber;

      @Override
      public JournalEntry getNextEntry() throws IOException {
        int firstByte = inputStream.read();
        if (firstByte == -1) {
          return null;
        }
        // All journal entries start with their size in bytes written as a varint.
        int size = CodedInputStream.readRawVarint32(firstByte, inputStream);
        byte[] buffer = size <= mBuffer.length ? mBuffer : new byte[size];
        // Total bytes read so far for journal entry
        int bytes = 0;
        // Bytes read in last read request
        int bytesRead = 0;
        while (bytes < size) {
          bytesRead = inputStream.read(buffer, bytesRead, size - bytesRead);
          if (bytesRead < 0) {
            break;
          }
          bytes += bytesRead;
        }
        if (bytes < size) {
          LOG.warn("Journal entry was truncated. Expected to read " + size + " bytes but only got "
              + bytes);
          return null;
        }

        JournalEntry entry = JournalEntry.parseFrom(new ByteArrayInputStream(buffer, 0, size));
        if (entry != null) {
          mLatestSequenceNumber = entry.getSequenceNumber();
        }
        return entry;
      }

      @Override
      public void close() throws IOException {
        inputStream.close();
      }

      @Override
      public long getLatestSequenceNumber() {
        return mLatestSequenceNumber;
      }
    };
  }
}

@@ -2326,16 +2326,17 @@
 al entry
+.
 %0A       
@@ -2344,19 +2344,70 @@
 int 
-bytes = 0;%0A
+totalBytesRead = 0;%0A        while (totalBytesRead %3C size) %7B%0A  
     
@@ -2444,17 +2444,20 @@
  request
-%0A
+.%0A  
         
@@ -2464,65 +2464,15 @@
 int 
-bytesRead = 0;%0A        while (bytes %3C size) %7B%0A          b
+latestB
 ytes
@@ -2503,17 +2503,22 @@
 buffer, 
-b
+totalB
 ytesRead
@@ -2526,17 +2526,22 @@
  size - 
-b
+totalB
 ytesRead
@@ -2553,25 +2553,31 @@
         if (
-b
+latestB
 ytesRead %3C 0
@@ -2625,18 +2625,33 @@
     
-bytes += b
+totalBytesRead += latestB
 ytes
@@ -2678,21 +2678,30 @@
     if (
-bytes
+totalBytesRead
  %3C size)
@@ -2819,21 +2819,30 @@
       + 
-bytes
+totalBytesRead
 );%0A     

Address comments