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.classification.InterfaceAudience;
35  import org.apache.hadoop.hbase.classification.InterfaceStability;
36  import org.apache.hadoop.hbase.HConstants;
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     this.closestRowBefore = get.isClosestRowBefore();
114     Map<byte[], NavigableSet<byte[]>> fams = get.getFamilyMap();
115     for (Map.Entry<byte[],NavigableSet<byte[]>> entry : fams.entrySet()) {
116       byte [] fam = entry.getKey();
117       NavigableSet<byte[]> cols = entry.getValue();
118       if (cols != null && cols.size() > 0) {
119         for (byte[] col : cols) {
120           addColumn(fam, col);
121         }
122       } else {
123         addFamily(fam);
124       }
125     }
126     for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) {
127       setAttribute(attr.getKey(), attr.getValue());
128     }
129     for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) {
130       TimeRange tr = entry.getValue();
131       setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax());
132     }
133   }
134 
135   public boolean isCheckExistenceOnly() {
136     return checkExistenceOnly;
137   }
138 
139   public Get setCheckExistenceOnly(boolean checkExistenceOnly) {
140     this.checkExistenceOnly = checkExistenceOnly;
141     return this;
142   }
143 
144   public boolean isClosestRowBefore() {
145     return closestRowBefore;
146   }
147 
148   public Get setClosestRowBefore(boolean closestRowBefore) {
149     this.closestRowBefore = closestRowBefore;
150     return this;
151   }
152 
153   /**
154    * Get all columns from the specified family.
155    * <p>
156    * Overrides previous calls to addColumn for this family.
157    * @param family family name
158    * @return the Get object
159    */
160   public Get addFamily(byte [] family) {
161     familyMap.remove(family);
162     familyMap.put(family, null);
163     return this;
164   }
165 
166   /**
167    * Get the column from the specific family with the specified qualifier.
168    * <p>
169    * Overrides previous calls to addFamily for this family.
170    * @param family family name
171    * @param qualifier column qualifier
172    * @return the Get objec
173    */
174   public Get addColumn(byte [] family, byte [] qualifier) {
175     NavigableSet<byte []> set = familyMap.get(family);
176     if(set == null) {
177       set = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
178     }
179     if (qualifier == null) {
180       qualifier = HConstants.EMPTY_BYTE_ARRAY;
181     }
182     set.add(qualifier);
183     familyMap.put(family, set);
184     return this;
185   }
186 
187   /**
188    * Get versions of columns only within the specified timestamp range,
189    * [minStamp, maxStamp).
190    * @param minStamp minimum timestamp value, inclusive
191    * @param maxStamp maximum timestamp value, exclusive
192    * @throws IOException
193    * @return this for invocation chaining
194    */
195   public Get setTimeRange(long minStamp, long maxStamp) throws IOException {
196     tr = new TimeRange(minStamp, maxStamp);
197     return this;
198   }
199 
200   /**
201    * Get versions of columns with the specified timestamp.
202    * @param timestamp version timestamp
203    * @return this for invocation chaining
204    */
205   public Get setTimeStamp(long timestamp)
206   throws IOException {
207     try {
208       tr = new TimeRange(timestamp, timestamp+1);
209     } catch(Exception e) {
210       // This should never happen, unless integer overflow or something extremely wrong...
211       LOG.error("TimeRange failed, likely caused by integer overflow. ", e);
212       throw e;
213     }
214     return this;
215   }
216 
217   @Override public Get setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) {
218     return (Get) super.setColumnFamilyTimeRange(cf, minStamp, maxStamp);
219   }
220 
221   /**
222    * Get all available versions.
223    * @return this for invocation chaining
224    */
225   public Get setMaxVersions() {
226     this.maxVersions = Integer.MAX_VALUE;
227     return this;
228   }
229 
230   /**
231    * Get up to the specified number of versions of each column.
232    * @param maxVersions maximum versions for each column
233    * @throws IOException if invalid number of versions
234    * @return this for invocation chaining
235    */
236   public Get setMaxVersions(int maxVersions) throws IOException {
237     if(maxVersions <= 0) {
238       throw new IOException("maxVersions must be positive");
239     }
240     this.maxVersions = maxVersions;
241     return this;
242   }
243 
244   /**
245    * Set the maximum number of values to return per row per Column Family
246    * @param limit the maximum number of values returned / row / CF
247    * @return this for invocation chaining
248    */
249   public Get setMaxResultsPerColumnFamily(int limit) {
250     this.storeLimit = limit;
251     return this;
252   }
253 
254   /**
255    * Set offset for the row per Column Family. This offset is only within a particular row/CF
256    * combination. It gets reset back to zero when we move to the next row or CF.
257    * @param offset is the number of kvs that will be skipped.
258    * @return this for invocation chaining
259    */
260   public Get setRowOffsetPerColumnFamily(int offset) {
261     this.storeOffset = offset;
262     return this;
263   }
264 
265   @Override
266   public Get setFilter(Filter filter) {
267     super.setFilter(filter);
268     return this;
269   }
270 
271   /* Accessors */
272 
273   /**
274    * Set whether blocks should be cached for this Get.
275    * <p>
276    * This is true by default.  When true, default settings of the table and
277    * family are used (this will never override caching blocks if the block
278    * cache is disabled for that family or entirely).
279    *
280    * @param cacheBlocks if false, default settings are overridden and blocks
281    * will not be cached
282    */
283   public Get setCacheBlocks(boolean cacheBlocks) {
284     this.cacheBlocks = cacheBlocks;
285     return this;
286   }
287 
288   /**
289    * Get whether blocks should be cached for this Get.
290    * @return true if default caching should be used, false if blocks should not
291    * be cached
292    */
293   public boolean getCacheBlocks() {
294     return cacheBlocks;
295   }
296 
297   /**
298    * Method for retrieving the get's row
299    * @return row
300    */
301   @Override
302   public byte [] getRow() {
303     return this.row;
304   }
305 
306   /**
307    * Method for retrieving the get's maximum number of version
308    * @return the maximum number of version to fetch for this get
309    */
310   public int getMaxVersions() {
311     return this.maxVersions;
312   }
313 
314   /**
315    * Method for retrieving the get's maximum number of values
316    * to return per Column Family
317    * @return the maximum number of values to fetch per CF
318    */
319   public int getMaxResultsPerColumnFamily() {
320     return this.storeLimit;
321   }
322 
323   /**
324    * Method for retrieving the get's offset per row per column
325    * family (#kvs to be skipped)
326    * @return the row offset
327    */
328   public int getRowOffsetPerColumnFamily() {
329     return this.storeOffset;
330   }
331 
332   /**
333    * Method for retrieving the get's TimeRange
334    * @return timeRange
335    */
336   public TimeRange getTimeRange() {
337     return this.tr;
338   }
339 
340   /**
341    * Method for retrieving the keys in the familyMap
342    * @return keys in the current familyMap
343    */
344   public Set<byte[]> familySet() {
345     return this.familyMap.keySet();
346   }
347 
348   /**
349    * Method for retrieving the number of families to get from
350    * @return number of families
351    */
352   public int numFamilies() {
353     return this.familyMap.size();
354   }
355 
356   /**
357    * Method for checking if any families have been inserted into this Get
358    * @return true if familyMap is non empty false otherwise
359    */
360   public boolean hasFamilies() {
361     return !this.familyMap.isEmpty();
362   }
363 
364   /**
365    * Method for retrieving the get's familyMap
366    * @return familyMap
367    */
368   public Map<byte[],NavigableSet<byte[]>> getFamilyMap() {
369     return this.familyMap;
370   }
371 
372   /**
373    * Compile the table and column family (i.e. schema) information
374    * into a String. Useful for parsing and aggregation by debugging,
375    * logging, and administration tools.
376    * @return Map
377    */
378   @Override
379   public Map<String, Object> getFingerprint() {
380     Map<String, Object> map = new HashMap<String, Object>();
381     List<String> families = new ArrayList<String>();
382     map.put("families", families);
383     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
384       this.familyMap.entrySet()) {
385       families.add(Bytes.toStringBinary(entry.getKey()));
386     }
387     return map;
388   }
389 
390   /**
391    * Compile the details beyond the scope of getFingerprint (row, columns,
392    * timestamps, etc.) into a Map along with the fingerprinted information.
393    * Useful for debugging, logging, and administration tools.
394    * @param maxCols a limit on the number of columns output prior to truncation
395    * @return Map
396    */
397   @Override
398   public Map<String, Object> toMap(int maxCols) {
399     // we start with the fingerprint map and build on top of it.
400     Map<String, Object> map = getFingerprint();
401     // replace the fingerprint's simple list of families with a
402     // map from column families to lists of qualifiers and kv details
403     Map<String, List<String>> columns = new HashMap<String, List<String>>();
404     map.put("families", columns);
405     // add scalar information first
406     map.put("row", Bytes.toStringBinary(this.row));
407     map.put("maxVersions", this.maxVersions);
408     map.put("cacheBlocks", this.cacheBlocks);
409     List<Long> timeRange = new ArrayList<Long>();
410     timeRange.add(this.tr.getMin());
411     timeRange.add(this.tr.getMax());
412     map.put("timeRange", timeRange);
413     int colCount = 0;
414     // iterate through affected families and add details
415     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
416       this.familyMap.entrySet()) {
417       List<String> familyList = new ArrayList<String>();
418       columns.put(Bytes.toStringBinary(entry.getKey()), familyList);
419       if(entry.getValue() == null) {
420         colCount++;
421         --maxCols;
422         familyList.add("ALL");
423       } else {
424         colCount += entry.getValue().size();
425         if (maxCols <= 0) {
426           continue;
427         }
428         for (byte [] column : entry.getValue()) {
429           if (--maxCols <= 0) {
430             continue;
431           }
432           familyList.add(Bytes.toStringBinary(column));
433         }
434       }
435     }
436     map.put("totalColumns", colCount);
437     if (this.filter != null) {
438       map.put("filter", this.filter.toString());
439     }
440     // add the id if set
441     if (getId() != null) {
442       map.put("id", getId());
443     }
444     return map;
445   }
446 
447   //Row
448   @Override
449   public int compareTo(Row other) {
450     // TODO: This is wrong.  Can't have two gets the same just because on same row.
451     return Bytes.compareTo(this.getRow(), other.getRow());
452   }
453 
454   @Override
455   public int hashCode() {
456     // TODO: This is wrong.  Can't have two gets the same just because on same row.  But it
457     // matches how equals works currently and gets rid of the findbugs warning.
458     return Bytes.hashCode(this.getRow());
459   }
460 
461   @Override
462   public boolean equals(Object obj) {
463     if (this == obj) {
464       return true;
465     }
466     if (obj == null || getClass() != obj.getClass()) {
467       return false;
468     }
469     Row other = (Row) obj;
470     // TODO: This is wrong.  Can't have two gets the same just because on same row.
471     return compareTo(other) == 0;
472   }
473 
474   @Override
475   public Get setAttribute(String name, byte[] value) {
476     return (Get) super.setAttribute(name, value);
477   }
478 
479   @Override
480   public Get setId(String id) {
481     return (Get) super.setId(id);
482   }
483 
484   @Override
485   public Get setAuthorizations(Authorizations authorizations) {
486     return (Get) super.setAuthorizations(authorizations);
487   }
488 
489   @Override
490   public Get setACL(Map<String, Permission> perms) {
491     return (Get) super.setACL(perms);
492   }
493 
494   @Override
495   public Get setACL(String user, Permission perms) {
496     return (Get) super.setACL(user, perms);
497   }
498 
499   @Override
500   public Get setConsistency(Consistency consistency) {
501     return (Get) super.setConsistency(consistency);
502   }
503 
504   @Override
505   public Get setReplicaId(int Id) {
506     return (Get) super.setReplicaId(Id);
507   }
508 
509   @Override
510   public Get setIsolationLevel(IsolationLevel level) {
511       return (Get) super.setIsolationLevel(level);
512   }
513 
514 }