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