View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.client;
20  
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.HashMap;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.NavigableSet;
28  import java.util.Set;
29  import java.util.TreeMap;
30  import java.util.TreeSet;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.classification.InterfaceStability;
37  import org.apache.hadoop.hbase.filter.Filter;
38  import org.apache.hadoop.hbase.io.TimeRange;
39  import org.apache.hadoop.hbase.security.access.Permission;
40  import org.apache.hadoop.hbase.security.visibility.Authorizations;
41  import org.apache.hadoop.hbase.util.Bytes;
42  
43  /**
44   * Used to perform Get operations on a single row.
45   * <p>
46   * To get everything for a row, instantiate a Get object with the row to get.
47   * To further narrow the scope of what to Get, use the methods below.
48   * <p>
49   * To get all columns from specific families, execute {@link #addFamily(byte[]) addFamily}
50   * for each family to retrieve.
51   * <p>
52   * To get specific columns, execute {@link #addColumn(byte[], byte[]) addColumn}
53   * for each column to retrieve.
54   * <p>
55   * To only retrieve columns within a specific range of version timestamps,
56   * execute {@link #setTimeRange(long, long) setTimeRange}.
57   * <p>
58   * To only retrieve columns with a specific timestamp, execute
59   * {@link #setTimeStamp(long) setTimestamp}.
60   * <p>
61   * To limit the number of versions of each column to be returned, execute
62   * {@link #setMaxVersions(int) setMaxVersions}.
63   * <p>
64   * To add a filter, call {@link #setFilter(Filter) setFilter}.
65   */
66  @InterfaceAudience.Public
67  @InterfaceStability.Stable
68  public class Get extends Query
69    implements Row, Comparable<Row> {
70    private static final Log LOG = LogFactory.getLog(Get.class);
71  
72    private byte [] row = null;
73    private int maxVersions = 1;
74    private boolean cacheBlocks = true;
75    private int storeLimit = -1;
76    private int storeOffset = 0;
77    private TimeRange tr = new TimeRange();
78    private boolean checkExistenceOnly = false;
79    private boolean closestRowBefore = false;
80    private Map<byte [], NavigableSet<byte []>> familyMap =
81      new TreeMap<byte [], NavigableSet<byte []>>(Bytes.BYTES_COMPARATOR);
82  
83    /**
84     * Create a Get operation for the specified row.
85     * <p>
86     * If no further operations are done, this will get the latest version of
87     * all columns in all families of the specified row.
88     * @param row row key
89     */
90    public Get(byte [] row) {
91      Mutation.checkRow(row);
92      this.row = row;
93    }
94  
95    /**
96     * Copy-constructor
97     *
98     * @param get
99     */
100   public Get(Get get) {
101     this(get.getRow());
102     // from Query
103     this.setFilter(get.getFilter());
104     this.setReplicaId(get.getReplicaId());
105     this.setConsistency(get.getConsistency());
106     // from Get
107     this.cacheBlocks = get.getCacheBlocks();
108     this.maxVersions = get.getMaxVersions();
109     this.storeLimit = get.getMaxResultsPerColumnFamily();
110     this.storeOffset = get.getRowOffsetPerColumnFamily();
111     this.tr = get.getTimeRange();
112     this.checkExistenceOnly = get.isCheckExistenceOnly();
113     Map<byte[], NavigableSet<byte[]>> fams = get.getFamilyMap();
114     for (Map.Entry<byte[],NavigableSet<byte[]>> entry : fams.entrySet()) {
115       byte [] fam = entry.getKey();
116       NavigableSet<byte[]> cols = entry.getValue();
117       if (cols != null && cols.size() > 0) {
118         for (byte[] col : cols) {
119           addColumn(fam, col);
120         }
121       } else {
122         addFamily(fam);
123       }
124     }
125     for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) {
126       setAttribute(attr.getKey(), attr.getValue());
127     }
128   }
129 
130   public boolean isCheckExistenceOnly() {
131     return checkExistenceOnly;
132   }
133 
134   public Get setCheckExistenceOnly(boolean checkExistenceOnly) {
135     this.checkExistenceOnly = checkExistenceOnly;
136     return this;
137   }
138 
139   /**
140    * This will always return the default value which is false as client cannot set the value to this
141    * property any more.
142    * @deprecated since 2.0.0 and will be removed in 3.0.0
143    */
144   @Deprecated
145   public boolean isClosestRowBefore() {
146     return closestRowBefore;
147   }
148 
149   /**
150    * This is not used any more and does nothing. Use reverse scan instead.
151    * @deprecated since 2.0.0 and will be removed in 3.0.0
152    */
153   @Deprecated
154   public Get setClosestRowBefore(boolean closestRowBefore) {
155     // do Nothing
156     return this;
157   }
158 
159   /**
160    * Get all columns from the specified family.
161    * <p>
162    * Overrides previous calls to addColumn for this family.
163    * @param family family name
164    * @return the Get object
165    */
166   public Get addFamily(byte [] family) {
167     familyMap.remove(family);
168     familyMap.put(family, null);
169     return this;
170   }
171 
172   /**
173    * Get the column from the specific family with the specified qualifier.
174    * <p>
175    * Overrides previous calls to addFamily for this family.
176    * @param family family name
177    * @param qualifier column qualifier
178    * @return the Get objec
179    */
180   public Get addColumn(byte [] family, byte [] qualifier) {
181     NavigableSet<byte []> set = familyMap.get(family);
182     if(set == null) {
183       set = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
184     }
185     if (qualifier == null) {
186       qualifier = HConstants.EMPTY_BYTE_ARRAY;
187     }
188     set.add(qualifier);
189     familyMap.put(family, set);
190     return this;
191   }
192 
193   /**
194    * Get versions of columns only within the specified timestamp range,
195    * [minStamp, maxStamp).
196    * @param minStamp minimum timestamp value, inclusive
197    * @param maxStamp maximum timestamp value, exclusive
198    * @throws IOException if invalid time range
199    * @return this for invocation chaining
200    */
201   public Get setTimeRange(long minStamp, long maxStamp)
202   throws IOException {
203     tr = new TimeRange(minStamp, maxStamp);
204     return this;
205   }
206 
207   /**
208    * Get versions of columns with the specified timestamp.
209    * @param timestamp version timestamp
210    * @return this for invocation chaining
211    */
212   public Get setTimeStamp(long timestamp)
213   throws IOException {
214     try {
215       tr = new TimeRange(timestamp, timestamp+1);
216     } catch(IOException e) {
217       // This should never happen, unless integer overflow or something extremely wrong...
218       LOG.error("TimeRange failed, likely caused by integer overflow. ", e);
219       throw e;
220     }
221     return this;
222   }
223 
224   /**
225    * Get all available versions.
226    * @return this for invocation chaining
227    */
228   public Get setMaxVersions() {
229     this.maxVersions = Integer.MAX_VALUE;
230     return this;
231   }
232 
233   /**
234    * Get up to the specified number of versions of each column.
235    * @param maxVersions maximum versions for each column
236    * @throws IOException if invalid number of versions
237    * @return this for invocation chaining
238    */
239   public Get setMaxVersions(int maxVersions) throws IOException {
240     if(maxVersions <= 0) {
241       throw new IOException("maxVersions must be positive");
242     }
243     this.maxVersions = maxVersions;
244     return this;
245   }
246 
247   /**
248    * Set the maximum number of values to return per row per Column Family
249    * @param limit the maximum number of values returned / row / CF
250    * @return this for invocation chaining
251    */
252   public Get setMaxResultsPerColumnFamily(int limit) {
253     this.storeLimit = limit;
254     return this;
255   }
256 
257   /**
258    * Set offset for the row per Column Family. This offset is only within a particular row/CF
259    * combination. It gets reset back to zero when we move to the next row or CF.
260    * @param offset is the number of kvs that will be skipped.
261    * @return this for invocation chaining
262    */
263   public Get setRowOffsetPerColumnFamily(int offset) {
264     this.storeOffset = offset;
265     return this;
266   }
267 
268   @Override
269   public Get setFilter(Filter filter) {
270     super.setFilter(filter);
271     return this;
272   }
273 
274   /* Accessors */
275 
276   /**
277    * Set whether blocks should be cached for this Get.
278    * <p>
279    * This is true by default.  When true, default settings of the table and
280    * family are used (this will never override caching blocks if the block
281    * cache is disabled for that family or entirely).
282    *
283    * @param cacheBlocks if false, default settings are overridden and blocks
284    * will not be cached
285    */
286   public Get setCacheBlocks(boolean cacheBlocks) {
287     this.cacheBlocks = cacheBlocks;
288     return this;
289   }
290 
291   /**
292    * Get whether blocks should be cached for this Get.
293    * @return true if default caching should be used, false if blocks should not
294    * be cached
295    */
296   public boolean getCacheBlocks() {
297     return cacheBlocks;
298   }
299 
300   /**
301    * Method for retrieving the get's row
302    * @return row
303    */
304   @Override
305   public byte [] getRow() {
306     return this.row;
307   }
308 
309   /**
310    * Method for retrieving the get's maximum number of version
311    * @return the maximum number of version to fetch for this get
312    */
313   public int getMaxVersions() {
314     return this.maxVersions;
315   }
316 
317   /**
318    * Method for retrieving the get's maximum number of values
319    * to return per Column Family
320    * @return the maximum number of values to fetch per CF
321    */
322   public int getMaxResultsPerColumnFamily() {
323     return this.storeLimit;
324   }
325 
326   /**
327    * Method for retrieving the get's offset per row per column
328    * family (#kvs to be skipped)
329    * @return the row offset
330    */
331   public int getRowOffsetPerColumnFamily() {
332     return this.storeOffset;
333   }
334 
335   /**
336    * Method for retrieving the get's TimeRange
337    * @return timeRange
338    */
339   public TimeRange getTimeRange() {
340     return this.tr;
341   }
342 
343   /**
344    * Method for retrieving the keys in the familyMap
345    * @return keys in the current familyMap
346    */
347   public Set<byte[]> familySet() {
348     return this.familyMap.keySet();
349   }
350 
351   /**
352    * Method for retrieving the number of families to get from
353    * @return number of families
354    */
355   public int numFamilies() {
356     return this.familyMap.size();
357   }
358 
359   /**
360    * Method for checking if any families have been inserted into this Get
361    * @return true if familyMap is non empty false otherwise
362    */
363   public boolean hasFamilies() {
364     return !this.familyMap.isEmpty();
365   }
366 
367   /**
368    * Method for retrieving the get's familyMap
369    * @return familyMap
370    */
371   public Map<byte[],NavigableSet<byte[]>> getFamilyMap() {
372     return this.familyMap;
373   }
374 
375   /**
376    * Compile the table and column family (i.e. schema) information
377    * into a String. Useful for parsing and aggregation by debugging,
378    * logging, and administration tools.
379    * @return Map
380    */
381   @Override
382   public Map<String, Object> getFingerprint() {
383     Map<String, Object> map = new HashMap<String, Object>();
384     List<String> families = new ArrayList<String>();
385     map.put("families", families);
386     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
387       this.familyMap.entrySet()) {
388       families.add(Bytes.toStringBinary(entry.getKey()));
389     }
390     return map;
391   }
392 
393   /**
394    * Compile the details beyond the scope of getFingerprint (row, columns,
395    * timestamps, etc.) into a Map along with the fingerprinted information.
396    * Useful for debugging, logging, and administration tools.
397    * @param maxCols a limit on the number of columns output prior to truncation
398    * @return Map
399    */
400   @Override
401   public Map<String, Object> toMap(int maxCols) {
402     // we start with the fingerprint map and build on top of it.
403     Map<String, Object> map = getFingerprint();
404     // replace the fingerprint's simple list of families with a
405     // map from column families to lists of qualifiers and kv details
406     Map<String, List<String>> columns = new HashMap<String, List<String>>();
407     map.put("families", columns);
408     // add scalar information first
409     map.put("row", Bytes.toStringBinary(this.row));
410     map.put("maxVersions", this.maxVersions);
411     map.put("cacheBlocks", this.cacheBlocks);
412     List<Long> timeRange = new ArrayList<Long>();
413     timeRange.add(this.tr.getMin());
414     timeRange.add(this.tr.getMax());
415     map.put("timeRange", timeRange);
416     int colCount = 0;
417     // iterate through affected families and add details
418     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
419       this.familyMap.entrySet()) {
420       List<String> familyList = new ArrayList<String>();
421       columns.put(Bytes.toStringBinary(entry.getKey()), familyList);
422       if(entry.getValue() == null) {
423         colCount++;
424         --maxCols;
425         familyList.add("ALL");
426       } else {
427         colCount += entry.getValue().size();
428         if (maxCols <= 0) {
429           continue;
430         }
431         for (byte [] column : entry.getValue()) {
432           if (--maxCols <= 0) {
433             continue;
434           }
435           familyList.add(Bytes.toStringBinary(column));
436         }
437       }
438     }
439     map.put("totalColumns", colCount);
440     if (this.filter != null) {
441       map.put("filter", this.filter.toString());
442     }
443     // add the id if set
444     if (getId() != null) {
445       map.put("id", getId());
446     }
447     return map;
448   }
449 
450   //Row
451   @Override
452   public int compareTo(Row other) {
453     // TODO: This is wrong.  Can't have two gets the same just because on same row.
454     return Bytes.compareTo(this.getRow(), other.getRow());
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 == null || getClass() != obj.getClass()) {
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 compareTo(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 }