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