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.hbase.Cell;
29  import org.apache.hadoop.hbase.CellUtil;
30  import org.apache.hadoop.hbase.KeyValue;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.classification.InterfaceStability;
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     byte [] family = CellUtil.cloneFamily(cell);
101     List<Cell> list = getCellList(family);
102     //Checking that the row of the kv is the same as the put
103     int res = Bytes.compareTo(this.row, 0, row.length,
104         cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
105     if (res != 0) {
106       throw new WrongRowIOException("The row in " + cell +
107         " doesn't match the original one " +  Bytes.toStringBinary(this.row));
108     }
109     list.add(cell);
110     familyMap.put(family, list);
111     return this;
112   }
113 
114   /**
115    * Increment the column from the specific family with the specified qualifier
116    * by the specified amount.
117    * <p>
118    * Overrides previous calls to addColumn for this family and qualifier.
119    * @param family family name
120    * @param qualifier column qualifier
121    * @param amount amount to increment by
122    * @return the Increment object
123    */
124   @SuppressWarnings("unchecked")
125   public Increment addColumn(byte [] family, byte [] qualifier, long amount) {
126     if (family == null) {
127       throw new IllegalArgumentException("family cannot be null");
128     }
129     if (qualifier == null) {
130       throw new IllegalArgumentException("qualifier cannot be null");
131     }
132     List<Cell> list = getCellList(family);
133     KeyValue kv = createPutKeyValue(family, qualifier, ts, Bytes.toBytes(amount));
134     list.add(kv);
135     familyMap.put(CellUtil.cloneFamily(kv), list);
136     return this;
137   }
138 
139   /**
140    * Gets the TimeRange used for this increment.
141    * @return TimeRange
142    */
143   public TimeRange getTimeRange() {
144     return this.tr;
145   }
146 
147   /**
148    * Sets the TimeRange to be used on the Get for this increment.
149    * <p>
150    * This is useful for when you have counters that only last for specific
151    * periods of time (ie. counters that are partitioned by time).  By setting
152    * the range of valid times for this increment, you can potentially gain
153    * some performance with a more optimal Get operation.
154    * <p>
155    * This range is used as [minStamp, maxStamp).
156    * @param minStamp minimum timestamp value, inclusive
157    * @param maxStamp maximum timestamp value, exclusive
158    * @throws IOException if invalid time range
159    * @return this
160    */
161   public Increment setTimeRange(long minStamp, long maxStamp)
162   throws IOException {
163     tr = new TimeRange(minStamp, maxStamp);
164     return this;
165   }
166 
167   /**
168    * Method for retrieving the number of families to increment from
169    * @return number of families
170    */
171   @Override
172   public int numFamilies() {
173     return this.familyMap.size();
174   }
175 
176   /**
177    * Method for checking if any families have been inserted into this Increment
178    * @return true if familyMap is non empty false otherwise
179    */
180   public boolean hasFamilies() {
181     return !this.familyMap.isEmpty();
182   }
183 
184   /**
185    * Before 0.95, when you called Increment#getFamilyMap(), you got back
186    * a map of families to a list of Longs.  Now, {@link #getFamilyCellMap()} returns
187    * families by list of Cells.  This method has been added so you can have the
188    * old behavior.
189    * @return Map of families to a Map of qualifiers and their Long increments.
190    * @since 0.95.0
191    */
192   public Map<byte[], NavigableMap<byte [], Long>> getFamilyMapOfLongs() {
193     NavigableMap<byte[], List<Cell>> map = super.getFamilyCellMap();
194     Map<byte [], NavigableMap<byte[], Long>> results =
195       new TreeMap<byte[], NavigableMap<byte [], Long>>(Bytes.BYTES_COMPARATOR);
196     for (Map.Entry<byte [], List<Cell>> entry: map.entrySet()) {
197       NavigableMap<byte [], Long> longs = new TreeMap<byte [], Long>(Bytes.BYTES_COMPARATOR);
198       for (Cell cell: entry.getValue()) {
199         longs.put(CellUtil.cloneQualifier(cell),
200             Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
201       }
202       results.put(entry.getKey(), longs);
203     }
204     return results;
205   }
206 
207   /**
208    * @return String
209    */
210   @Override
211   public String toString() {
212     StringBuilder sb = new StringBuilder();
213     sb.append("row=");
214     sb.append(Bytes.toStringBinary(this.row));
215     if(this.familyMap.size() == 0) {
216       sb.append(", no columns set to be incremented");
217       return sb.toString();
218     }
219     sb.append(", families=");
220     boolean moreThanOne = false;
221     for(Map.Entry<byte [], List<Cell>> entry: this.familyMap.entrySet()) {
222       if(moreThanOne) {
223         sb.append("), ");
224       } else {
225         moreThanOne = true;
226         sb.append("{");
227       }
228       sb.append("(family=");
229       sb.append(Bytes.toString(entry.getKey()));
230       sb.append(", columns=");
231       if(entry.getValue() == null) {
232         sb.append("NONE");
233       } else {
234         sb.append("{");
235         boolean moreThanOneB = false;
236         for(Cell cell : entry.getValue()) {
237           if(moreThanOneB) {
238             sb.append(", ");
239           } else {
240             moreThanOneB = true;
241           }
242           sb.append(CellUtil.getCellKey(cell) + "+=" +
243               Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
244         }
245         sb.append("}");
246       }
247     }
248     sb.append("}");
249     return sb.toString();
250   }
251 
252   @Override
253   public int compareTo(Row i) {
254     // TODO: This is wrong.  Can't have two the same just because on same row.
255     return Bytes.compareTo(this.getRow(), i.getRow());
256   }
257 
258   @Override
259   public int hashCode() {
260     // TODO: This is wrong.  Can't have two gets the same just because on same row.  But it
261     // matches how equals works currently and gets rid of the findbugs warning.
262     return Bytes.hashCode(this.getRow());
263   }
264 
265   @Override
266   public boolean equals(Object obj) {
267     // TODO: This is wrong.  Can't have two the same just because on same row.
268     if (this == obj) {
269       return true;
270     }
271     if (obj == null || getClass() != obj.getClass()) {
272       return false;
273     }
274     Row other = (Row) obj;
275     return compareTo(other) == 0;
276   }
277 
278   @Override
279   protected long extraHeapSize(){
280     return HEAP_OVERHEAD;
281   }
282 
283   @Override
284   public Increment setAttribute(String name, byte[] value) {
285     return (Increment) super.setAttribute(name, value);
286   }
287 
288   @Override
289   public Increment setId(String id) {
290     return (Increment) super.setId(id);
291   }
292 
293   @Override
294   public Increment setDurability(Durability d) {
295     return (Increment) super.setDurability(d);
296   }
297 
298   @Override
299   public Increment setFamilyCellMap(NavigableMap<byte[], List<Cell>> map) {
300     return (Increment) super.setFamilyCellMap(map);
301   }
302 
303   @Override
304   public Increment setClusterIds(List<UUID> clusterIds) {
305     return (Increment) super.setClusterIds(clusterIds);
306   }
307 
308   @Override
309   public Increment setCellVisibility(CellVisibility expression) {
310     return (Increment) super.setCellVisibility(expression);
311   }
312 
313   @Override
314   public Increment setACL(String user, Permission perms) {
315     return (Increment) super.setACL(user, perms);
316   }
317 
318   @Override
319   public Increment setACL(Map<String, Permission> perms) {
320     return (Increment) super.setACL(perms);
321   }
322 }