001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import java.io.IOException;
021import java.nio.ByteBuffer;
022import java.util.ArrayList;
023import java.util.HashMap;
024import java.util.List;
025import java.util.Map;
026import java.util.NavigableSet;
027import java.util.Set;
028import java.util.TreeMap;
029import java.util.TreeSet;
030import java.util.stream.Collectors;
031import org.apache.hadoop.hbase.HConstants;
032import org.apache.hadoop.hbase.filter.Filter;
033import org.apache.hadoop.hbase.io.TimeRange;
034import org.apache.hadoop.hbase.security.access.Permission;
035import org.apache.hadoop.hbase.security.visibility.Authorizations;
036import org.apache.hadoop.hbase.util.Bytes;
037import org.apache.yetus.audience.InterfaceAudience;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040
041/**
042 * Used to perform Get operations on a single row.
043 * <p>
044 * To get everything for a row, instantiate a Get object with the row to get. To further narrow the
045 * scope of what to Get, use the methods below.
046 * <p>
047 * To get all columns from specific families, execute {@link #addFamily(byte[]) addFamily} for each
048 * family to retrieve.
049 * <p>
050 * To get specific columns, execute {@link #addColumn(byte[], byte[]) addColumn} for each column to
051 * retrieve.
052 * <p>
053 * To only retrieve columns within a specific range of version timestamps, execute
054 * {@link #setTimeRange(long, long) setTimeRange}.
055 * <p>
056 * To only retrieve columns with a specific timestamp, execute {@link #setTimestamp(long)
057 * setTimestamp}.
058 * <p>
059 * To limit the number of versions of each column to be returned, execute {@link #readVersions(int)
060 * readVersions}.
061 * <p>
062 * To add a filter, call {@link #setFilter(Filter) setFilter}.
063 */
064@InterfaceAudience.Public
065public class Get extends Query implements Row {
066  private static final Logger LOG = LoggerFactory.getLogger(Get.class);
067
068  private byte[] row = null;
069  private int maxVersions = 1;
070  private boolean cacheBlocks = true;
071  private int storeLimit = -1;
072  private int storeOffset = 0;
073  private TimeRange tr = TimeRange.allTime();
074  private boolean checkExistenceOnly = false;
075  private Map<byte[], NavigableSet<byte[]>> familyMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
076
077  /**
078   * Create a Get operation for the specified row.
079   * <p>
080   * If no further operations are done, this will get the latest version of all columns in all
081   * families of the specified row.
082   * @param row row key
083   */
084  public Get(byte[] row) {
085    Mutation.checkRow(row);
086    this.row = row;
087  }
088
089  /**
090   * Copy-constructor
091   */
092  public Get(Get get) {
093    this(get.getRow());
094    // from Query
095    this.setFilter(get.getFilter());
096    this.setReplicaId(get.getReplicaId());
097    this.setConsistency(get.getConsistency());
098    // from Get
099    this.cacheBlocks = get.getCacheBlocks();
100    this.maxVersions = get.getMaxVersions();
101    this.storeLimit = get.getMaxResultsPerColumnFamily();
102    this.storeOffset = get.getRowOffsetPerColumnFamily();
103    this.tr = get.getTimeRange();
104    this.checkExistenceOnly = get.isCheckExistenceOnly();
105    this.loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue();
106    Map<byte[], NavigableSet<byte[]>> fams = get.getFamilyMap();
107    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : fams.entrySet()) {
108      byte[] fam = entry.getKey();
109      NavigableSet<byte[]> cols = entry.getValue();
110      if (cols != null && cols.size() > 0) {
111        for (byte[] col : cols) {
112          addColumn(fam, col);
113        }
114      } else {
115        addFamily(fam);
116      }
117    }
118    for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) {
119      setAttribute(attr.getKey(), attr.getValue());
120    }
121    for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) {
122      TimeRange tr = entry.getValue();
123      setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax());
124    }
125    super.setPriority(get.getPriority());
126  }
127
128  /**
129   * Create a Get operation for the specified row.
130   */
131  public Get(byte[] row, int rowOffset, int rowLength) {
132    Mutation.checkRow(row, rowOffset, rowLength);
133    this.row = Bytes.copy(row, rowOffset, rowLength);
134  }
135
136  /**
137   * Create a Get operation for the specified row.
138   */
139  public Get(ByteBuffer row) {
140    Mutation.checkRow(row);
141    this.row = new byte[row.remaining()];
142    row.get(this.row);
143  }
144
145  public boolean isCheckExistenceOnly() {
146    return checkExistenceOnly;
147  }
148
149  public Get setCheckExistenceOnly(boolean checkExistenceOnly) {
150    this.checkExistenceOnly = checkExistenceOnly;
151    return this;
152  }
153
154  /**
155   * Get all columns from the specified family.
156   * <p>
157   * Overrides previous calls to addColumn for this family.
158   * @param family family name
159   * @return the Get object
160   */
161  public Get addFamily(byte[] family) {
162    familyMap.remove(family);
163    familyMap.put(family, null);
164    return this;
165  }
166
167  /**
168   * Get the column from the specific family with the specified qualifier.
169   * <p>
170   * Overrides previous calls to addFamily for this family.
171   * @param family    family name
172   * @param qualifier column qualifier
173   * @return the Get objec
174   */
175  public Get addColumn(byte[] family, byte[] qualifier) {
176    NavigableSet<byte[]> set = familyMap.get(family);
177    if (set == null) {
178      set = new TreeSet<>(Bytes.BYTES_COMPARATOR);
179      familyMap.put(family, set);
180    }
181    if (qualifier == null) {
182      qualifier = HConstants.EMPTY_BYTE_ARRAY;
183    }
184    set.add(qualifier);
185    return this;
186  }
187
188  /**
189   * Get versions of columns only within the specified timestamp range, [minStamp, maxStamp).
190   * @param minStamp minimum timestamp value, inclusive
191   * @param maxStamp maximum timestamp value, exclusive
192   * @return this for invocation chaining
193   */
194  public Get setTimeRange(long minStamp, long maxStamp) throws IOException {
195    tr = TimeRange.between(minStamp, maxStamp);
196    return this;
197  }
198
199  /**
200   * Get versions of columns with the specified timestamp.
201   * @param timestamp version timestamp
202   * @return this for invocation chaining
203   */
204  public Get setTimestamp(long timestamp) {
205    try {
206      tr = TimeRange.at(timestamp);
207    } catch (Exception e) {
208      // This should never happen, unless integer overflow or something extremely wrong...
209      LOG.error("TimeRange failed, likely caused by integer overflow. ", e);
210      throw e;
211    }
212    return this;
213  }
214
215  @Override
216  public Get setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) {
217    return (Get) super.setColumnFamilyTimeRange(cf, minStamp, maxStamp);
218  }
219
220  /**
221   * Get all available versions.
222   * @return this for invocation chaining
223   */
224  public Get readAllVersions() {
225    this.maxVersions = Integer.MAX_VALUE;
226    return this;
227  }
228
229  /**
230   * Get up to the specified number of versions of each column.
231   * @param versions specified number of versions for each column
232   * @throws IOException if invalid number of versions
233   * @return this for invocation chaining
234   */
235  public Get readVersions(int versions) throws IOException {
236    if (versions <= 0) {
237      throw new IOException("versions must be positive");
238    }
239    this.maxVersions = versions;
240    return this;
241  }
242
243  @Override
244  public Get setLoadColumnFamiliesOnDemand(boolean value) {
245    return (Get) super.setLoadColumnFamiliesOnDemand(value);
246  }
247
248  /**
249   * Set the maximum number of values to return per row per Column Family
250   * @param limit the maximum number of values returned / row / CF
251   * @return this for invocation chaining
252   */
253  public Get setMaxResultsPerColumnFamily(int limit) {
254    this.storeLimit = limit;
255    return this;
256  }
257
258  /**
259   * Set offset for the row per Column Family. This offset is only within a particular row/CF
260   * combination. It gets reset back to zero when we move to the next row or CF.
261   * @param offset is the number of kvs that will be skipped.
262   * @return this for invocation chaining
263   */
264  public Get setRowOffsetPerColumnFamily(int offset) {
265    this.storeOffset = offset;
266    return this;
267  }
268
269  @Override
270  public Get setFilter(Filter filter) {
271    super.setFilter(filter);
272    return this;
273  }
274
275  /* Accessors */
276
277  /**
278   * Set whether blocks should be cached for this Get.
279   * <p>
280   * This is true by default. When true, default settings of the table and family are used (this
281   * will never override caching blocks if the block cache is disabled for that family or entirely).
282   * @param cacheBlocks if false, default settings are overridden and blocks will not be cached
283   */
284  public Get setCacheBlocks(boolean cacheBlocks) {
285    this.cacheBlocks = cacheBlocks;
286    return this;
287  }
288
289  /**
290   * Get whether blocks should be cached for this Get.
291   * @return true if default caching should be used, false if blocks should not be cached
292   */
293  public boolean getCacheBlocks() {
294    return cacheBlocks;
295  }
296
297  /**
298   * Method for retrieving the get's row
299   */
300  @Override
301  public byte[] getRow() {
302    return this.row;
303  }
304
305  /**
306   * Method for retrieving the get's maximum number of version
307   * @return the maximum number of version to fetch for this get
308   */
309  public int getMaxVersions() {
310    return this.maxVersions;
311  }
312
313  /**
314   * Method for retrieving the get's maximum number of values to return per Column Family
315   * @return the maximum number of values to fetch per CF
316   */
317  public int getMaxResultsPerColumnFamily() {
318    return this.storeLimit;
319  }
320
321  /**
322   * Method for retrieving the get's offset per row per column family (#kvs to be skipped)
323   * @return the row offset
324   */
325  public int getRowOffsetPerColumnFamily() {
326    return this.storeOffset;
327  }
328
329  /**
330   * Method for retrieving the get's TimeRange
331   */
332  public TimeRange getTimeRange() {
333    return this.tr;
334  }
335
336  /**
337   * Method for retrieving the keys in the familyMap
338   * @return keys in the current familyMap
339   */
340  public Set<byte[]> familySet() {
341    return this.familyMap.keySet();
342  }
343
344  /**
345   * Method for retrieving the number of families to get from
346   * @return number of families
347   */
348  public int numFamilies() {
349    return this.familyMap.size();
350  }
351
352  /**
353   * Method for checking if any families have been inserted into this Get
354   * @return true if familyMap is non empty false otherwise
355   */
356  public boolean hasFamilies() {
357    return !this.familyMap.isEmpty();
358  }
359
360  /**
361   * Method for retrieving the get's familyMap
362   */
363  public Map<byte[], NavigableSet<byte[]>> getFamilyMap() {
364    return this.familyMap;
365  }
366
367  /**
368   * Compile the table and column family (i.e. schema) information into a String. Useful for parsing
369   * and aggregation by debugging, logging, and administration tools.
370   */
371  @Override
372  public Map<String, Object> getFingerprint() {
373    Map<String, Object> map = new HashMap<>();
374    List<String> families = new ArrayList<>(this.familyMap.entrySet().size());
375    map.put("families", families);
376    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) {
377      families.add(Bytes.toStringBinary(entry.getKey()));
378    }
379    return map;
380  }
381
382  /**
383   * Compile the details beyond the scope of getFingerprint (row, columns, timestamps, etc.) into a
384   * Map along with the fingerprinted information. Useful for debugging, logging, and administration
385   * tools.
386   * @param maxCols a limit on the number of columns output prior to truncation
387   */
388  @Override
389  public Map<String, Object> toMap(int maxCols) {
390    // we start with the fingerprint map and build on top of it.
391    Map<String, Object> map = getFingerprint();
392    // replace the fingerprint's simple list of families with a
393    // map from column families to lists of qualifiers and kv details
394    Map<String, List<String>> columns = new HashMap<>();
395    map.put("families", columns);
396    // add scalar information first
397    map.put("row", Bytes.toStringBinary(this.row));
398    map.put("maxVersions", this.maxVersions);
399    map.put("cacheBlocks", this.cacheBlocks);
400    List<Long> timeRange = new ArrayList<>(2);
401    timeRange.add(this.tr.getMin());
402    timeRange.add(this.tr.getMax());
403    map.put("timeRange", timeRange);
404    int colCount = 0;
405    // iterate through affected families and add details
406    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) {
407      List<String> familyList = new ArrayList<>();
408      columns.put(Bytes.toStringBinary(entry.getKey()), familyList);
409      if (entry.getValue() == null) {
410        colCount++;
411        --maxCols;
412        familyList.add("ALL");
413      } else {
414        colCount += entry.getValue().size();
415        if (maxCols <= 0) {
416          continue;
417        }
418        for (byte[] column : entry.getValue()) {
419          if (--maxCols <= 0) {
420            continue;
421          }
422          familyList.add(Bytes.toStringBinary(column));
423        }
424      }
425    }
426    map.put("totalColumns", colCount);
427    if (this.filter != null) {
428      map.put("filter", this.filter.toString());
429    }
430    // add the id if set
431    if (getId() != null) {
432      map.put("id", getId());
433    }
434    map.put("storeLimit", this.storeLimit);
435    map.put("storeOffset", this.storeOffset);
436    map.put("checkExistenceOnly", this.checkExistenceOnly);
437
438    map.put("targetReplicaId", this.targetReplicaId);
439    map.put("consistency", this.consistency);
440    map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand);
441    if (!colFamTimeRangeMap.isEmpty()) {
442      Map<String, List<Long>> colFamTimeRangeMapStr = colFamTimeRangeMap.entrySet().stream()
443        .collect(Collectors.toMap((e) -> Bytes.toStringBinary(e.getKey()), e -> {
444          TimeRange value = e.getValue();
445          List<Long> rangeList = new ArrayList<>();
446          rangeList.add(value.getMin());
447          rangeList.add(value.getMax());
448          return rangeList;
449        }));
450
451      map.put("colFamTimeRangeMap", colFamTimeRangeMapStr);
452    }
453    map.put("priority", getPriority());
454    return map;
455  }
456
457  @Override
458  public int hashCode() {
459    // TODO: This is wrong. Can't have two gets the same just because on same row. But it
460    // matches how equals works currently and gets rid of the findbugs warning.
461    return Bytes.hashCode(this.getRow());
462  }
463
464  @Override
465  public boolean equals(Object obj) {
466    if (this == obj) {
467      return true;
468    }
469    if (!(obj instanceof Row)) {
470      return false;
471    }
472    Row other = (Row) obj;
473    // TODO: This is wrong. Can't have two gets the same just because on same row.
474    return Row.COMPARATOR.compare(this, other) == 0;
475  }
476
477  @Override
478  public Get setAttribute(String name, byte[] value) {
479    return (Get) super.setAttribute(name, value);
480  }
481
482  @Override
483  public Get setId(String id) {
484    return (Get) super.setId(id);
485  }
486
487  @Override
488  public Get setAuthorizations(Authorizations authorizations) {
489    return (Get) super.setAuthorizations(authorizations);
490  }
491
492  @Override
493  public Get setACL(Map<String, Permission> perms) {
494    return (Get) super.setACL(perms);
495  }
496
497  @Override
498  public Get setACL(String user, Permission perms) {
499    return (Get) super.setACL(user, perms);
500  }
501
502  @Override
503  public Get setConsistency(Consistency consistency) {
504    return (Get) super.setConsistency(consistency);
505  }
506
507  @Override
508  public Get setReplicaId(int Id) {
509    return (Get) super.setReplicaId(Id);
510  }
511
512  @Override
513  public Get setIsolationLevel(IsolationLevel level) {
514    return (Get) super.setIsolationLevel(level);
515  }
516
517  @Override
518  public Get setPriority(int priority) {
519    return (Get) super.setPriority(priority);
520  }
521}