Java Code Examples for org.apache.hadoop.hbase.util.Bytes#equals()

The following examples show how to use org.apache.hadoop.hbase.util.Bytes#equals() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: hbase   File: GroupingTableMap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract columns values from the current record. This method returns
 * null if any of the columns are not found.
 *
 * Override this method if you want to deal with nulls differently.
 *
 * @param r
 * @return array of byte values
 */
protected byte[][] extractKeyValues(Result r) {
  byte[][] keyVals = null;
  ArrayList<byte[]> foundList = new ArrayList<>();
  int numCols = columns.length;
  if (numCols > 0) {
    for (Cell value: r.listCells()) {
      byte [] column = CellUtil.makeColumn(CellUtil.cloneFamily(value),
          CellUtil.cloneQualifier(value));
      for (int i = 0; i < numCols; i++) {
        if (Bytes.equals(column, columns[i])) {
          foundList.add(CellUtil.cloneValue(value));
          break;
        }
      }
    }
    if(foundList.size() == numCols) {
      keyVals = foundList.toArray(new byte[numCols][]);
    }
  }
  return keyVals;
}
 
Example 2
Source Project: phoenix   File: IndexSplitTransaction.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Does checks on split inputs.
 * @return <code>true</code> if the region is splittable else
 * <code>false</code> if it is not (e.g. its already closed, etc.).
 */
public boolean prepare() {
  if (!this.parent.isSplittable()) return false;
  // Split key can be null if this region is unsplittable; i.e. has refs.
  if (this.splitrow == null) return false;
  HRegionInfo hri = this.parent.getRegionInfo();
  parent.prepareToSplit();
  // Check splitrow.
  byte [] startKey = hri.getStartKey();
  byte [] endKey = hri.getEndKey();
  if (Bytes.equals(startKey, splitrow) ||
      !this.parent.getRegionInfo().containsRow(splitrow)) {
    LOG.info("Split row is not inside region key range or is equal to " +
        "startkey: " + Bytes.toStringBinary(this.splitrow));
    return false;
  }
  long rid = getDaughterRegionIdTimestamp(hri);
  this.hri_a = new HRegionInfo(hri.getTable(), startKey, this.splitrow, false, rid);
  this.hri_b = new HRegionInfo(hri.getTable(), this.splitrow, endKey, false, rid);
  return true;
}
 
Example 3
Source Project: hbase   File: ZKLeaderManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Removes the leader znode, if it is currently claimed by this instance.
 */
public void stepDownAsLeader() {
  try {
    synchronized(lock) {
      if (!leaderExists.get()) {
        return;
      }
      byte[] leaderId = ZKUtil.getData(watcher, leaderZNode);
      if (leaderId != null && Bytes.equals(nodeId, leaderId)) {
        LOG.info("Stepping down as leader");
        ZKUtil.deleteNodeFailSilent(watcher, leaderZNode);
        leaderExists.set(false);
      } else {
        LOG.info("Not current leader, no need to step down");
      }
    }
  } catch (KeeperException ke) {
    watcher.abort("Unhandled zookeeper exception removing leader node", ke);
    candidate.stop("Unhandled zookeeper exception removing leader node: "
        + ke.getMessage());
  } catch (InterruptedException e) {
    watcher.abort("Unhandled zookeeper exception removing leader node", e);
    candidate.stop("Unhandled zookeeper exception removing leader node: "
        + e.getMessage());
  }
}
 
Example 4
Source Project: hbase   File: TestStatusResource.java    License: Apache License 2.0 6 votes vote down vote up
private static void validate(StorageClusterStatusModel model) {
  assertNotNull(model);
  assertTrue(model.getRegions() + ">= 1", model.getRegions() >= 1);
  assertTrue(model.getRequests() >= 0);
  assertTrue(model.getAverageLoad() >= 0.0);
  assertNotNull(model.getLiveNodes());
  assertNotNull(model.getDeadNodes());
  assertFalse(model.getLiveNodes().isEmpty());
  boolean foundMeta = false;
  for (StorageClusterStatusModel.Node node: model.getLiveNodes()) {
    assertNotNull(node.getName());
    assertTrue(node.getStartCode() > 0L);
    assertTrue(node.getRequests() >= 0);
    for (StorageClusterStatusModel.Node.Region region: node.getRegions()) {
      if (Bytes.equals(region.getName(), META_REGION_NAME)) {
        foundMeta = true;
      }
    }
  }
  assertTrue(foundMeta);
}
 
Example 5
private long getMaxSeqId(HRegionServer rs, RegionInfo region) throws IOException {
  Path walFile = ((AbstractFSWAL<?>) rs.getWAL(null)).getCurrentFileName();
  long maxSeqId = -1L;
  try (WAL.Reader reader =
    WALFactory.createReader(UTIL.getTestFileSystem(), walFile, UTIL.getConfiguration())) {
    for (;;) {
      WAL.Entry entry = reader.next();
      if (entry == null) {
        break;
      }
      if (Bytes.equals(region.getEncodedNameAsBytes(), entry.getKey().getEncodedRegionName())) {
        maxSeqId = Math.max(maxSeqId, entry.getKey().getSequenceId());
      }
    }
  }
  return maxSeqId;
}
 
