Verifies that the block is associated with a file that has a lease.
Increments, logs and then returns the stamp

@param block block
@param fromNN if it is for lease recovery initiated by NameNode
@return a new generation stamp
354974
public long nextGenerationStampForBlock(Block block, boolean fromNN) throws IOException {
    writeLock();
    try {
      if (isInSafeMode()) {
        throw new SafeModeException("Cannot get nextGenStamp for " + block, safeMode);
      }
      Block blockWithWildcardGenstamp = new Block(block.getBlockId());
      BlockInfo storedBlock = blocksMap.getStoredBlock(blockWithWildcardGenstamp);
      if (storedBlock == null) {
        String msg = block + " is already commited, storedBlock == null.";
        LOG.info(msg);
        throw new BlockAlreadyCommittedException(msg);
      }
      INodeFile fileINode = storedBlock.getINode();
      if (!fileINode.isUnderConstruction()) {
        String msg = block + " is already commited, !fileINode.isUnderConstruction().";
        LOG.info(msg);
        throw new BlockAlreadyCommittedException(msg);
      }
      // Disallow client-initiated recovery once
      // NameNode initiated lease recovery starts
      String path = null;
      try {
        path = fileINode.getFullPathName();
      } catch (IOException ioe) {
        throw (BlockAlreadyCommittedException)
          new BlockAlreadyCommittedException(
              block + " is already deleted").initCause(ioe);
      }
      if (!fromNN && HdfsConstants.NN_RECOVERY_LEASEHOLDER.equals(
          leaseManager.getLeaseByPath(path).getHolder())) {
        String msg = block +
          "is being recovered by NameNode, ignoring the request from a client";
        LOG.info(msg);
        throw new IOException(msg);
      }
      if (!((INodeFileUnderConstruction) fileINode).setLastRecoveryTime(now())) {
        String msg = block + " is being recovered, ignoring this request.";
        LOG.info(msg);
        throw new IOException(msg);
      }
      return nextGenerationStamp();
    } finally {
      writeUnlock();
    }
  }
68679
public static BlockLocation[] locatedBlocks2Locations(LocatedBlocks blocks) {
    if (blocks == null) {
      return new BlockLocation[0];
    }
    int nrBlocks = blocks.locatedBlockCount();
    BlockLocation[] blkLocations = new BlockLocation[nrBlocks];
    if (nrBlocks == 0) {
      return blkLocations;
    }
    int idx = 0;
    for (LocatedBlock blk : blocks.getLocatedBlocks()) {
      assert idx < nrBlocks : "Incorrect index";
      DatanodeInfo[] locations = blk.getLocations();
      String[] hosts = new String[locations.length];
      String[] names = new String[locations.length];
      String[] racks = new String[locations.length];
      for (int hCnt = 0; hCnt < locations.length; hCnt++) {
        hosts[hCnt] = locations[hCnt].getHostName();
        names[hCnt] = locations[hCnt].getName();
        NodeBase node = new NodeBase(names[hCnt],
                                     locations[hCnt].getNetworkLocation());
        racks[hCnt] = node.toString();
      }
      blkLocations[idx] = new BlockLocation(names, hosts, racks,
                                            blk.getStartOffset(),
                                            blk.getBlockSize(),
                                            blk.isCorrupt());
      idx++;
    }
    return blkLocations;
  }
705631
private static Block convertBlock(TBlock tblk) {
    return new Block(tblk.getBlockId(), 
                     tblk.getNumBytes(),
                     tblk.getGenerationStamp());
  }
78157
boolean internalReleaseLeaseOne(Lease lease, String src,
        INodeFileUnderConstruction pendingFile, boolean discardLastBlock) throws IOException {
    // if it is safe to discard the last block, then do so
    if (discardLastBlock && discardDone(pendingFile, src)) {
      // Have client retry lease recovery.
      return false;
    }

    // Initialize lease recovery for pendingFile. If there are no blocks
    // associated with this file, then reap lease immediately. Otherwise
    // renew the lease and trigger lease recovery.
    if (pendingFile.getTargets() == null ||
      pendingFile.getTargets().length == 0) {
      if (pendingFile.getBlocks().length == 0) {
        finalizeINodeFileUnderConstruction(src, pendingFile);
        NameNode.stateChangeLog.warn("BLOCK*"
          + " internalReleaseLease: No blocks found, lease removed for " +  src);
        // Tell the client that lease recovery has succeeded.
        return true;
      }
      // setup the Inode.targets for the last block from the blocksMap
      //
      Block[] blocks = pendingFile.getBlocks();
      Block last = blocks[blocks.length - 1];
      DatanodeDescriptor[] targets =
        new DatanodeDescriptor[blocksMap.numNodes(last)];
      Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(last);
      for (int i = 0; it != null && it.hasNext(); i++) {
        targets[i] = it.next();
      }
      pendingFile.setTargets(targets, last.getGenerationStamp());
    }
    // start lease recovery of the last block for this file.
    pendingFile.assignPrimaryDatanode();
    Lease reassignedLease = reassignLease(
      lease, src, HdfsConstants.NN_RECOVERY_LEASEHOLDER, pendingFile
    );
    getEditLog().logOpenFile(src, pendingFile);
    leaseManager.renewLease(reassignedLease);
    return false;  // Have the client retry lease recovery.
  }
