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  
27  import org.apache.hadoop.classification.InterfaceAudience;
28  import org.apache.hadoop.classification.InterfaceStability;
29  import org.apache.hadoop.hbase.Cell;
30  import org.apache.hadoop.hbase.KeyValue;
31  import org.apache.hadoop.hbase.KeyValueUtil;
32  import org.apache.hadoop.hbase.io.TimeRange;
33  import org.apache.hadoop.hbase.util.Bytes;
34  import org.apache.hadoop.hbase.util.ClassSize;
35  
36  /**
37   * Used to perform Increment operations on a single row.
38   * <p>
39   * This operation does not appear atomic to readers.  Increments are done
40   * under a single row lock, so write operations to a row are synchronized, but
41   * readers do not take row locks so get and scan operations can see this
42   * operation partially completed.
43   * <p>
44   * To increment columns of a row, instantiate an Increment object with the row
45   * to increment.  At least one column to increment must be specified using the
46   * {@link #addColumn(byte[], byte[], long)} method.
47   */
48  @InterfaceAudience.Public
49  @InterfaceStability.Stable
50  public class Increment extends Mutation implements Comparable<Row> {
51    private static final long HEAP_OVERHEAD =  ClassSize.REFERENCE + ClassSize.TIMERANGE;
52  
53    private TimeRange tr = new TimeRange();
54  
55    /**
56     * Create a Increment operation for the specified row.
57     * <p>
58     * At least one column must be incremented.
59     * @param row row key (we will make a copy of this).
60     */
61    public Increment(byte [] row) {
62      this(row, 0, row.length);
63    }
64  
65    /**
66     * Create a Increment operation for the specified row.
67     * <p>
68     * At least one column must be incremented.
69     * @param row row key (we will make a copy of this).
70     */
71    public Increment(final byte [] row, final int offset, final int length) {
72      checkRow(row, offset, length);
73      this.row = Bytes.copy(row, offset, length);
74    }
75    /**
76     * Copy constructor
77     * @param i
78     */
79    public Increment(Increment i) {
80      this.row = i.getRow();
81      this.ts = i.getTimeStamp();
82      this.tr = i.getTimeRange();
83      this.familyMap.putAll(i.getFamilyCellMap());
84      for (Map.Entry<String, byte[]> entry : i.getAttributesMap().entrySet()) {
85        this.setAttribute(entry.getKey(), entry.getValue());
86      }
87    }
88  
89    /**
90     * Add the specified KeyValue to this operation.
91     * @param cell individual Cell
92     * @return this
93     * @throws java.io.IOException e
94     */
95    @SuppressWarnings("unchecked")
96    public Increment add(Cell cell) throws IOException{
97      KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
98      byte [] family = kv.getFamily();
99      List<Cell> list = getCellList(family);
100     //Checking that the row of the kv is the same as the put
101     int res = Bytes.compareTo(this.row, 0, row.length,
102         kv.getRowArray(), kv.getRowOffset(), kv.getRowLength());
103     if (res != 0) {
104       throw new WrongRowIOException("The row in " + kv.toString() +
105         " doesn't match the original one " +  Bytes.toStringBinary(this.row));
106     }
107     list.add(kv);
108     familyMap.put(family, list);
109     return this;
110   }
111 
112   /**
113    * Increment the column from the specific family with the specified qualifier
114    * by the specified amount.
115    * <p>
116    * Overrides previous calls to addColumn for this family and qualifier.
117    * @param family family name
118    * @param qualifier column qualifier
119    * @param amount amount to increment by
120    * @return the Increment object
121    */
122   @SuppressWarnings("unchecked")
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(kv.getFamily(), 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   public int numFamilies() {
170     return this.familyMap.size();
171   }
172 
173   /**
174    * Method for checking if any families have been inserted into this Increment
175    * @return true if familyMap is non empty false otherwise
176    */
177   public boolean hasFamilies() {
178     return !this.familyMap.isEmpty();
179   }
180 
181   /**
182    * Before 0.95, when you called Increment#getFamilyMap(), you got back
183    * a map of families to a list of Longs.  Now, {@link #getFamilyCellMap()} returns
184    * families by list of Cells.  This method has been added so you can have the
185    * old behavior.
186    * @return Map of families to a Map of qualifiers and their Long increments.
187    * @since 0.95.0
188    */
189   public Map<byte[], NavigableMap<byte [], Long>> getFamilyMapOfLongs() {
190     NavigableMap<byte[], List<Cell>> map = super.getFamilyCellMap();
191     Map<byte [], NavigableMap<byte[], Long>> results =
192       new TreeMap<byte[], NavigableMap<byte [], Long>>(Bytes.BYTES_COMPARATOR);
193     for (Map.Entry<byte [], List<Cell>> entry: map.entrySet()) {
194       NavigableMap<byte [], Long> longs = new TreeMap<byte [], Long>(Bytes.BYTES_COMPARATOR);
195       for (Cell cell: entry.getValue()) {
196         KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
197         longs.put(kv.getQualifier(),
198             Bytes.toLong(kv.getValueArray(), kv.getValueOffset(), kv.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           KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
241           sb.append(Bytes.toStringBinary(kv.getKey()) + "+=" +
242               Bytes.toLong(kv.getValueArray(), kv.getValueOffset(), kv.getValueLength()));
243         }
244         sb.append("}");
245       }
246     }
247     sb.append("}");
248     return sb.toString();
249   }
250 
251   @Override
252   public int compareTo(Row i) {
253     // TODO: This is wrong.  Can't have two the same just because on same row.
254     return Bytes.compareTo(this.getRow(), i.getRow());
255   }
256 
257   @Override
258   public int hashCode() {
259     // TODO: This is wrong.  Can't have two gets the same just because on same row.  But it
260     // matches how equals works currently and gets rid of the findbugs warning.
261     return Bytes.hashCode(this.getRow());
262   }
263 
264   @Override
265   public boolean equals(Object obj) {
266     // TODO: This is wrong.  Can't have two the same just because on same row.
267     if (this == obj) {
268       return true;
269     }
270     if (obj == null || getClass() != obj.getClass()) {
271       return false;
272     }
273     Row other = (Row) obj;
274     return compareTo(other) == 0;
275   }
276 
277   protected long extraHeapSize(){
278     return HEAP_OVERHEAD;
279   }
280 }