Example 6
Source Project: hbase   File: FuzzyRowFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return true if and only if the fields of the filter that are serialized are equal to the
 *         corresponding fields in other. Used for testing.
 */
@Override
boolean areSerializedFieldsEqual(Filter o) {
  if (o == this) return true;
  if (!(o instanceof FuzzyRowFilter)) return false;

  FuzzyRowFilter other = (FuzzyRowFilter) o;
  if (this.fuzzyKeysData.size() != other.fuzzyKeysData.size()) return false;
  for (int i = 0; i < fuzzyKeysData.size(); ++i) {
    Pair<byte[], byte[]> thisData = this.fuzzyKeysData.get(i);
    Pair<byte[], byte[]> otherData = other.fuzzyKeysData.get(i);
    if (!(Bytes.equals(thisData.getFirst(), otherData.getFirst()) && Bytes.equals(
      thisData.getSecond(), otherData.getSecond()))) {
      return false;
    }
  }
  return true;
}
 
Example 7
private void verifyIndexColumns(final byte[][] requestedColumns, final IndexSpecification indexSpec) {
    if (requestedColumns == null) {
        return;
    }
    for (byte[] requestedColumn : requestedColumns) {
        boolean found = false;
        for (byte[] indexColumn : indexSpec.getAllColumns()) {
            if (Bytes.equals(requestedColumn, indexColumn)) {
                found = true;
                break;
            }
        }
        if (!found) {
            throw new RuntimeException("Column [" + Bytes.toString(requestedColumn) + "] not in index "
                    + indexSpec.getIndexId());
        }
    }
}
 
Example 8
private List<HRegionLocation> getRegionLocationsForReopen(
    List<HRegionLocation> tableRegionsForReopen) {

  List<HRegionLocation> regionsToReopen = new ArrayList<>();
  if (CollectionUtils.isNotEmpty(regionNames) &&
    CollectionUtils.isNotEmpty(tableRegionsForReopen)) {
    for (byte[] regionName : regionNames) {
      for (HRegionLocation hRegionLocation : tableRegionsForReopen) {
        if (Bytes.equals(regionName, hRegionLocation.getRegion().getRegionName())) {
          regionsToReopen.add(hRegionLocation);
          break;
        }
      }
    }
  } else {
    regionsToReopen = tableRegionsForReopen;
  }
  return regionsToReopen;
}
 
Example 9
/**
 * Finds if the start of the qualifier part of the Cell matches 'startsWith'
 *
 * COPIED from PrivateCellUtil.qualifierStartsWith()
 * @param left       the cell with which we need to match the qualifier
 * @param startsWith the serialized keyvalue format byte[]
 * @return true if the qualifier have same staring characters, false otherwise
 */
private static boolean qualifierStartsWith(final Cell left, final byte[] startsWith) {
  if (startsWith == null || startsWith.length == 0) {
    throw new IllegalArgumentException("Cannot pass an empty startsWith");
  }
  return Bytes
      .equals(left.getQualifierArray(), left.getQualifierOffset(), startsWith.length, startsWith,
          0, startsWith.length);
}
 
Example 10
Source Project: hbase   File: AccessController.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void preDisableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName)
    throws IOException {
  if (Bytes.equals(tableName.getName(), PermissionStorage.ACL_GLOBAL_NAME)) {
    // We have to unconditionally disallow disable of the ACL table when we are installed,
    // even if not enforcing authorizations. We are still allowing grants and revocations,
    // checking permissions and logging audit messages, etc. If the ACL table is not
    // available we will fail random actions all over the place.
    throw new AccessDeniedException("Not allowed to disable " + PermissionStorage.ACL_TABLE_NAME
        + " table with AccessController installed");
  }
  requirePermission(c, "disableTable",
      tableName, null, null, Action.ADMIN, Action.CREATE);
}
 
Example 11
Source Project: hbase   File: LRUDictionary.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object other) {
  if (!(other instanceof Node)) {
    return false;
  }

  Node casted = (Node) other;
  return Bytes.equals(container, offset, length, casted.getContents(),
      casted.offset, casted.length);
}
 
Example 12
Source Project: hbase   File: ThriftTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result next() throws IOException {
  if (cache.size() == 0) {
    setupNextScanner();
    try {
      List<TResult> tResults = client
          .getScannerResults(tableNameInBytes, scan, scan.getCaching());
      Result[] results = ThriftUtilities.resultsFromThrift(tResults);
      boolean firstKey = true;
      for (Result result : results) {
        // If it is a reverse scan, we use the last result's key as the startkey, since there is
        // no way to construct a closet rowkey smaller than the last result
        // So when the results return, we must rule out the first result, since it has already
        // returned to user.
        if (firstKey) {
          firstKey = false;
          if (scan.isReversed() && lastResult != null) {
            if (Bytes.equals(lastResult.getRow(), result.getRow())) {
              continue;
            }
          }
        }
        cache.add(result);
        lastResult = result;
      }
    } catch (TException e) {
      throw new IOException(e);
    }
  }

  if (cache.size() > 0) {
    return cache.poll();
  } else {
    //scan finished
    return null;
  }
}
 