221605
void notifyNamenodeReceivedBlock(Block block, String delHint) {
    if (block==null) {
      throw new IllegalArgumentException("Block is null");
    }
    if (delHint != null && !delHint.isEmpty()) {
      block = new ReceivedBlockInfo(block, delHint);
    }
    synchronized (receivedAndDeletedBlockList) {
      receivedAndDeletedBlockList.add(block);
      pendingReceivedRequests++;
      if (!shouldBackoff) {
        receivedAndDeletedBlockList.notifyAll();
      }
    }
  }
1106213
public long newId() {
        for (; ; ) {
            Block block = this.block;
            long res = block.next();
            if (res != Long.MIN_VALUE) {
                return res;
            }

            synchronized (this) {
                if (block != this.block) {
                    // new block was assigned in the meantime
                    continue;
                }
                this.block = new Block(batchIdSupplier.newIdBatch(batchSize), validity);
            }
        }
    }
1025161
File getValidateBlockFile(int namespaceId, Block b, boolean checkSize)
      throws IOException {
    //Should we check for metadata file too?
    DatanodeBlockInfo blockInfo = this.getDatanodeBlockInfo(namespaceId, b);
    File f = null;
    if (blockInfo != null) {
      if (checkSize) {
        blockInfo.verifyFinalizedSize();
      }
      f = blockInfo.getBlockDataFile().getFile();
      assert f != null;

      if(f.exists()) {
        return f;
      }
   
      // if file is not null, but doesn't exist - possibly disk failed
      datanode.checkDiskError();
    }
    
    if (InterDatanodeProtocol.LOG.isDebugEnabled()) {
      InterDatanodeProtocol.LOG.debug("b=" + b + ", f=" + ((f == null) ? "null"
          : f));
    }
    return null;
  }
482191
BlocksWithLocations getBlocks(DatanodeID datanode, long size)
    throws IOException {
    readLock();
    try {
      checkSuperuserPrivilege();

      DatanodeDescriptor node = getDatanode(datanode);
      if (node == null) {
        NameNode.stateChangeLog.warn("BLOCK* NameSystem.getBlocks: "
          + "Asking for blocks from an unrecorded node " + datanode.getName());
        throw new IllegalArgumentException(
          "Unexpected exception.  Got getBlocks message for datanode " +
            datanode.getName() + ", but there is no info for it");
      }

      int numBlocks = node.numBlocks();
      if (numBlocks == 0) {
        return new BlocksWithLocations(new BlockWithLocations[0]);
      }
      Iterator<BlockInfo> iter = node.getBlockIterator();
      int startBlock = r.nextInt(numBlocks); // starting from a random block
      // skip blocks
      for (int i = 0; i < startBlock; i++) {
        iter.next();
      }
      List<BlockWithLocations> results = new ArrayList<BlockWithLocations>();
      long totalSize = 0;
      while (totalSize < size && iter.hasNext()) {
        totalSize += addBlock(iter.next(), results);
      }
      if (totalSize < size) {
        iter = node.getBlockIterator(); // start from the beginning
        for (int i = 0; i < startBlock && totalSize < size; i++) {
          totalSize += addBlock(iter.next(), results);
        }
      }

      return new BlocksWithLocations(
        results.toArray(new BlockWithLocations[results.size()]));
    } finally {
      readUnlock();
    }
  }
1032758
function BlockPacket(block, witness) {
  if (!(this instanceof BlockPacket))
    return new BlockPacket(block, witness);

  Packet.call(this);

  this.block = block || new MemBlock();
  this.witness = witness || false;
}
848086
def iterateBlocksBackFrom(block):
        
        count = 0
        while block.isValid() and count < MAX_SEARCH_OFFSET_LINES:
            yield block
            block = block.previous()
            count += 1
1189983
Block createNextBlock(@Nullable final Address to, final long version,
                          @Nullable TransactionOutPoint prevOut, final long time,
                          final byte[] pubKey, final Coin coinbaseValue,
                          final int height) {
        Block b = new Block(params, version);
        b.setDifficultyTarget(difficultyTarget);
        b.addCoinbaseTransaction(pubKey, coinbaseValue, height);

        if (to != null) {
            // Add a transaction paying 50 coins to the "to" address.
            Transaction t = new Transaction(params);
            t.addOutput(new TransactionOutput(params, t, FIFTY_COINS, to));
            // The input does not really need to be a valid signature, as long as it has the right general form.
            TransactionInput input;
            if (prevOut == null) {
                input = new TransactionInput(params, t, Script.createInputScript(EMPTY_BYTES, EMPTY_BYTES));
                // Importantly the outpoint hash cannot be zero as that's how we detect a coinbase transaction in isolation
                // but it must be unique to avoid 'different' transactions looking the same.
                byte[] counter = new byte[32];
                counter[0] = (byte) txCounter;
                counter[1] = (byte) (txCounter++ >> 8);
                input.getOutpoint().setHash(Sha256Hash.wrap(counter));
            } else {
                input = new TransactionInput(params, t, Script.createInputScript(EMPTY_BYTES, EMPTY_BYTES), prevOut);
            }
            t.addInput(input);
            b.addTransaction(t);
        }

        b.setPrevBlockHash(getHash());
        // Don't let timestamp go backwards
        if (getTimeSeconds() >= time)
            b.setTime(getTimeSeconds() + 1);
        else
            b.setTime(time);
        b.solve();
        try {
            b.verifyHeader();
        } catch (VerificationException e) {
            throw new RuntimeException(e); // Cannot happen.
        }
        if (b.getVersion() != version) {
            throw new RuntimeException();
        }
        return b;
    }
