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