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;
20  
21  import java.io.ByteArrayInputStream;
22  import java.io.ByteArrayOutputStream;
23  import java.io.DataInputStream;
24  import java.io.DataOutputStream;
25  import java.io.IOException;
26  import java.util.Arrays;
27  import java.util.Collections;
28  import java.util.Iterator;
29  import java.util.List;
30  import java.util.Set;
31  import java.util.TreeSet;
32  
33  import junit.framework.TestCase;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.hbase.KeyValue.KVComparator;
38  import org.apache.hadoop.hbase.KeyValue.MetaComparator;
39  import org.apache.hadoop.hbase.KeyValue.Type;
40  import org.apache.hadoop.hbase.testclassification.SmallTests;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.junit.Test;
43  import org.junit.experimental.categories.Category;
44  
45  import static org.junit.Assert.assertNotEquals;
46  
47  @Category(SmallTests.class)
48  public class TestKeyValue extends TestCase {
49    private static final Log LOG = LogFactory.getLog(TestKeyValue.class);
50  
51    public void testColumnCompare() throws Exception {
52      final byte [] a = Bytes.toBytes("aaa");
53      byte [] family1 = Bytes.toBytes("abc");
54      byte [] qualifier1 = Bytes.toBytes("def");
55      byte [] family2 = Bytes.toBytes("abcd");
56      byte [] qualifier2 = Bytes.toBytes("ef");
57  
58      KeyValue aaa = new KeyValue(a, family1, qualifier1, 0L, Type.Put, a);
59      assertFalse(CellUtil.matchingColumn(aaa, family2, qualifier2));
60      assertTrue(CellUtil.matchingColumn(aaa, family1, qualifier1));
61      aaa = new KeyValue(a, family2, qualifier2, 0L, Type.Put, a);
62      assertFalse(CellUtil.matchingColumn(aaa, family1, qualifier1));
63      assertTrue(CellUtil.matchingColumn(aaa, family2,qualifier2));
64      byte [] nullQualifier = new byte[0];
65      aaa = new KeyValue(a, family1, nullQualifier, 0L, Type.Put, a);
66      assertTrue(CellUtil.matchingColumn(aaa, family1,null));
67      assertFalse(CellUtil.matchingColumn(aaa, family2,qualifier2));
68    }
69  
70    /**
71     * Test a corner case when the family qualifier is a prefix of the
72     *  column qualifier.
73     */
74    public void testColumnCompare_prefix() throws Exception {
75      final byte [] a = Bytes.toBytes("aaa");
76      byte [] family1 = Bytes.toBytes("abc");
77      byte [] qualifier1 = Bytes.toBytes("def");
78      byte [] family2 = Bytes.toBytes("ab");
79      byte [] qualifier2 = Bytes.toBytes("def");
80  
81      KeyValue aaa = new KeyValue(a, family1, qualifier1, 0L, Type.Put, a);
82      assertFalse(CellUtil.matchingColumn(aaa, family2, qualifier2));
83    }
84  
85    public void testBasics() throws Exception {
86      LOG.info("LOWKEY: " + KeyValue.LOWESTKEY.toString());
87      check(Bytes.toBytes(getName()),
88        Bytes.toBytes(getName()), Bytes.toBytes(getName()), 1,
89        Bytes.toBytes(getName()));
90      // Test empty value and empty column -- both should work. (not empty fam)
91      check(Bytes.toBytes(getName()), Bytes.toBytes(getName()), null, 1, null);
92      check(HConstants.EMPTY_BYTE_ARRAY, Bytes.toBytes(getName()), null, 1, null);
93      // empty qual is equivalent to null qual
94      assertEquals(
95        new KeyValue(Bytes.toBytes("rk"), Bytes.toBytes("fam"), null, 1, (byte[]) null),
96        new KeyValue(Bytes.toBytes("rk"), Bytes.toBytes("fam"),
97          HConstants.EMPTY_BYTE_ARRAY, 1, (byte[]) null));
98    }
99  
100   private void check(final byte [] row, final byte [] family, byte [] qualifier,
101     final long timestamp, final byte [] value) {
102     KeyValue kv = new KeyValue(row, family, qualifier, timestamp, value);
103     assertTrue(Bytes.compareTo(kv.getRow(), row) == 0);
104     assertTrue(CellUtil.matchingColumn(kv, family, qualifier));
105     // Call toString to make sure it works.
106     LOG.info(kv.toString());
107   }
108 
109   public void testPlainCompare() throws Exception {
110     final byte [] a = Bytes.toBytes("aaa");
111     final byte [] b = Bytes.toBytes("bbb");
112     final byte [] fam = Bytes.toBytes("col");
113     final byte [] qf = Bytes.toBytes("umn");
114     KeyValue aaa = new KeyValue(a, fam, qf, a);
115     KeyValue bbb = new KeyValue(b, fam, qf, b);
116     assertTrue(KeyValue.COMPARATOR.compare(aaa, bbb) < 0);
117     assertTrue(KeyValue.COMPARATOR.compare(bbb, aaa) > 0);
118     // Compare breaks if passed same ByteBuffer as both left and right arguments.
119     assertTrue(KeyValue.COMPARATOR.compare(bbb, bbb) == 0);
120     assertTrue(KeyValue.COMPARATOR.compare(aaa, aaa) == 0);
121     // Do compare with different timestamps.
122     aaa = new KeyValue(a, fam, qf, 1, a);
123     bbb = new KeyValue(a, fam, qf, 2, a);
124     assertTrue(KeyValue.COMPARATOR.compare(aaa, bbb) > 0);
125     assertTrue(KeyValue.COMPARATOR.compare(bbb, aaa) < 0);
126     assertTrue(KeyValue.COMPARATOR.compare(aaa, aaa) == 0);
127     // Do compare with different types.  Higher numbered types -- Delete
128     // should sort ahead of lower numbers; i.e. Put
129     aaa = new KeyValue(a, fam, qf, 1, KeyValue.Type.Delete, a);
130     bbb = new KeyValue(a, fam, qf, 1, a);
131     assertTrue(KeyValue.COMPARATOR.compare(aaa, bbb) < 0);
132     assertTrue(KeyValue.COMPARATOR.compare(bbb, aaa) > 0);
133     assertTrue(KeyValue.COMPARATOR.compare(aaa, aaa) == 0);
134   }
135 
136   public void testMoreComparisons() throws Exception {
137     long now = System.currentTimeMillis();
138 
139     // Meta compares
140     KeyValue aaa = new KeyValue(
141         Bytes.toBytes("TestScanMultipleVersions,row_0500,1236020145502"), now);
142     KeyValue bbb = new KeyValue(
143         Bytes.toBytes("TestScanMultipleVersions,,99999999999999"), now);
144     KVComparator c = new KeyValue.MetaComparator();
145     assertTrue(c.compare(bbb, aaa) < 0);
146 
147     KeyValue aaaa = new KeyValue(Bytes.toBytes("TestScanMultipleVersions,,1236023996656"),
148         Bytes.toBytes("info"), Bytes.toBytes("regioninfo"), 1236024396271L,
149         (byte[])null);
150     assertTrue(c.compare(aaaa, bbb) < 0);
151 
152     KeyValue x = new KeyValue(Bytes.toBytes("TestScanMultipleVersions,row_0500,1236034574162"),
153         Bytes.toBytes("info"), Bytes.toBytes(""), 9223372036854775807L,
154         (byte[])null);
155     KeyValue y = new KeyValue(Bytes.toBytes("TestScanMultipleVersions,row_0500,1236034574162"),
156         Bytes.toBytes("info"), Bytes.toBytes("regioninfo"), 1236034574912L,
157         (byte[])null);
158     assertTrue(c.compare(x, y) < 0);
159     comparisons(new KeyValue.MetaComparator());
160     comparisons(new KeyValue.KVComparator());
161     metacomparisons(new KeyValue.MetaComparator());
162   }
163 
164   public void testMetaComparatorTableKeysWithCommaOk() {
165     MetaComparator c = new KeyValue.MetaComparator();
166     long now = System.currentTimeMillis();
167     // meta keys values are not quite right.  A users can enter illegal values
168     // from shell when scanning meta.
169     KeyValue a = new KeyValue(Bytes.toBytes("table,key,with,commas1,1234"), now);
170     KeyValue b = new KeyValue(Bytes.toBytes("table,key,with,commas2,0123"), now);
171     assertTrue(c.compare(a, b) < 0);
172   }
173 
174   /**
175    * Tests cases where rows keys have characters below the ','.
176    * See HBASE-832
177    * @throws IOException
178    */
179   public void testKeyValueBorderCases() throws IOException {
180     // % sorts before , so if we don't do special comparator, rowB would
181     // come before rowA.
182     KeyValue rowA = new KeyValue(Bytes.toBytes("testtable,www.hbase.org/,1234"),
183       Bytes.toBytes("fam"), Bytes.toBytes(""), Long.MAX_VALUE, (byte[])null);
184     KeyValue rowB = new KeyValue(Bytes.toBytes("testtable,www.hbase.org/%20,99999"),
185         Bytes.toBytes("fam"), Bytes.toBytes(""), Long.MAX_VALUE, (byte[])null);
186     assertTrue(KeyValue.META_COMPARATOR.compare(rowA, rowB) < 0);
187 
188     rowA = new KeyValue(Bytes.toBytes("testtable,,1234"), Bytes.toBytes("fam"),
189         Bytes.toBytes(""), Long.MAX_VALUE, (byte[])null);
190     rowB = new KeyValue(Bytes.toBytes("testtable,$www.hbase.org/,99999"),
191         Bytes.toBytes("fam"), Bytes.toBytes(""), Long.MAX_VALUE, (byte[])null);
192     assertTrue(KeyValue.META_COMPARATOR.compare(rowA, rowB) < 0);
193 
194   }
195 
196   private void metacomparisons(final KeyValue.MetaComparator c) {
197     long now = System.currentTimeMillis();
198     assertTrue(c.compare(new KeyValue(
199         Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",a,,0,1"), now),
200       new KeyValue(
201           Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",a,,0,1"), now)) == 0);
202     KeyValue a = new KeyValue(
203         Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",a,,0,1"), now);
204     KeyValue b = new KeyValue(
205         Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",a,,0,2"), now);
206     assertTrue(c.compare(a, b) < 0);
207     assertTrue(c.compare(new KeyValue(
208         Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",a,,0,2"), now),
209       new KeyValue(
210           Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",a,,0,1"), now)) > 0);
211   }
212 
213   private void comparisons(final KeyValue.KVComparator c) {
214     long now = System.currentTimeMillis();
215     assertTrue(c.compare(new KeyValue(
216         Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",,1"), now),
217       new KeyValue(
218           Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",,1"), now)) == 0);
219     assertTrue(c.compare(new KeyValue(
220         Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",,1"), now),
221       new KeyValue(
222           Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",,2"), now)) < 0);
223     assertTrue(c.compare(new KeyValue(
224         Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",,2"), now),
225       new KeyValue(
226           Bytes.toBytes(TableName.META_TABLE_NAME.getNameAsString()+",,1"), now)) > 0);
227   }
228 
229   public void testBinaryKeys() throws Exception {
230     Set<KeyValue> set = new TreeSet<KeyValue>(KeyValue.COMPARATOR);
231     final byte [] fam = Bytes.toBytes("col");
232     final byte [] qf = Bytes.toBytes("umn");
233     final byte [] nb = new byte[0];
234     KeyValue [] keys = {new KeyValue(Bytes.toBytes("aaaaa,\u0000\u0000,2"), fam, qf, 2, nb),
235       new KeyValue(Bytes.toBytes("aaaaa,\u0001,3"), fam, qf, 3, nb),
236       new KeyValue(Bytes.toBytes("aaaaa,,1"), fam, qf, 1, nb),
237       new KeyValue(Bytes.toBytes("aaaaa,\u1000,5"), fam, qf, 5, nb),
238       new KeyValue(Bytes.toBytes("aaaaa,a,4"), fam, qf, 4, nb),
239       new KeyValue(Bytes.toBytes("a,a,0"), fam, qf, 0, nb),
240     };
241     // Add to set with bad comparator
242     Collections.addAll(set, keys);
243     // This will output the keys incorrectly.
244     boolean assertion = false;
245     int count = 0;
246     try {
247       for (KeyValue k: set) {
248         assertTrue(count++ == k.getTimestamp());
249       }
250     } catch (junit.framework.AssertionFailedError e) {
251       // Expected
252       assertion = true;
253     }
254     assertTrue(assertion);
255     // Make set with good comparator
256     set = new TreeSet<KeyValue>(new KeyValue.MetaComparator());
257     Collections.addAll(set, keys);
258     count = 0;
259     for (KeyValue k: set) {
260       assertTrue(count++ == k.getTimestamp());
261     }
262   }
263 
264   public void testStackedUpKeyValue() {
265     // Test multiple KeyValues in a single blob.
266 
267     // TODO actually write this test!
268 
269   }
270 
271   private final byte[] rowA = Bytes.toBytes("rowA");
272   private final byte[] rowB = Bytes.toBytes("rowB");
273 
274   private final byte[] family = Bytes.toBytes("family");
275   private final byte[] qualA = Bytes.toBytes("qfA");
276   private final byte[] qualB = Bytes.toBytes("qfB");
277 
278   private void assertKVLess(KeyValue.KVComparator c,
279                             KeyValue less,
280                             KeyValue greater) {
281     int cmp = c.compare(less,greater);
282     assertTrue(cmp < 0);
283     cmp = c.compare(greater,less);
284     assertTrue(cmp > 0);
285   }
286 
287   private void assertKVLessWithoutRow(KeyValue.KVComparator c, int common, KeyValue less,
288       KeyValue greater) {
289     int cmp = c.compareIgnoringPrefix(common, less.getBuffer(), less.getOffset()
290         + KeyValue.ROW_OFFSET, less.getKeyLength(), greater.getBuffer(),
291         greater.getOffset() + KeyValue.ROW_OFFSET, greater.getKeyLength());
292     assertTrue(cmp < 0);
293     cmp = c.compareIgnoringPrefix(common, greater.getBuffer(), greater.getOffset()
294         + KeyValue.ROW_OFFSET, greater.getKeyLength(), less.getBuffer(),
295         less.getOffset() + KeyValue.ROW_OFFSET, less.getKeyLength());
296     assertTrue(cmp > 0);
297   }
298 
299   public void testCompareWithoutRow() {
300     final KeyValue.KVComparator c = KeyValue.COMPARATOR;
301     byte[] row = Bytes.toBytes("row");
302 
303     byte[] fa = Bytes.toBytes("fa");
304     byte[] fami = Bytes.toBytes("fami");
305     byte[] fami1 = Bytes.toBytes("fami1");
306 
307     byte[] qual0 = Bytes.toBytes("");
308     byte[] qual1 = Bytes.toBytes("qf1");
309     byte[] qual2 = Bytes.toBytes("qf2");
310     long ts = 1;
311 
312     // 'fa:'
313     KeyValue kv_0 = new KeyValue(row, fa, qual0, ts, Type.Put);
314     // 'fami:'
315     KeyValue kv0_0 = new KeyValue(row, fami, qual0, ts, Type.Put);
316     // 'fami:qf1'
317     KeyValue kv0_1 = new KeyValue(row, fami, qual1, ts, Type.Put);
318     // 'fami:qf2'
319     KeyValue kv0_2 = new KeyValue(row, fami, qual2, ts, Type.Put);
320     // 'fami1:'
321     KeyValue kv1_0 = new KeyValue(row, fami1, qual0, ts, Type.Put);
322 
323     // 'fami:qf1' < 'fami:qf2'
324     assertKVLessWithoutRow(c, 0, kv0_1, kv0_2);
325     // 'fami:qf1' < 'fami1:'
326     assertKVLessWithoutRow(c, 0, kv0_1, kv1_0);
327 
328     // Test comparison by skipping the same prefix bytes.
329     /***
330      * KeyValue Format and commonLength:
331      * |_keyLen_|_valLen_|_rowLen_|_rowKey_|_famiLen_|_fami_|_Quali_|....
332      * ------------------|-------commonLength--------|--------------
333      */
334     int commonLength = KeyValue.ROW_LENGTH_SIZE + KeyValue.FAMILY_LENGTH_SIZE
335         + row.length;
336     // 'fa:' < 'fami:'. They have commonPrefix + 2 same prefix bytes.
337     assertKVLessWithoutRow(c, commonLength + 2, kv_0, kv0_0);
338     // 'fami:' < 'fami:qf1'. They have commonPrefix + 4 same prefix bytes.
339     assertKVLessWithoutRow(c, commonLength + 4, kv0_0, kv0_1);
340     // 'fami:qf1' < 'fami1:'. They have commonPrefix + 4 same prefix bytes.
341     assertKVLessWithoutRow(c, commonLength + 4, kv0_1, kv1_0);
342     // 'fami:qf1' < 'fami:qf2'. They have commonPrefix + 6 same prefix bytes.
343     assertKVLessWithoutRow(c, commonLength + 6, kv0_1, kv0_2);
344   }
345 
346   public void testFirstLastOnRow() {
347     final KVComparator c = KeyValue.COMPARATOR;
348     long ts = 1;
349     byte[] bufferA = new byte[128];
350     int offsetA = 0;
351     byte[] bufferB = new byte[128];
352     int offsetB = 7;
353 
354     // These are listed in sort order (ie: every one should be less
355     // than the one on the next line).
356     final KeyValue firstOnRowA = KeyValueUtil.createFirstOnRow(rowA);
357     final KeyValue firstOnRowABufferFamQual = KeyValueUtil.createFirstOnRow(bufferA, offsetA,
358         rowA, 0, rowA.length, family, 0, family.length, qualA, 0, qualA.length);
359     final KeyValue kvA_1 = new KeyValue(rowA, null, null, ts, Type.Put);
360     final KeyValue kvA_2 = new KeyValue(rowA, family, qualA, ts, Type.Put);
361 
362     final KeyValue lastOnRowA = KeyValueUtil.createLastOnRow(rowA);
363     final KeyValue firstOnRowB = KeyValueUtil.createFirstOnRow(rowB);
364     final KeyValue firstOnRowBBufferFam = KeyValueUtil.createFirstOnRow(bufferB, offsetB,
365         rowB, 0, rowB.length, family, 0, family.length, null, 0, 0);
366     final KeyValue kvB = new KeyValue(rowB, family, qualA, ts, Type.Put);
367 
368     assertKVLess(c, firstOnRowA, firstOnRowB);
369     assertKVLess(c, firstOnRowA, firstOnRowBBufferFam);
370     assertKVLess(c, firstOnRowABufferFamQual, firstOnRowB);
371     assertKVLess(c, firstOnRowA, kvA_1);
372     assertKVLess(c, firstOnRowA, kvA_2);
373     assertKVLess(c, firstOnRowABufferFamQual, kvA_2);
374     assertKVLess(c, kvA_1, kvA_2);
375     assertKVLess(c, kvA_2, firstOnRowB);
376     assertKVLess(c, kvA_1, firstOnRowB);
377     assertKVLess(c, kvA_2, firstOnRowBBufferFam);
378     assertKVLess(c, kvA_1, firstOnRowBBufferFam);
379 
380     assertKVLess(c, lastOnRowA, firstOnRowB);
381     assertKVLess(c, lastOnRowA, firstOnRowBBufferFam);
382     assertKVLess(c, firstOnRowB, kvB);
383     assertKVLess(c, firstOnRowBBufferFam, kvB);
384     assertKVLess(c, lastOnRowA, kvB);
385 
386     assertKVLess(c, kvA_2, lastOnRowA);
387     assertKVLess(c, kvA_1, lastOnRowA);
388     assertKVLess(c, firstOnRowA, lastOnRowA);
389     assertKVLess(c, firstOnRowABufferFamQual, lastOnRowA);
390   }
391 
392   public void testCreateKeyOnly() throws Exception {
393     long ts = 1;
394     byte [] value = Bytes.toBytes("a real value");
395     byte [] evalue = new byte[0]; // empty value
396 
397     for (byte[] val : new byte[][]{value, evalue}) {
398       for (boolean useLen : new boolean[]{false,true}) {
399         KeyValue kv1 = new KeyValue(rowA, family, qualA, ts, val);
400         KeyValue kv1ko = kv1.createKeyOnly(useLen);
401         // keys are still the same
402         assertTrue(kv1.equals(kv1ko));
403         // but values are not
404         assertTrue(kv1ko.getValue().length == (useLen?Bytes.SIZEOF_INT:0));
405         if (useLen) {
406           assertEquals(kv1.getValueLength(), Bytes.toInt(kv1ko.getValue()));
407         }
408       }
409     }
410   }
411 
412   public void testCreateKeyValueFromKey() {
413     KeyValue kv = new KeyValue(Bytes.toBytes("myRow"), Bytes.toBytes("myCF"),
414         Bytes.toBytes("myQualifier"), 12345L, Bytes.toBytes("myValue"));
415     int initialPadding = 10;
416     int endingPadding = 20;
417     int keyLen = kv.getKeyLength();
418     byte[] tmpArr = new byte[initialPadding + endingPadding + keyLen];
419     System.arraycopy(kv.getBuffer(), kv.getKeyOffset(), tmpArr,
420         initialPadding, keyLen);
421     KeyValue kvFromKey = KeyValue.createKeyValueFromKey(tmpArr, initialPadding,
422         keyLen);
423     assertEquals(keyLen, kvFromKey.getKeyLength());
424     assertEquals(KeyValue.ROW_OFFSET + keyLen, kvFromKey.getBuffer().length);
425     System.err.println("kv=" + kv);
426     System.err.println("kvFromKey=" + kvFromKey);
427     assertEquals(kvFromKey.toString(),
428         kv.toString().replaceAll("=[0-9]+", "=0"));
429   }
430 
431   /**
432    * Tests that getTimestamp() does always return the proper timestamp, even after updating it.
433    * See HBASE-6265.
434    */
435   public void testGetTimestamp() {
436     KeyValue kv = new KeyValue(Bytes.toBytes("myRow"), Bytes.toBytes("myCF"),
437       Bytes.toBytes("myQualifier"), HConstants.LATEST_TIMESTAMP,
438       Bytes.toBytes("myValue"));
439     long time1 = kv.getTimestamp();
440     kv.updateLatestStamp(Bytes.toBytes(12345L));
441     long time2 = kv.getTimestamp();
442     assertEquals(HConstants.LATEST_TIMESTAMP, time1);
443     assertEquals(12345L, time2);
444   }
445 
446   /**
447    * See HBASE-7845
448    */
449   public void testGetShortMidpointKey() {
450     final KVComparator keyComparator = KeyValue.COMPARATOR;
451     //verify that faked shorter rowkey could be generated
452     long ts = 5;
453     KeyValue kv1 = new KeyValue(Bytes.toBytes("the quick brown fox"), family, qualA, ts, Type.Put);
454     KeyValue kv2 = new KeyValue(Bytes.toBytes("the who test text"), family, qualA, ts, Type.Put);
455     byte[] newKey = keyComparator.getShortMidpointKey(kv1.getKey(), kv2.getKey());
456     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), newKey) < 0);
457     assertTrue(keyComparator.compareFlatKey(newKey, kv2.getKey()) < 0);
458     short newRowLength = Bytes.toShort(newKey, 0);
459     byte[] expectedArray = Bytes.toBytes("the r");
460     Bytes.equals(newKey, KeyValue.ROW_LENGTH_SIZE, newRowLength, expectedArray, 0,
461       expectedArray.length);
462 
463     //verify: same with "row + family + qualifier", return rightKey directly
464     kv1 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, 5, Type.Put);
465     kv2 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, 0, Type.Put);
466     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), kv2.getKey()) < 0);
467     newKey = keyComparator.getShortMidpointKey(kv1.getKey(), kv2.getKey());
468     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), newKey) < 0);
469     assertTrue(keyComparator.compareFlatKey(newKey, kv2.getKey()) == 0);
470     kv1 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, -5, Type.Put);
471     kv2 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, -10, Type.Put);
472     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), kv2.getKey()) < 0);
473     newKey = keyComparator.getShortMidpointKey(kv1.getKey(), kv2.getKey());
474     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), newKey) < 0);
475     assertTrue(keyComparator.compareFlatKey(newKey, kv2.getKey()) == 0);
476 
477     // verify: same with row, different with qualifier
478     kv1 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, 5, Type.Put);
479     kv2 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualB, 5, Type.Put);
480     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), kv2.getKey()) < 0);
481     newKey = keyComparator.getShortMidpointKey(kv1.getKey(), kv2.getKey());
482     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), newKey) < 0);
483     assertTrue(keyComparator.compareFlatKey(newKey, kv2.getKey()) < 0);
484     KeyValue newKeyValue = KeyValue.createKeyValueFromKey(newKey);
485     assertTrue(Arrays.equals(newKeyValue.getFamily(),family));
486     assertTrue(Arrays.equals(newKeyValue.getQualifier(),qualB));
487     assertTrue(newKeyValue.getTimestamp() == HConstants.LATEST_TIMESTAMP);
488     assertTrue(newKeyValue.getTypeByte() == Type.Maximum.getCode());
489 
490     //verify metaKeyComparator's getShortMidpointKey output
491     final KVComparator metaKeyComparator = KeyValue.META_COMPARATOR;
492     kv1 = new KeyValue(Bytes.toBytes("ilovehbase123"), family, qualA, 5, Type.Put);
493     kv2 = new KeyValue(Bytes.toBytes("ilovehbase234"), family, qualA, 0, Type.Put);
494     newKey = metaKeyComparator.getShortMidpointKey(kv1.getKey(), kv2.getKey());
495     assertTrue(metaKeyComparator.compareFlatKey(kv1.getKey(), newKey) < 0);
496     assertTrue(metaKeyComparator.compareFlatKey(newKey, kv2.getKey()) == 0);
497 
498     //verify common fix scenario
499     kv1 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, ts, Type.Put);
500     kv2 = new KeyValue(Bytes.toBytes("ilovehbaseandhdfs"), family, qualA, ts, Type.Put);
501     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), kv2.getKey()) < 0);
502     newKey = keyComparator.getShortMidpointKey(kv1.getKey(), kv2.getKey());
503     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), newKey) < 0);
504     assertTrue(keyComparator.compareFlatKey(newKey, kv2.getKey()) < 0);
505     newRowLength = Bytes.toShort(newKey, 0);
506     expectedArray = Bytes.toBytes("ilovehbasea");
507     Bytes.equals(newKey, KeyValue.ROW_LENGTH_SIZE, newRowLength, expectedArray, 0,
508       expectedArray.length);
509     //verify only 1 offset scenario
510     kv1 = new KeyValue(Bytes.toBytes("100abcdefg"), family, qualA, ts, Type.Put);
511     kv2 = new KeyValue(Bytes.toBytes("101abcdefg"), family, qualA, ts, Type.Put);
512     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), kv2.getKey()) < 0);
513     newKey = keyComparator.getShortMidpointKey(kv1.getKey(), kv2.getKey());
514     assertTrue(keyComparator.compareFlatKey(kv1.getKey(), newKey) < 0);
515     assertTrue(keyComparator.compareFlatKey(newKey, kv2.getKey()) < 0);
516     newRowLength = Bytes.toShort(newKey, 0);
517     expectedArray = Bytes.toBytes("101");
518     Bytes.equals(newKey, KeyValue.ROW_LENGTH_SIZE, newRowLength, expectedArray, 0,
519       expectedArray.length);
520   }
521 
522   public void testKVsWithTags() {
523     byte[] row = Bytes.toBytes("myRow");
524     byte[] cf = Bytes.toBytes("myCF");
525     byte[] q = Bytes.toBytes("myQualifier");
526     byte[] value = Bytes.toBytes("myValue");
527     byte[] metaValue1 = Bytes.toBytes("metaValue1");
528     byte[] metaValue2 = Bytes.toBytes("metaValue2");
529     KeyValue kv = new KeyValue(row, cf, q, HConstants.LATEST_TIMESTAMP, value, new Tag[] {
530         new Tag((byte) 1, metaValue1), new Tag((byte) 2, metaValue2) });
531     assertTrue(kv.getTagsLength() > 0);
532     assertTrue(Bytes.equals(kv.getRow(), row));
533     assertTrue(Bytes.equals(kv.getFamily(), cf));
534     assertTrue(Bytes.equals(kv.getQualifier(), q));
535     assertTrue(Bytes.equals(kv.getValue(), value));
536     List<Tag> tags = kv.getTags();
537     assertNotNull(tags);
538     assertEquals(2, tags.size());
539     boolean meta1Ok = false, meta2Ok = false;
540     for (Tag tag : tags) {
541       if (tag.getType() == (byte) 1) {
542         if (Bytes.equals(tag.getValue(), metaValue1)) {
543           meta1Ok = true;
544         }
545       } else {
546         if (Bytes.equals(tag.getValue(), metaValue2)) {
547           meta2Ok = true;
548         }
549       }
550     }
551     assertTrue(meta1Ok);
552     assertTrue(meta2Ok);
553     Iterator<Tag> tagItr = CellUtil.tagsIterator(kv.getTagsArray(), kv.getTagsOffset(),
554         kv.getTagsLength());
555     //Iterator<Tag> tagItr = kv.tagsIterator();
556     assertTrue(tagItr.hasNext());
557     Tag next = tagItr.next();
558     assertEquals(10, next.getTagLength());
559     assertEquals((byte) 1, next.getType());
560     Bytes.equals(next.getValue(), metaValue1);
561     assertTrue(tagItr.hasNext());
562     next = tagItr.next();
563     assertEquals(10, next.getTagLength());
564     assertEquals((byte) 2, next.getType());
565     Bytes.equals(next.getValue(), metaValue2);
566     assertFalse(tagItr.hasNext());
567 
568     tagItr = CellUtil.tagsIterator(kv.getTagsArray(), kv.getTagsOffset(),
569         kv.getTagsLength());
570     assertTrue(tagItr.hasNext());
571     next = tagItr.next();
572     assertEquals(10, next.getTagLength());
573     assertEquals((byte) 1, next.getType());
574     Bytes.equals(next.getValue(), metaValue1);
575     assertTrue(tagItr.hasNext());
576     next = tagItr.next();
577     assertEquals(10, next.getTagLength());
578     assertEquals((byte) 2, next.getType());
579     Bytes.equals(next.getValue(), metaValue2);
580     assertFalse(tagItr.hasNext());
581   }
582   
583   public void testMetaKeyComparator() {
584     MetaComparator c = new KeyValue.MetaComparator();
585     long now = System.currentTimeMillis();
586 
587     KeyValue a = new KeyValue(Bytes.toBytes("table1"), now);
588     KeyValue b = new KeyValue(Bytes.toBytes("table2"), now);
589     assertTrue(c.compare(a, b) < 0);
590     
591     a = new KeyValue(Bytes.toBytes("table1,111"), now);
592     b = new KeyValue(Bytes.toBytes("table2"), now);
593     assertTrue(c.compare(a, b) < 0);
594     
595     a = new KeyValue(Bytes.toBytes("table1"), now);
596     b = new KeyValue(Bytes.toBytes("table2,111"), now);
597     assertTrue(c.compare(a, b) < 0);
598     
599     a = new KeyValue(Bytes.toBytes("table,111"), now);
600     b = new KeyValue(Bytes.toBytes("table,2222"), now);
601     assertTrue(c.compare(a, b) < 0);
602     
603     a = new KeyValue(Bytes.toBytes("table,111,aaaa"), now);
604     b = new KeyValue(Bytes.toBytes("table,2222"), now);
605     assertTrue(c.compare(a, b) < 0);
606     
607     a = new KeyValue(Bytes.toBytes("table,111"), now);
608     b = new KeyValue(Bytes.toBytes("table,2222.bbb"), now);
609     assertTrue(c.compare(a, b) < 0);
610 
611     a = new KeyValue(Bytes.toBytes("table,,aaaa"), now);
612     b = new KeyValue(Bytes.toBytes("table,111,bbb"), now);
613     assertTrue(c.compare(a, b) < 0);
614     
615     a = new KeyValue(Bytes.toBytes("table,111,aaaa"), now);
616     b = new KeyValue(Bytes.toBytes("table,111,bbb"), now);
617     assertTrue(c.compare(a, b) < 0);
618 
619     a = new KeyValue(Bytes.toBytes("table,111,xxxx"), now);
620     b = new KeyValue(Bytes.toBytes("table,111,222,bbb"), now);
621     assertTrue(c.compare(a, b) < 0);
622     
623     a = new KeyValue(Bytes.toBytes("table,111,11,xxx"), now);
624     b = new KeyValue(Bytes.toBytes("table,111,222,bbb"), now);
625     assertTrue(c.compare(a, b) < 0);
626   }
627 
628   public void testKeyValueSerialization() throws Exception {
629     KeyValue kvA1 = new KeyValue(Bytes.toBytes("key"), Bytes.toBytes("cf"), Bytes.toBytes("qualA"),
630         Bytes.toBytes("1"));
631     KeyValue kvA2 = new KeyValue(Bytes.toBytes("key"), Bytes.toBytes("cf"), Bytes.toBytes("qualA"),
632         Bytes.toBytes("2"));
633     MockKeyValue mkvA1 = new MockKeyValue(kvA1);
634     MockKeyValue mkvA2 = new MockKeyValue(kvA2);
635     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
636     DataOutputStream os = new DataOutputStream(byteArrayOutputStream);
637     KeyValueUtil.oswrite(mkvA1, os, true);
638     KeyValueUtil.oswrite(mkvA2, os, true);
639     DataInputStream is = new DataInputStream(new ByteArrayInputStream(
640         byteArrayOutputStream.toByteArray()));
641     KeyValue deSerKV1 = KeyValue.iscreate(is);
642     assertTrue(kvA1.equals(deSerKV1));
643     KeyValue deSerKV2 = KeyValue.iscreate(is);
644     assertTrue(kvA2.equals(deSerKV2));
645   }
646 
647   private class MockKeyValue implements Cell {
648     private final KeyValue kv;
649 
650     public MockKeyValue(KeyValue kv) {
651       this.kv = kv;
652     }
653 
654     /**
655      * This returns the offset where the tag actually starts.
656      */
657     @Override
658     public int getTagsOffset() {
659       return this.kv.getTagsOffset();
660     }
661 
662     // used to achieve atomic operations in the memstore.
663     @Override
664     public long getMvccVersion() {
665       return this.kv.getMvccVersion();
666     }
667 
668     /**
669      * used to achieve atomic operations in the memstore.
670      */
671     @Override
672     public long getSequenceId() {
673       return this.kv.getSequenceId();
674     }
675 
676     /**
677      * This returns the total length of the tag bytes
678      */
679     @Override
680     public int getTagsLength() {
681       return this.kv.getTagsLength();
682     }
683 
684     /**
685      * 
686      * @return Timestamp
687      */
688     @Override
689     public long getTimestamp() {
690       return this.kv.getTimestamp();
691     }
692 
693     /**
694      * @return KeyValue.TYPE byte representation
695      */
696     @Override
697     public byte getTypeByte() {
698       return this.kv.getTypeByte();
699     }
700 
701     /**
702      * @return the backing array of the entire KeyValue (all KeyValue fields are
703      *         in a single array)
704      */
705     @Override
706     public byte[] getValueArray() {
707       return this.kv.getValueArray();
708     }
709 
710     /**
711      * @return the value offset
712      */
713     @Override
714     public int getValueOffset() {
715       return this.kv.getValueOffset();
716     }
717 
718     /**
719      * @return Value length
720      */
721     @Override
722     public int getValueLength() {
723       return this.kv.getValueLength();
724     }
725 
726     /**
727      * @return the backing array of the entire KeyValue (all KeyValue fields are
728      *         in a single array)
729      */
730     @Override
731     public byte[] getRowArray() {
732       return this.kv.getRowArray();
733     }
734 
735     /**
736      * @return Row offset
737      */
738     @Override
739     public int getRowOffset() {
740       return this.kv.getRowOffset();
741     }
742 
743     /**
744      * @return Row length
745      */
746     @Override
747     public short getRowLength() {
748       return this.kv.getRowLength();
749     }
750 
751     /**
752      * @return the backing array of the entire KeyValue (all KeyValue fields are
753      *         in a single array)
754      */
755     @Override
756     public byte[] getFamilyArray() {
757       return this.kv.getFamilyArray();
758     }
759 
760     /**
761      * @return Family offset
762      */
763     @Override
764     public int getFamilyOffset() {
765       return this.kv.getFamilyOffset();
766     }
767 
768     /**
769      * @return Family length
770      */
771     @Override
772     public byte getFamilyLength() {
773       return this.kv.getFamilyLength();
774     }
775 
776     /**
777      * @return the backing array of the entire KeyValue (all KeyValue fields are
778      *         in a single array)
779      */
780     @Override
781     public byte[] getQualifierArray() {
782       return this.kv.getQualifierArray();
783     }
784 
785     /**
786      * @return Qualifier offset
787      */
788     @Override
789     public int getQualifierOffset() {
790       return this.kv.getQualifierOffset();
791     }
792 
793     /**
794      * @return Qualifier length
795      */
796     @Override
797     public int getQualifierLength() {
798       return this.kv.getQualifierLength();
799     }
800 
801     @Override
802     @Deprecated
803     public byte[] getValue() {
804       // TODO Auto-generated method stub
805       return null;
806     }
807 
808     @Override
809     @Deprecated
810     public byte[] getFamily() {
811       // TODO Auto-generated method stub
812       return null;
813     }
814 
815     @Override
816     @Deprecated
817     public byte[] getQualifier() {
818       // TODO Auto-generated method stub
819       return null;
820     }
821 
822     @Override
823     @Deprecated
824     public byte[] getRow() {
825       // TODO Auto-generated method stub
826       return null;
827     }
828 
829     /**
830      * @return the backing array of the entire KeyValue (all KeyValue fields are
831      *         in a single array)
832      */
833     @Override
834     public byte[] getTagsArray() {
835       return this.kv.getTagsArray();
836     }
837   }
838 
839   public void testEqualsAndHashCode() throws Exception {
840     KeyValue kvA1 = new KeyValue(Bytes.toBytes("key"), Bytes.toBytes("cf"),
841         Bytes.toBytes("qualA"), Bytes.toBytes("1"));
842     KeyValue kvA2 = new KeyValue(Bytes.toBytes("key"), Bytes.toBytes("cf"),
843         Bytes.toBytes("qualA"), Bytes.toBytes("2"));
844     // We set a different sequence id on kvA2 to demonstrate that the equals and hashCode also
845     // don't take this into account.
846     kvA2.setSequenceId(2);
847     KeyValue kvB = new KeyValue(Bytes.toBytes("key"), Bytes.toBytes("cf"),
848         Bytes.toBytes("qualB"), Bytes.toBytes("1"));
849 
850     assertEquals(kvA1, kvA2);
851     assertNotEquals(kvA1, kvB);
852     assertEquals(kvA1.hashCode(), kvA2.hashCode());
853     assertNotEquals(kvA1.hashCode(), kvB.hashCode());
854   }
855 
856   @Test
857   public void testRawBytesComparator() {
858     long ts = System.currentTimeMillis();
859     byte[] key = Bytes.toBytes("key");
860     byte[] cf = Bytes.toBytes("cf");
861     byte[] qualifier = Bytes.toBytes("qualifier");
862     byte[] value = Bytes.toBytes("value");
863     KeyValue kvA1 = new KeyValue(key, cf, qualifier, ts, Type.Put, value);
864     KeyValue kvA2 = new KeyValue(key, cf, qualifier, ts, Type.DeleteFamily, value);
865     assertTrue(KeyValue.RAW_COMPARATOR.compare(kvA1, kvA2) > 0);
866   }
867 }