Example 13
@Override
public boolean equals(Object obj) {
  if (this == obj) return true;
  if (!super.equals(obj)) return false;
  if (getClass() != obj.getClass()) return false;
  CoveredColumn other = (CoveredColumn) obj;
  if (hashCode != other.hashCode) return false;
  if (!familyString.equals(other.familyString)) return false;
  return Bytes.equals(qualifier, other.qualifier);
}
 
Example 14
@Override
public void preWALWrite(ObserverContext<? extends WALCoprocessorEnvironment> env,
    RegionInfo info, WALKey logKey, WALEdit logEdit) throws IOException {
  // check table name matches or not.
  if (!Bytes.equals(info.getTable().toBytes(), this.tableName)) {
    return;
  }
  preWALWriteCalled = true;
  // here we're going to remove one keyvalue from the WALEdit, and add
  // another one to it.
  List<Cell> cells = logEdit.getCells();
  Cell deletedCell = null;
  for (Cell cell : cells) {
    // assume only one kv from the WALEdit matches.
    byte[] family = CellUtil.cloneFamily(cell);
    byte[] qulifier = CellUtil.cloneQualifier(cell);

    if (Arrays.equals(family, ignoredFamily) &&
        Arrays.equals(qulifier, ignoredQualifier)) {
      LOG.debug("Found the KeyValue from WALEdit which should be ignored.");
      deletedCell = cell;
    }
    if (Arrays.equals(family, changedFamily) &&
        Arrays.equals(qulifier, changedQualifier)) {
      LOG.debug("Found the KeyValue from WALEdit which should be changed.");
      cell.getValueArray()[cell.getValueOffset()] =
          (byte) (cell.getValueArray()[cell.getValueOffset()] + 1);
    }
  }
  if (null != row) {
    cells.add(new KeyValue(row, addedFamily, addedQualifier));
  }
  if (deletedCell != null) {
    LOG.debug("About to delete a KeyValue from WALEdit.");
    cells.remove(deletedCell);
  }
}
 
Example 15
Source Project: hbase   File: RowCountEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a count of the rows in the region where this coprocessor is loaded.
 */
@Override
public void getRowCount(RpcController controller, CountRequest request,
                        RpcCallback<CountResponse> done) {
  Scan scan = new Scan();
  scan.setFilter(new FirstKeyOnlyFilter());
  CountResponse response = null;
  InternalScanner scanner = null;
  try {
    scanner = env.getRegion().getScanner(scan);
    List<Cell> results = new ArrayList<>();
    boolean hasMore = false;
    byte[] lastRow = null;
    long count = 0;
    do {
      hasMore = scanner.next(results);
      for (Cell kv : results) {
        byte[] currentRow = CellUtil.cloneRow(kv);
        if (lastRow == null || !Bytes.equals(lastRow, currentRow)) {
          lastRow = currentRow;
          count++;
        }
      }
      results.clear();
    } while (hasMore);

    response = CountResponse.newBuilder()
        .setCount(count).build();
  } catch (IOException ioe) {
    CoprocessorRpcUtils.setControllerException(controller, ioe);
  } finally {
    if (scanner != null) {
      try {
        scanner.close();
      } catch (IOException ignored) {}
    }
  }
  done.run(response);
}
 
Example 16
Source Project: geowave   File: HBaseBulkDeleteEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(final Object other) {
  if (!(other instanceof Column)) {
    return false;
  }
  final Column column = (Column) other;
  return Bytes.equals(family, column.family) && Bytes.equals(qualifier, column.qualifier);
}
 
Example 17
Source Project: hbase   File: RegionInfoBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return true if the given row falls in this region.
 */
@Override
public boolean containsRow(byte[] row) {
  return Bytes.compareTo(row, startKey) >= 0 &&
    (Bytes.compareTo(row, endKey) < 0 ||
     Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY));
}
 
Example 18
Source Project: phoenix   File: GuidePostsInfo.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isEmptyGpsKey(byte[] key) {
    return Bytes.equals(key, GuidePostsInfo.EMPTY_GUIDEPOST_KEY);
}
 
Example 19
protected boolean resultFound(ImmutableBytesWritable ptr) {
    if(Bytes.equals(ptr.get(), PDataType.TRUE_BYTES)) {
        return true;
    }
    return false;
}
 
Example 20
Source Project: hbase   File: MobUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Gets whether the current region name follows the pattern of a mob region name.
 * @param tableName The current table name.
 * @param regionName The current region name.
 * @return True if the current region name follows the pattern of a mob region name.
 */
public static boolean isMobRegionName(TableName tableName, byte[] regionName) {
  return Bytes.equals(regionName, getMobRegionInfo(tableName).getRegionName());
}