1233612
public static Block fromElementBlock(int positionCount, Optional<boolean[]> valueIsNull, int[] arrayOffset, Block values)
    {
        validateConstructorArguments(0, positionCount, valueIsNull.orElse(null), arrayOffset, values);
        // for performance reasons per element checks are only performed on the public construction
        for (int i = 0; i < positionCount; i++) {
            int offset = arrayOffset[i];
            int length = arrayOffset[i + 1] - offset;
            if (length < 0) {
                throw new IllegalArgumentException(format("Offset is not monotonically ascending. offsets[%s]=%s, offsets[%s]=%s", i, arrayOffset[i], i + 1, arrayOffset[i + 1]));
            }
            if (valueIsNull.isPresent() && valueIsNull.get()[i] && length != 0) {
                throw new IllegalArgumentException("A null array must have zero entries");
            }
        }
        return new ArrayBlock(0, positionCount, valueIsNull.orElse(null), arrayOffset, values);
    }
774137
static public int getBlockCrc(DataNode datanode, ReplicaToRead ri,
      int namespaceId, Block block) throws IOException {
    InputStream rawStreamIn = null;
    DataInputStream streamIn = null;
    try {
      int bytesPerCRC;
      int checksumSize;

      long crcPerBlock;

      rawStreamIn = BlockWithChecksumFileReader.getMetaDataInputStream(
          datanode.data, namespaceId, block);
      streamIn = new DataInputStream(new BufferedInputStream(rawStreamIn,
          FSConstants.BUFFER_SIZE));

      final BlockMetadataHeader header = BlockMetadataHeader
          .readHeader(streamIn);
      final DataChecksum checksum = header.getChecksum();
      if (checksum.getChecksumType() != DataChecksum.CHECKSUM_CRC32) {
        throw new IOException("File Checksum now is only supported for CRC32");
      }

      bytesPerCRC = checksum.getBytesPerChecksum();
      checksumSize = checksum.getChecksumSize();
      crcPerBlock = (((BlockWithChecksumFileReader.MetaDataInputStream) rawStreamIn)
          .getLength() - BlockMetadataHeader.getHeaderSize()) / checksumSize;

      int blockCrc = 0;
      byte[] buffer = new byte[checksumSize];
      for (int i = 0; i < crcPerBlock; i++) {
        IOUtils.readFully(streamIn, buffer, 0, buffer.length);
        int intChecksum = ((buffer[0] & 0xff) << 24)
            | ((buffer[1] & 0xff) << 16) | ((buffer[2] & 0xff) << 8)
            | ((buffer[3] & 0xff));

        if (i == 0) {
          blockCrc = intChecksum;
        } else {
          int chunkLength;
          if (i != crcPerBlock - 1 || ri.getBytesVisible() % bytesPerCRC == 0) {
            chunkLength = bytesPerCRC;
          } else {
            chunkLength = (int) ri.getBytesVisible() % bytesPerCRC;
          }
          blockCrc = CrcConcat.concatCrc(blockCrc, intChecksum, chunkLength);
        }
      }
      return blockCrc;
    } finally {
      if (streamIn != null) {
        IOUtils.closeStream(streamIn);
      }
      if (rawStreamIn != null) {
        IOUtils.closeStream(rawStreamIn);
      }
    }
  }
48225
function (blockName) {
            if (self.blockList.indexOf(blockName) > -1) {
                throw new Error('block<' + blockName + '> is already defined!');
            }
            self.blockList.push(blockName);
            return MARK.define(blockName);
        }
834741
public BasicBlock lookupBlockByLabel(int blockLabel) {
        for (Iterator<BasicBlock> i = blockIterator(); i.hasNext();) {
            BasicBlock basicBlock = i.next();
            if (basicBlock.getLabel() == blockLabel) {
                return basicBlock;
            }
        }
        return null;
    }
779479
public static Document getOwnerDocument(Node n) {
    return n == null || !isElement(n) ? null : n.getNodeType() == Node.DOCUMENT_NODE
        ? n.<Document> cast() : n.getOwnerDocument();
  }
445395
function getBlockIncreaseFromName(methodName) {
  const matchNumbers = String(methodName).match(/_increaseBlockBy(\d+)/);

  if (matchNumbers !== null
    && typeof matchNumbers[1] === 'string') {
    return parseInt(matchNumbers[1], 10);
  }

  return 0;
}