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  import java.io.IOException;
22  import java.util.List;
23  import java.util.Map;
24  import java.util.NavigableMap;
25  import java.util.TreeMap;
26  import java.util.UUID;
27  
28  import org.apache.hadoop.classification.InterfaceAudience;
29  import org.apache.hadoop.classification.InterfaceStability;
30  import org.apache.hadoop.hbase.Cell;
31  import org.apache.hadoop.hbase.KeyValue;
32  import org.apache.hadoop.hbase.KeyValueUtil;
33  import org.apache.hadoop.hbase.io.TimeRange;
34  import org.apache.hadoop.hbase.security.access.Permission;
35  import org.apache.hadoop.hbase.security.visibility.CellVisibility;
36  import org.apache.hadoop.hbase.util.Bytes;
37  import org.apache.hadoop.hbase.util.ClassSize;
38  
39  /**
40   * Used to perform Increment operations on a single row.
41   * <p>
42   * This operation does not appear atomic to readers.  Increments are done
43   * under a single row lock, so write operations to a row are synchronized, but
44   * readers do not take row locks so get and scan operations can see this
45   * operation partially completed.
46   * <p>
47   * To increment columns of a row, instantiate an Increment object with the row
48   * to increment.  At least one column to increment must be specified using the
49   * {@link #addColumn(byte[], byte[], long)} method.
50   */
51  @InterfaceAudience.Public
52  @InterfaceStability.Stable
53  public class Increment extends Mutation implements Comparable<Row> {
54    private static final long HEAP_OVERHEAD =  ClassSize.REFERENCE + ClassSize.TIMERANGE;
55  
56    private TimeRange tr = new TimeRange();
57  
58    /**
59     * Create a Increment operation for the specified row.
60     * <p>
61     * At least one column must be incremented.
62     * @param row row key (we will make a copy of this).
63     */
64    public Increment(byte [] row) {
65      this(row, 0, row.length);
66    }
67  
68    /**
69     * Create a Increment operation for the specified row.
70     * <p>
71     * At least one column must be incremented.
72     * @param row row key (we will make a copy of this).
73     */
74    public Increment(final byte [] row, final int offset, final int length) {
75      checkRow(row, offset, length);
76      this.row = Bytes.copy(row, offset, length);
77    }
78    /**
79     * Copy constructor
80     * @param i
81     */
82    public Increment(Increment i) {
83      this.row = i.getRow();
84      this.ts = i.getTimeStamp();
85      this.tr = i.getTimeRange();
86      this.familyMap.putAll(i.getFamilyCellMap());
87      for (Map.Entry<String, byte[]> entry : i.getAttributesMap().entrySet()) {
88        this.setAttribute(entry.getKey(), entry.getValue());
89      }
90    }
91  
92    /**
93     * Add the specified KeyValue to this operation.
94     * @param cell individual Cell
95     * @return this
96     * @throws java.io.IOException e
97     */
98    @SuppressWarnings("unchecked")
99    public Increment add(Cell cell) throws IOException{
100     KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
101     byte [] family = kv.getFamily();
102     List<Cell> list = getCellList(family);
103     //Checking that the row of the kv is the same as the put
104     int res = Bytes.compareTo(this.row, 0, row.length,
105         kv.getRowArray(), kv.getRowOffset(), kv.getRowLength());
106     if (res != 0) {
107       throw new WrongRowIOException("The row in " + kv.toString() +
108         " doesn't match the original one " +  Bytes.toStringBinary(this.row));
109     }
110     list.add(kv);
111     familyMap.put(family, list);
112     return this;
113   }
114 
115   /**
116    * Increment the column from the specific family with the specified qualifier
117    * by the specified amount.
118    * <p>
119    * Overrides previous calls to addColumn for this family and qualifier.
120    * @param family family name
121    * @param qualifier column qualifier
122    * @param amount amount to increment by
123    * @return the Increment object
124    */
125   @SuppressWarnings("unchecked")
126   public Increment addColumn(byte [] family, byte [] qualifier, long amount) {
127     if (family == null) {
128       throw new IllegalArgumentException("family cannot be null");
129     }
130     if (qualifier == null) {
131       throw new IllegalArgumentException("qualifier cannot be null");
132     }
133     List<Cell> list = getCellList(family);
134     KeyValue kv = createPutKeyValue(family, qualifier, ts, Bytes.toBytes(amount));
135     list.add(kv);
136     familyMap.put(kv.getFamily(), list);
137     return this;
138   }
139 
140   /**
141    * Gets the TimeRange used for this increment.
142    * @return TimeRange
143    */
144   public TimeRange getTimeRange() {
145     return this.tr;
146   }
147 
148   /**
149    * Sets the TimeRange to be used on the Get for this increment.
150    * <p>
151    * This is useful for when you have counters that only last for specific
152    * periods of time (ie. counters that are partitioned by time).  By setting
153    * the range of valid times for this increment, you can potentially gain
154    * some performance with a more optimal Get operation.
155    * <p>
156    * This range is used as [minStamp, maxStamp).
157    * @param minStamp minimum timestamp value, inclusive
158    * @param maxStamp maximum timestamp value, exclusive
159    * @throws IOException if invalid time range
160    * @return this
161    */
162   public Increment setTimeRange(long minStamp, long maxStamp)
163   throws IOException {
164     tr = new TimeRange(minStamp, maxStamp);
165     return this;
166   }
167 
168   /**
169    * Method for retrieving the number of families to increment from
170    * @return number of families
171    */
172   @Override
173   public int numFamilies() {
174     return this.familyMap.size();
175   }
176 
177   /**
178    * Method for checking if any families have been inserted into this Increment
179    * @return true if familyMap is non empty false otherwise
180    */
181   public boolean hasFamilies() {
182     return !this.familyMap.isEmpty();
183   }
184 
185   /**
186    * Before 0.95, when you called Increment#getFamilyMap(), you got back
187    * a map of families to a list of Longs.  Now, {@link #getFamilyCellMap()} returns
188    * families by list of Cells.  This method has been added so you can have the
189    * old behavior.
190    * @return Map of families to a Map of qualifiers and their Long increments.
191    * @since 0.95.0
192    */
193   public Map<byte[], NavigableMap<byte [], Long>> getFamilyMapOfLongs() {
194     NavigableMap<byte[], List<Cell>> map = super.getFamilyCellMap();
195     Map<byte [], NavigableMap<byte[], Long>> results =
196       new TreeMap<byte[], NavigableMap<byte [], Long>>(Bytes.BYTES_COMPARATOR);
197     for (Map.Entry<byte [], List<Cell>> entry: map.entrySet()) {
198       NavigableMap<byte [], Long> longs = new TreeMap<byte [], Long>(Bytes.BYTES_COMPARATOR);
199       for (Cell cell: entry.getValue()) {
200         KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
201         longs.put(kv.getQualifier(),
202             Bytes.toLong(kv.getValueArray(), kv.getValueOffset(), kv.getValueLength()));
203       }
204       results.put(entry.getKey(), longs);
205     }
206     return results;
207   }
208 
209   /**
210    * @return String
211    */
212   @Override
213   public String toString() {
214     StringBuilder sb = new StringBuilder();
215     sb.append("row=");
216     sb.append(Bytes.toStringBinary(this.row));
217     if(this.familyMap.size() == 0) {
218       sb.append(", no columns set to be incremented");
219       return sb.toString();
220     }
221     sb.append(", families=");
222     boolean moreThanOne = false;
223     for(Map.Entry<byte [], List<Cell>> entry: this.familyMap.entrySet()) {
224       if(moreThanOne) {
225         sb.append("), ");
226       } else {
227         moreThanOne = true;
228         sb.append("{");
229       }
230       sb.append("(family=");
231       sb.append(Bytes.toString(entry.getKey()));
232       sb.append(", columns=");
233       if(entry.getValue() == null) {
234         sb.append("NONE");
235       } else {
236         sb.append("{");
237         boolean moreThanOneB = false;
238         for(Cell cell : entry.getValue()) {
239           if(moreThanOneB) {
240             sb.append(", ");
241           } else {
242             moreThanOneB = true;
243           }
244           KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
245           sb.append(Bytes.toStringBinary(kv.getKey()) + "+=" +
246               Bytes.toLong(kv.getValueArray(), kv.getValueOffset(), kv.getValueLength()));
247         }
248         sb.append("}");
249       }
250     }
251     sb.append("}");
252     return sb.toString();
253   }
254 
255   @Override
256   public int compareTo(Row i) {
257     // TODO: This is wrong.  Can't have two the same just because on same row.
258     return Bytes.compareTo(this.getRow(), i.getRow());
259   }
260 
261   @Override
262   public int hashCode() {
263     // TODO: This is wrong.  Can't have two gets the same just because on same row.  But it
264     // matches how equals works currently and gets rid of the findbugs warning.
265     return Bytes.hashCode(this.getRow());
266   }
267 
268   @Override
269   public boolean equals(Object obj) {
270     // TODO: This is wrong.  Can't have two the same just because on same row.
271     if (this == obj) {
272       return true;
273     }
274     if (obj == null || getClass() != obj.getClass()) {
275       return false;
276     }
277     Row other = (Row) obj;
278     return compareTo(other) == 0;
279   }
280 
281   @Override
282   protected long extraHeapSize(){
283     return HEAP_OVERHEAD;
284   }
285 
286   @Override
287   public Increment setAttribute(String name, byte[] value) {
288     return (Increment) super.setAttribute(name, value);
289   }
290 
291   @Override
292   public Increment setId(String id) {
293     return (Increment) super.setId(id);
294   }
295 
296   @Override
297   @Deprecated
298   public Increment setWriteToWAL(boolean write) {
299     return (Increment) super.setWriteToWAL(write);
300   }
301 
302   @Override
303   public Increment setDurability(Durability d) {
304     return (Increment) super.setDurability(d);
305   }
306 
307   @Override
308   public Increment setFamilyCellMap(NavigableMap<byte[], List<Cell>> map) {
309     return (Increment) super.setFamilyCellMap(map);
310   }
311 
312   @Override
313   @Deprecated
314   public Increment setFamilyMap(NavigableMap<byte[], List<KeyValue>> map) {
315     return (Increment) super.setFamilyMap(map);
316   }
317 
318   @Override
319   public Increment setClusterIds(List<UUID> clusterIds) {
320     return (Increment) super.setClusterIds(clusterIds);
321   }
322 
323   @Override
324   public Increment setCellVisibility(CellVisibility expression) {
325     return (Increment) super.setCellVisibility(expression);
326   }
327 
328   @Override
329   public Increment setACL(String user, Permission perms) {
330     return (Increment) super.setACL(user, perms);
331   }
332 
333   @Override
334   public Increment setACL(Map<String, Permission> perms) {
335     return (Increment) super.setACL(perms);
336   }
337 }