Code example for Checksum

Methods: getValue, reset, update

0
      final int length = buf.length;
      sum.update(b, off, length);
      writeChecksumChunk(b, off, length, false);
      return length;
    } 
     
    // copy user data to local buffer 
    int bytesToCopy = buf.length-count;
    bytesToCopy = (len<bytesToCopy) ? len : bytesToCopy;
    sum.update(b, off, bytesToCopy);
    System.arraycopy(b, off, buf, count, bytesToCopy);
    count += bytesToCopy;
    if (count == buf.length) {
      // local buffer is full 
      flushBuffer(); 
    }  
    return bytesToCopy;
  } 
 
  /* Forces any buffered output bytes to be checksumed and written out to 
   * the underlying output stream.  
   */ 
  protected synchronized void flushBuffer() throws IOException { 
    flushBuffer(false); 
  } 
 
  /* Forces any buffered output bytes to be checksumed and written out to 
   * the underlying output stream.  If keep is true, then the state of  
   * this object remains intact. 
   */ 
  protected synchronized void flushBuffer(boolean keep) throws IOException {
    if (count != 0) {
      int chunkLen = count;
      count = 0;
      writeChecksumChunk(buf, 0, chunkLen, keep);
      if (keep) {
        count = chunkLen;
      } 
    } 
  } 
   
  /** Generate checksum for the data chunk and output data chunk & checksum 
   * to the underlying output stream. If keep is true then keep the 
   * current checksum intact, do not reset it. 
   */ 
  private void writeChecksumChunk(byte b[], int off, int len, boolean keep)
  throws IOException { 
    int tempChecksum = (int)sum.getValue();
    if (!keep) {
      sum.reset();
    } 
    int2byte(tempChecksum, checksum);
    writeChunk(b, off, len, checksum);
  } 
 
  /** 
   * Converts a checksum integer value to a byte stream 
   */ 
  static public byte[] convertToByteStream(Checksum sum, int checksumSize) {
    return int2byte((int)sum.getValue(), new byte[checksumSize]);
  } 
 
  static byte[] int2byte(int integer, byte[] bytes) {
    bytes[0] = (byte)((integer >>> 24) & 0xFF);
    bytes[1] = (byte)((integer >>> 16) & 0xFF);
    bytes[2] = (byte)((integer >>>  8) & 0xFF);