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 static org.junit.Assert.assertArrayEquals;
22  import static org.junit.Assert.assertEquals;
23  import static org.junit.Assert.assertFalse;
24  import static org.junit.Assert.assertNotNull;
25  import static org.junit.Assert.assertNull;
26  import static org.junit.Assert.assertSame;
27  import static org.junit.Assert.assertTrue;
28  import static org.junit.Assert.fail;
29  
30  import java.io.IOException;
31  import java.lang.reflect.Method;
32  import java.util.ArrayList;
33  import java.util.Arrays;
34  import java.util.Collections;
35  import java.util.HashSet;
36  import java.util.Iterator;
37  import java.util.List;
38  import java.util.Map;
39  import java.util.NavigableMap;
40  import java.util.UUID;
41  import java.util.concurrent.Callable;
42  import java.util.concurrent.ExecutorService;
43  import java.util.concurrent.Executors;
44  import java.util.concurrent.atomic.AtomicReference;
45  
46  import org.apache.log4j.Level;
47  import org.apache.commons.lang.ArrayUtils;
48  import org.apache.commons.logging.Log;
49  import org.apache.commons.logging.LogFactory;
50  import org.apache.hadoop.conf.Configuration;
51  import org.apache.hadoop.hbase.Abortable;
52  import org.apache.hadoop.hbase.Cell;
53  import org.apache.hadoop.hbase.CellUtil;
54  import org.apache.hadoop.hbase.DoNotRetryIOException;
55  import org.apache.hadoop.hbase.HBaseTestingUtility;
56  import org.apache.hadoop.hbase.HColumnDescriptor;
57  import org.apache.hadoop.hbase.HConstants;
58  import org.apache.hadoop.hbase.HRegionInfo;
59  import org.apache.hadoop.hbase.HRegionLocation;
60  import org.apache.hadoop.hbase.HTableDescriptor;
61  import org.apache.hadoop.hbase.KeyValue;
62  import org.apache.hadoop.hbase.MiniHBaseCluster;
63  import org.apache.hadoop.hbase.RegionLocations;
64  import org.apache.hadoop.hbase.ServerName;
65  import org.apache.hadoop.hbase.TableName;
66  import org.apache.hadoop.hbase.Waiter;
67  import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
68  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
69  import org.apache.hadoop.hbase.coprocessor.MultiRowMutationEndpoint;
70  import org.apache.hadoop.hbase.filter.BinaryComparator;
71  import org.apache.hadoop.hbase.filter.CompareFilter;
72  import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
73  import org.apache.hadoop.hbase.filter.Filter;
74  import org.apache.hadoop.hbase.filter.FilterList;
75  import org.apache.hadoop.hbase.filter.KeyOnlyFilter;
76  import org.apache.hadoop.hbase.filter.LongComparator;
77  import org.apache.hadoop.hbase.filter.PrefixFilter;
78  import org.apache.hadoop.hbase.filter.QualifierFilter;
79  import org.apache.hadoop.hbase.filter.RegexStringComparator;
80  import org.apache.hadoop.hbase.filter.RowFilter;
81  import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
82  import org.apache.hadoop.hbase.filter.WhileMatchFilter;
83  import org.apache.hadoop.hbase.io.hfile.BlockCache;
84  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
85  import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
86  import org.apache.hadoop.hbase.master.HMaster;
87  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
88  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos;
89  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto;
90  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
91  import org.apache.hadoop.hbase.protobuf.generated.MultiRowMutationProtos.MultiRowMutationService;
92  import org.apache.hadoop.hbase.protobuf.generated.MultiRowMutationProtos.MutateRowsRequest;
93  import org.apache.hadoop.hbase.regionserver.HRegion;
94  import org.apache.hadoop.hbase.regionserver.HRegionServer;
95  import org.apache.hadoop.hbase.regionserver.NoSuchColumnFamilyException;
96  import org.apache.hadoop.hbase.regionserver.Region;
97  import org.apache.hadoop.hbase.regionserver.Store;
98  import org.apache.hadoop.hbase.testclassification.LargeTests;
99  import org.apache.hadoop.hbase.util.Bytes;
100 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
101 import org.apache.hadoop.hbase.util.Pair;
102 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
103 import org.apache.log4j.AppenderSkeleton;
104 import org.apache.log4j.Logger;
105 import org.apache.log4j.spi.LoggingEvent;
106 import org.junit.After;
107 import org.junit.AfterClass;
108 import org.junit.Before;
109 import org.junit.BeforeClass;
110 import org.junit.Ignore;
111 import org.junit.Test;
112 import org.junit.experimental.categories.Category;
113 /**
114  * Run tests that use the HBase clients; {@link HTable}.
115  * Sets up the HBase mini cluster once at start and runs through all client tests.
116  * Each creates a table named for the method and does its stuff against that.
117  */
118 @Category(LargeTests.class)
119 @SuppressWarnings ("deprecation")
120 public class TestFromClientSide {
121   final Log LOG = LogFactory.getLog(getClass());
122   protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
123   private static byte [] ROW = Bytes.toBytes("testRow");
124   private static byte [] FAMILY = Bytes.toBytes("testFamily");
125   private static byte [] QUALIFIER = Bytes.toBytes("testQualifier");
126   private static byte [] VALUE = Bytes.toBytes("testValue");
127   protected static int SLAVES = 3;
128 
129   /**
130    * @throws java.lang.Exception
131    */
132   @BeforeClass
133   public static void setUpBeforeClass() throws Exception {
134     // Uncomment the following lines if more verbosity is needed for
135     // debugging (see HBASE-12285 for details).
136     //((Log4JLogger)RpcServer.LOG).getLogger().setLevel(Level.ALL);
137     //((Log4JLogger)RpcClient.LOG).getLogger().setLevel(Level.ALL);
138     //((Log4JLogger)ScannerCallable.LOG).getLogger().setLevel(Level.ALL);
139     Configuration conf = TEST_UTIL.getConfiguration();
140     conf.setStrings(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
141         MultiRowMutationEndpoint.class.getName());
142     conf.setBoolean("hbase.table.sanity.checks", true); // enable for below tests
143     // We need more than one region server in this test
144     TEST_UTIL.startMiniCluster(SLAVES);
145   }
146 
147   /**
148    * @throws java.lang.Exception
149    */
150   @AfterClass
151   public static void tearDownAfterClass() throws Exception {
152     TEST_UTIL.shutdownMiniCluster();
153   }
154 
155   /**
156    * @throws java.lang.Exception
157    */
158   @Before
159   public void setUp() throws Exception {
160     // Nothing to do.
161   }
162 
163   /**
164    * @throws java.lang.Exception
165    */
166   @After
167   public void tearDown() throws Exception {
168     // Nothing to do.
169   }
170 
171   /**
172    * Basic client side validation of HBASE-4536
173    */
174    @Test
175    public void testKeepDeletedCells() throws Exception {
176      final TableName TABLENAME = TableName.valueOf("testKeepDeletesCells");
177      final byte[] FAMILY = Bytes.toBytes("family");
178      final byte[] C0 = Bytes.toBytes("c0");
179 
180      final byte[] T1 = Bytes.toBytes("T1");
181      final byte[] T2 = Bytes.toBytes("T2");
182      final byte[] T3 = Bytes.toBytes("T3");
183      HColumnDescriptor hcd = new HColumnDescriptor(FAMILY)
184          .setKeepDeletedCells(true).setMaxVersions(3);
185 
186      HTableDescriptor desc = new HTableDescriptor(TABLENAME);
187      desc.addFamily(hcd);
188      TEST_UTIL.getHBaseAdmin().createTable(desc);
189      Configuration c = TEST_UTIL.getConfiguration();
190      Table h = new HTable(c, TABLENAME);
191 
192      long ts = System.currentTimeMillis();
193      Put p = new Put(T1, ts);
194      p.add(FAMILY, C0, T1);
195      h.put(p);
196      p = new Put(T1, ts+2);
197      p.add(FAMILY, C0, T2);
198      h.put(p);
199      p = new Put(T1, ts+4);
200      p.add(FAMILY, C0, T3);
201      h.put(p);
202 
203      Delete d = new Delete(T1, ts+3);
204      h.delete(d);
205 
206      d = new Delete(T1, ts+3);
207      d.deleteColumns(FAMILY, C0, ts+3);
208      h.delete(d);
209 
210      Get g = new Get(T1);
211      // does *not* include the delete
212      g.setTimeRange(0, ts+3);
213      Result r = h.get(g);
214      assertArrayEquals(T2, r.getValue(FAMILY, C0));
215 
216      Scan s = new Scan(T1);
217      s.setTimeRange(0, ts+3);
218      s.setMaxVersions();
219      ResultScanner scanner = h.getScanner(s);
220      Cell[] kvs = scanner.next().rawCells();
221      assertArrayEquals(T2, CellUtil.cloneValue(kvs[0]));
222      assertArrayEquals(T1, CellUtil.cloneValue(kvs[1]));
223      scanner.close();
224 
225      s = new Scan(T1);
226      s.setRaw(true);
227      s.setMaxVersions();
228      scanner = h.getScanner(s);
229      kvs = scanner.next().rawCells();
230      assertTrue(CellUtil.isDeleteFamily(kvs[0]));
231      assertArrayEquals(T3, CellUtil.cloneValue(kvs[1]));
232      assertTrue(CellUtil.isDelete(kvs[2]));
233      assertArrayEquals(T2, CellUtil.cloneValue(kvs[3]));
234      assertArrayEquals(T1, CellUtil.cloneValue(kvs[4]));
235      scanner.close();
236      h.close();
237    }
238 
239     /**
240     * Basic client side validation of HBASE-10118
241     */
242    @Test
243    public void testPurgeFutureDeletes() throws Exception {
244      final TableName TABLENAME = TableName.valueOf("testPurgeFutureDeletes");
245      final byte[] ROW = Bytes.toBytes("row");
246      final byte[] FAMILY = Bytes.toBytes("family");
247      final byte[] COLUMN = Bytes.toBytes("column");
248      final byte[] VALUE = Bytes.toBytes("value");
249 
250      Table table = TEST_UTIL.createTable(TABLENAME, FAMILY);
251 
252      // future timestamp
253      long ts = System.currentTimeMillis() * 2;
254      Put put = new Put(ROW, ts);
255      put.add(FAMILY, COLUMN, VALUE);
256      table.put(put);
257 
258      Get get = new Get(ROW);
259      Result result = table.get(get);
260      assertArrayEquals(VALUE, result.getValue(FAMILY, COLUMN));
261 
262      Delete del = new Delete(ROW);
263      del.deleteColumn(FAMILY, COLUMN, ts);
264      table.delete(del);
265 
266      get = new Get(ROW);
267      result = table.get(get);
268      assertNull(result.getValue(FAMILY, COLUMN));
269 
270      // major compaction, purged future deletes
271      TEST_UTIL.getHBaseAdmin().flush(TABLENAME);
272      TEST_UTIL.getHBaseAdmin().majorCompact(TABLENAME);
273 
274      // waiting for the major compaction to complete
275      TEST_UTIL.waitFor(6000, new Waiter.Predicate<IOException>() {
276        @Override
277        public boolean evaluate() throws IOException {
278          return TEST_UTIL.getHBaseAdmin().getCompactionState(TABLENAME) ==
279              AdminProtos.GetRegionInfoResponse.CompactionState.NONE;
280        }
281      });
282 
283      put = new Put(ROW, ts);
284      put.add(FAMILY, COLUMN, VALUE);
285      table.put(put);
286 
287      get = new Get(ROW);
288      result = table.get(get);
289      assertArrayEquals(VALUE, result.getValue(FAMILY, COLUMN));
290 
291      table.close();
292    }
293 
294    /**
295     * @deprecated Tests deprecated functionality. Remove when we are past 1.0.
296     * @throws Exception
297     */
298    @Deprecated
299    @Test
300    public void testSharedZooKeeper() throws Exception {
301      Configuration newConfig = new Configuration(TEST_UTIL.getConfiguration());
302      newConfig.set(HConstants.HBASE_CLIENT_INSTANCE_ID, "12345");
303 
304      // First with a simple ZKW
305      ZooKeeperWatcher z0 = new ZooKeeperWatcher(
306        newConfig, "hconnection", new Abortable() {
307        @Override public void abort(String why, Throwable e) {}
308        @Override public boolean isAborted() {return false;}
309      });
310      z0.getRecoverableZooKeeper().getZooKeeper().exists("/oldZooKeeperWatcher", false);
311      z0.close();
312 
313      // Then a ZooKeeperKeepAliveConnection
314      ConnectionManager.HConnectionImplementation connection1 =
315        (ConnectionManager.HConnectionImplementation)
316          HConnectionManager.getConnection(newConfig);
317 
318      ZooKeeperKeepAliveConnection z1 = connection1.getKeepAliveZooKeeperWatcher();
319      z1.getRecoverableZooKeeper().getZooKeeper().exists("/z1", false);
320 
321      z1.close();
322 
323      // will still work, because the real connection is not closed yet
324      // Not do be done in real code
325      z1.getRecoverableZooKeeper().getZooKeeper().exists("/z1afterclose", false);
326 
327 
328      ZooKeeperKeepAliveConnection z2 = connection1.getKeepAliveZooKeeperWatcher();
329      assertTrue(
330        "ZooKeeperKeepAliveConnection equals on same connection", z1 == z2);
331 
332 
333 
334      Configuration newConfig2 = new Configuration(TEST_UTIL.getConfiguration());
335      newConfig2.set(HConstants.HBASE_CLIENT_INSTANCE_ID, "6789");
336      ConnectionManager.HConnectionImplementation connection2 =
337        (ConnectionManager.HConnectionImplementation)
338          HConnectionManager.getConnection(newConfig2);
339 
340      assertTrue("connections should be different ", connection1 != connection2);
341 
342      ZooKeeperKeepAliveConnection z3 = connection2.getKeepAliveZooKeeperWatcher();
343      assertTrue(
344        "ZooKeeperKeepAliveConnection should be different" +
345          " on different connections", z1 != z3);
346 
347      // Bypass the private access
348      Method m = ConnectionManager.HConnectionImplementation.class.
349        getDeclaredMethod("closeZooKeeperWatcher");
350      m.setAccessible(true);
351      m.invoke(connection2);
352 
353      ZooKeeperKeepAliveConnection z4 = connection2.getKeepAliveZooKeeperWatcher();
354      assertTrue(
355        "ZooKeeperKeepAliveConnection should be recreated" +
356          " when previous connections was closed"
357        , z3 != z4);
358 
359 
360      z2.getRecoverableZooKeeper().getZooKeeper().exists("/z2", false);
361      z4.getRecoverableZooKeeper().getZooKeeper().exists("/z4", false);
362 
363 
364      HConnectionManager.deleteConnection(newConfig);
365      try {
366        z2.getRecoverableZooKeeper().getZooKeeper().exists("/z2", false);
367        assertTrue("We should not have a valid connection for z2", false);
368      } catch (Exception e){
369      }
370 
371      z4.getRecoverableZooKeeper().getZooKeeper().exists("/z4", false);
372      // We expect success here.
373 
374 
375      HConnectionManager.deleteConnection(newConfig2);
376      try {
377        z4.getRecoverableZooKeeper().getZooKeeper().exists("/z4", false);
378        assertTrue("We should not have a valid connection for z4", false);
379      } catch (Exception e){
380      }
381    }
382 
383 
384   /**
385    * Verifies that getConfiguration returns the same Configuration object used
386    * to create the HTable instance.
387    */
388   @Test
389   public void testGetConfiguration() throws Exception {
390     TableName TABLE = TableName.valueOf("testGetConfiguration");
391     byte[][] FAMILIES = new byte[][] { Bytes.toBytes("foo") };
392     Configuration conf = TEST_UTIL.getConfiguration();
393     Table table = TEST_UTIL.createTable(TABLE, FAMILIES, conf);
394     assertSame(conf, table.getConfiguration());
395   }
396 
397   /**
398    * Test from client side of an involved filter against a multi family that
399    * involves deletes.
400    *
401    * @throws Exception
402    */
403   @Test
404   public void testWeirdCacheBehaviour() throws Exception {
405     TableName TABLE = TableName.valueOf("testWeirdCacheBehaviour");
406     byte [][] FAMILIES = new byte[][] { Bytes.toBytes("trans-blob"),
407         Bytes.toBytes("trans-type"), Bytes.toBytes("trans-date"),
408         Bytes.toBytes("trans-tags"), Bytes.toBytes("trans-group") };
409     HTable ht = TEST_UTIL.createTable(TABLE, FAMILIES);
410     String value = "this is the value";
411     String value2 = "this is some other value";
412     String keyPrefix1 = UUID.randomUUID().toString();
413     String keyPrefix2 = UUID.randomUUID().toString();
414     String keyPrefix3 = UUID.randomUUID().toString();
415     putRows(ht, 3, value, keyPrefix1);
416     putRows(ht, 3, value, keyPrefix2);
417     putRows(ht, 3, value, keyPrefix3);
418     ht.flushCommits();
419     putRows(ht, 3, value2, keyPrefix1);
420     putRows(ht, 3, value2, keyPrefix2);
421     putRows(ht, 3, value2, keyPrefix3);
422     Table table = new HTable(TEST_UTIL.getConfiguration(), TABLE);
423     System.out.println("Checking values for key: " + keyPrefix1);
424     assertEquals("Got back incorrect number of rows from scan", 3,
425         getNumberOfRows(keyPrefix1, value2, table));
426     System.out.println("Checking values for key: " + keyPrefix2);
427     assertEquals("Got back incorrect number of rows from scan", 3,
428         getNumberOfRows(keyPrefix2, value2, table));
429     System.out.println("Checking values for key: " + keyPrefix3);
430     assertEquals("Got back incorrect number of rows from scan", 3,
431         getNumberOfRows(keyPrefix3, value2, table));
432     deleteColumns(ht, value2, keyPrefix1);
433     deleteColumns(ht, value2, keyPrefix2);
434     deleteColumns(ht, value2, keyPrefix3);
435     System.out.println("Starting important checks.....");
436     assertEquals("Got back incorrect number of rows from scan: " + keyPrefix1,
437       0, getNumberOfRows(keyPrefix1, value2, table));
438     assertEquals("Got back incorrect number of rows from scan: " + keyPrefix2,
439       0, getNumberOfRows(keyPrefix2, value2, table));
440     assertEquals("Got back incorrect number of rows from scan: " + keyPrefix3,
441       0, getNumberOfRows(keyPrefix3, value2, table));
442     ht.setScannerCaching(0);
443     assertEquals("Got back incorrect number of rows from scan", 0,
444       getNumberOfRows(keyPrefix1, value2, table)); ht.setScannerCaching(100);
445     assertEquals("Got back incorrect number of rows from scan", 0,
446       getNumberOfRows(keyPrefix2, value2, table));
447   }
448 
449   private void deleteColumns(Table ht, String value, String keyPrefix)
450   throws IOException {
451     ResultScanner scanner = buildScanner(keyPrefix, value, ht);
452     Iterator<Result> it = scanner.iterator();
453     int count = 0;
454     while (it.hasNext()) {
455       Result result = it.next();
456       Delete delete = new Delete(result.getRow());
457       delete.deleteColumn(Bytes.toBytes("trans-tags"), Bytes.toBytes("qual2"));
458       ht.delete(delete);
459       count++;
460     }
461     assertEquals("Did not perform correct number of deletes", 3, count);
462   }
463 
464   private int getNumberOfRows(String keyPrefix, String value, Table ht)
465       throws Exception {
466     ResultScanner resultScanner = buildScanner(keyPrefix, value, ht);
467     Iterator<Result> scanner = resultScanner.iterator();
468     int numberOfResults = 0;
469     while (scanner.hasNext()) {
470       Result result = scanner.next();
471       System.out.println("Got back key: " + Bytes.toString(result.getRow()));
472       for (Cell kv : result.rawCells()) {
473         System.out.println("kv=" + kv.toString() + ", "
474             + Bytes.toString(CellUtil.cloneValue(kv)));
475       }
476       numberOfResults++;
477     }
478     return numberOfResults;
479   }
480 
481   private ResultScanner buildScanner(String keyPrefix, String value, Table ht)
482       throws IOException {
483     // OurFilterList allFilters = new OurFilterList();
484     FilterList allFilters = new FilterList(/* FilterList.Operator.MUST_PASS_ALL */);
485     allFilters.addFilter(new PrefixFilter(Bytes.toBytes(keyPrefix)));
486     SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes
487         .toBytes("trans-tags"), Bytes.toBytes("qual2"), CompareOp.EQUAL, Bytes
488         .toBytes(value));
489     filter.setFilterIfMissing(true);
490     allFilters.addFilter(filter);
491 
492     // allFilters.addFilter(new
493     // RowExcludingSingleColumnValueFilter(Bytes.toBytes("trans-tags"),
494     // Bytes.toBytes("qual2"), CompareOp.EQUAL, Bytes.toBytes(value)));
495 
496     Scan scan = new Scan();
497     scan.addFamily(Bytes.toBytes("trans-blob"));
498     scan.addFamily(Bytes.toBytes("trans-type"));
499     scan.addFamily(Bytes.toBytes("trans-date"));
500     scan.addFamily(Bytes.toBytes("trans-tags"));
501     scan.addFamily(Bytes.toBytes("trans-group"));
502     scan.setFilter(allFilters);
503 
504     return ht.getScanner(scan);
505   }
506 
507   private void putRows(Table ht, int numRows, String value, String key)
508       throws IOException {
509     for (int i = 0; i < numRows; i++) {
510       String row = key + "_" + UUID.randomUUID().toString();
511       System.out.println(String.format("Saving row: %s, with value %s", row,
512           value));
513       Put put = new Put(Bytes.toBytes(row));
514       put.setDurability(Durability.SKIP_WAL);
515       put.add(Bytes.toBytes("trans-blob"), null, Bytes
516           .toBytes("value for blob"));
517       put.add(Bytes.toBytes("trans-type"), null, Bytes.toBytes("statement"));
518       put.add(Bytes.toBytes("trans-date"), null, Bytes
519           .toBytes("20090921010101999"));
520       put.add(Bytes.toBytes("trans-tags"), Bytes.toBytes("qual2"), Bytes
521           .toBytes(value));
522       put.add(Bytes.toBytes("trans-group"), null, Bytes
523           .toBytes("adhocTransactionGroupId"));
524       ht.put(put);
525     }
526   }
527 
528   /**
529    * Test filters when multiple regions.  It does counts.  Needs eye-balling of
530    * logs to ensure that we're not scanning more regions that we're supposed to.
531    * Related to the TestFilterAcrossRegions over in the o.a.h.h.filter package.
532    * @throws IOException
533    * @throws InterruptedException
534    */
535   @Test
536   public void testFilterAcrossMultipleRegions()
537   throws IOException, InterruptedException {
538     TableName name = TableName.valueOf("testFilterAcrossMutlipleRegions");
539     HTable t = TEST_UTIL.createTable(name, FAMILY);
540     int rowCount = TEST_UTIL.loadTable(t, FAMILY, false);
541     assertRowCount(t, rowCount);
542     // Split the table.  Should split on a reasonable key; 'lqj'
543     Map<HRegionInfo, ServerName> regions  = splitTable(t);
544     assertRowCount(t, rowCount);
545     // Get end key of first region.
546     byte [] endKey = regions.keySet().iterator().next().getEndKey();
547     // Count rows with a filter that stops us before passed 'endKey'.
548     // Should be count of rows in first region.
549     int endKeyCount = countRows(t, createScanWithRowFilter(endKey));
550     assertTrue(endKeyCount < rowCount);
551 
552     // How do I know I did not got to second region?  Thats tough.  Can't really
553     // do that in client-side region test.  I verified by tracing in debugger.
554     // I changed the messages that come out when set to DEBUG so should see
555     // when scanner is done. Says "Finished with scanning..." with region name.
556     // Check that its finished in right region.
557 
558     // New test.  Make it so scan goes into next region by one and then two.
559     // Make sure count comes out right.
560     byte [] key = new byte [] {endKey[0], endKey[1], (byte)(endKey[2] + 1)};
561     int plusOneCount = countRows(t, createScanWithRowFilter(key));
562     assertEquals(endKeyCount + 1, plusOneCount);
563     key = new byte [] {endKey[0], endKey[1], (byte)(endKey[2] + 2)};
564     int plusTwoCount = countRows(t, createScanWithRowFilter(key));
565     assertEquals(endKeyCount + 2, plusTwoCount);
566 
567     // New test.  Make it so I scan one less than endkey.
568     key = new byte [] {endKey[0], endKey[1], (byte)(endKey[2] - 1)};
569     int minusOneCount = countRows(t, createScanWithRowFilter(key));
570     assertEquals(endKeyCount - 1, minusOneCount);
571     // For above test... study logs.  Make sure we do "Finished with scanning.."
572     // in first region and that we do not fall into the next region.
573 
574     key = new byte [] {'a', 'a', 'a'};
575     int countBBB = countRows(t,
576       createScanWithRowFilter(key, null, CompareFilter.CompareOp.EQUAL));
577     assertEquals(1, countBBB);
578 
579     int countGreater = countRows(t, createScanWithRowFilter(endKey, null,
580       CompareFilter.CompareOp.GREATER_OR_EQUAL));
581     // Because started at start of table.
582     assertEquals(0, countGreater);
583     countGreater = countRows(t, createScanWithRowFilter(endKey, endKey,
584       CompareFilter.CompareOp.GREATER_OR_EQUAL));
585     assertEquals(rowCount - endKeyCount, countGreater);
586   }
587 
588   /*
589    * @param key
590    * @return Scan with RowFilter that does LESS than passed key.
591    */
592   private Scan createScanWithRowFilter(final byte [] key) {
593     return createScanWithRowFilter(key, null, CompareFilter.CompareOp.LESS);
594   }
595 
596   /*
597    * @param key
598    * @param op
599    * @param startRow
600    * @return Scan with RowFilter that does CompareOp op on passed key.
601    */
602   private Scan createScanWithRowFilter(final byte [] key,
603       final byte [] startRow, CompareFilter.CompareOp op) {
604     // Make sure key is of some substance... non-null and > than first key.
605     assertTrue(key != null && key.length > 0 &&
606       Bytes.BYTES_COMPARATOR.compare(key, new byte [] {'a', 'a', 'a'}) >= 0);
607     LOG.info("Key=" + Bytes.toString(key));
608     Scan s = startRow == null? new Scan(): new Scan(startRow);
609     Filter f = new RowFilter(op, new BinaryComparator(key));
610     f = new WhileMatchFilter(f);
611     s.setFilter(f);
612     return s;
613   }
614 
615   /*
616    * @param t
617    * @param s
618    * @return Count of rows in table.
619    * @throws IOException
620    */
621   private int countRows(final Table t, final Scan s)
622   throws IOException {
623     // Assert all rows in table.
624     ResultScanner scanner = t.getScanner(s);
625     int count = 0;
626     for (Result result: scanner) {
627       count++;
628       assertTrue(result.size() > 0);
629       // LOG.info("Count=" + count + ", row=" + Bytes.toString(result.getRow()));
630     }
631     return count;
632   }
633 
634   private void assertRowCount(final Table t, final int expected)
635   throws IOException {
636     assertEquals(expected, countRows(t, new Scan()));
637   }
638 
639   /*
640    * Split table into multiple regions.
641    * @param t Table to split.
642    * @return Map of regions to servers.
643    * @throws IOException
644    */
645   private Map<HRegionInfo, ServerName> splitTable(final HTable t)
646   throws IOException, InterruptedException {
647     // Split this table in two.
648     HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
649     admin.split(t.getTableName());
650     admin.close();
651     Map<HRegionInfo, ServerName> regions = waitOnSplit(t);
652     assertTrue(regions.size() > 1);
653     return regions;
654   }
655 
656   /*
657    * Wait on table split.  May return because we waited long enough on the split
658    * and it didn't happen.  Caller should check.
659    * @param t
660    * @return Map of table regions; caller needs to check table actually split.
661    */
662   private Map<HRegionInfo, ServerName> waitOnSplit(final HTable t)
663   throws IOException {
664     Map<HRegionInfo, ServerName> regions = t.getRegionLocations();
665     int originalCount = regions.size();
666     for (int i = 0; i < TEST_UTIL.getConfiguration().getInt("hbase.test.retries", 30); i++) {
667       Thread.currentThread();
668       try {
669         Thread.sleep(1000);
670       } catch (InterruptedException e) {
671         e.printStackTrace();
672       }
673       regions = t.getRegionLocations();
674       if (regions.size() > originalCount) break;
675     }
676     return regions;
677   }
678 
679   @Test
680   public void testSuperSimple() throws Exception {
681     byte [] TABLE = Bytes.toBytes("testSuperSimple");
682     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
683     Put put = new Put(ROW);
684     put.add(FAMILY, QUALIFIER, VALUE);
685     ht.put(put);
686     Scan scan = new Scan();
687     scan.addColumn(FAMILY, TABLE);
688     ResultScanner scanner = ht.getScanner(scan);
689     Result result = scanner.next();
690     assertTrue("Expected null result", result == null);
691     scanner.close();
692   }
693 
694   @Test
695   public void testMaxKeyValueSize() throws Exception {
696     byte [] TABLE = Bytes.toBytes("testMaxKeyValueSize");
697     Configuration conf = TEST_UTIL.getConfiguration();
698     String oldMaxSize = conf.get(TableConfiguration.MAX_KEYVALUE_SIZE_KEY);
699     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
700     byte[] value = new byte[4 * 1024 * 1024];
701     Put put = new Put(ROW);
702     put.add(FAMILY, QUALIFIER, value);
703     ht.put(put);
704     try {
705       TEST_UTIL.getConfiguration().setInt(
706           TableConfiguration.MAX_KEYVALUE_SIZE_KEY, 2 * 1024 * 1024);
707       // Create new table so we pick up the change in Configuration.
708       try (Connection connection =
709           ConnectionFactory.createConnection(TEST_UTIL.getConfiguration())) {
710         try (Table t = connection.getTable(TableName.valueOf(FAMILY))) {
711           put = new Put(ROW);
712           put.add(FAMILY, QUALIFIER, value);
713           t.put(put);
714         }
715       }
716       fail("Inserting a too large KeyValue worked, should throw exception");
717     } catch(Exception e) {}
718     conf.set(TableConfiguration.MAX_KEYVALUE_SIZE_KEY, oldMaxSize);
719   }
720 
721   @Test
722   public void testFilters() throws Exception {
723     byte [] TABLE = Bytes.toBytes("testFilters");
724     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
725     byte [][] ROWS = makeN(ROW, 10);
726     byte [][] QUALIFIERS = {
727         Bytes.toBytes("col0-<d2v1>-<d3v2>"), Bytes.toBytes("col1-<d2v1>-<d3v2>"),
728         Bytes.toBytes("col2-<d2v1>-<d3v2>"), Bytes.toBytes("col3-<d2v1>-<d3v2>"),
729         Bytes.toBytes("col4-<d2v1>-<d3v2>"), Bytes.toBytes("col5-<d2v1>-<d3v2>"),
730         Bytes.toBytes("col6-<d2v1>-<d3v2>"), Bytes.toBytes("col7-<d2v1>-<d3v2>"),
731         Bytes.toBytes("col8-<d2v1>-<d3v2>"), Bytes.toBytes("col9-<d2v1>-<d3v2>")
732     };
733     for(int i=0;i<10;i++) {
734       Put put = new Put(ROWS[i]);
735       put.setDurability(Durability.SKIP_WAL);
736       put.add(FAMILY, QUALIFIERS[i], VALUE);
737       ht.put(put);
738     }
739     Scan scan = new Scan();
740     scan.addFamily(FAMILY);
741     Filter filter = new QualifierFilter(CompareOp.EQUAL,
742       new RegexStringComparator("col[1-5]"));
743     scan.setFilter(filter);
744     ResultScanner scanner = ht.getScanner(scan);
745     int expectedIndex = 1;
746     for(Result result : ht.getScanner(scan)) {
747       assertEquals(result.size(), 1);
748       assertTrue(Bytes.equals(CellUtil.cloneRow(result.rawCells()[0]), ROWS[expectedIndex]));
749       assertTrue(Bytes.equals(CellUtil.cloneQualifier(result.rawCells()[0]),
750           QUALIFIERS[expectedIndex]));
751       expectedIndex++;
752     }
753     assertEquals(expectedIndex, 6);
754     scanner.close();
755   }
756 
757   @Test
758   public void testFilterWithLongCompartor() throws Exception {
759     byte [] TABLE = Bytes.toBytes("testFilterWithLongCompartor");
760     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
761     byte [][] ROWS = makeN(ROW, 10);
762     byte [][] values = new byte[10][];
763     for (int i = 0; i < 10; i ++) {
764         values[i] = Bytes.toBytes(100L * i);
765     }
766     for(int i = 0; i < 10; i ++) {
767       Put put = new Put(ROWS[i]);
768       put.setDurability(Durability.SKIP_WAL);
769       put.add(FAMILY, QUALIFIER, values[i]);
770       ht.put(put);
771     }
772     Scan scan = new Scan();
773     scan.addFamily(FAMILY);
774     Filter filter = new SingleColumnValueFilter(FAMILY, QUALIFIER, CompareOp.GREATER,
775       new LongComparator(500));
776     scan.setFilter(filter);
777     ResultScanner scanner = ht.getScanner(scan);
778     int expectedIndex = 0;
779     for(Result result : ht.getScanner(scan)) {
780       assertEquals(result.size(), 1);
781       assertTrue(Bytes.toLong(result.getValue(FAMILY, QUALIFIER)) > 500);
782       expectedIndex++;
783     }
784     assertEquals(expectedIndex, 4);
785     scanner.close();
786 }
787 
788   @Test
789   public void testKeyOnlyFilter() throws Exception {
790     byte [] TABLE = Bytes.toBytes("testKeyOnlyFilter");
791     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
792     byte [][] ROWS = makeN(ROW, 10);
793     byte [][] QUALIFIERS = {
794         Bytes.toBytes("col0-<d2v1>-<d3v2>"), Bytes.toBytes("col1-<d2v1>-<d3v2>"),
795         Bytes.toBytes("col2-<d2v1>-<d3v2>"), Bytes.toBytes("col3-<d2v1>-<d3v2>"),
796         Bytes.toBytes("col4-<d2v1>-<d3v2>"), Bytes.toBytes("col5-<d2v1>-<d3v2>"),
797         Bytes.toBytes("col6-<d2v1>-<d3v2>"), Bytes.toBytes("col7-<d2v1>-<d3v2>"),
798         Bytes.toBytes("col8-<d2v1>-<d3v2>"), Bytes.toBytes("col9-<d2v1>-<d3v2>")
799     };
800     for(int i=0;i<10;i++) {
801       Put put = new Put(ROWS[i]);
802       put.setDurability(Durability.SKIP_WAL);
803       put.add(FAMILY, QUALIFIERS[i], VALUE);
804       ht.put(put);
805     }
806     Scan scan = new Scan();
807     scan.addFamily(FAMILY);
808     Filter filter = new KeyOnlyFilter(true);
809     scan.setFilter(filter);
810     ResultScanner scanner = ht.getScanner(scan);
811     int count = 0;
812     for(Result result : ht.getScanner(scan)) {
813       assertEquals(result.size(), 1);
814       assertEquals(result.rawCells()[0].getValueLength(), Bytes.SIZEOF_INT);
815       assertEquals(Bytes.toInt(CellUtil.cloneValue(result.rawCells()[0])), VALUE.length);
816       count++;
817     }
818     assertEquals(count, 10);
819     scanner.close();
820   }
821 
822   /**
823    * Test simple table and non-existent row cases.
824    */
825   @Test
826   public void testSimpleMissing() throws Exception {
827     byte [] TABLE = Bytes.toBytes("testSimpleMissing");
828     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
829     byte [][] ROWS = makeN(ROW, 4);
830 
831     // Try to get a row on an empty table
832     Get get = new Get(ROWS[0]);
833     Result result = ht.get(get);
834     assertEmptyResult(result);
835 
836     get = new Get(ROWS[0]);
837     get.addFamily(FAMILY);
838     result = ht.get(get);
839     assertEmptyResult(result);
840 
841     get = new Get(ROWS[0]);
842     get.addColumn(FAMILY, QUALIFIER);
843     result = ht.get(get);
844     assertEmptyResult(result);
845 
846     Scan scan = new Scan();
847     result = getSingleScanResult(ht, scan);
848     assertNullResult(result);
849 
850 
851     scan = new Scan(ROWS[0]);
852     result = getSingleScanResult(ht, scan);
853     assertNullResult(result);
854 
855     scan = new Scan(ROWS[0],ROWS[1]);
856     result = getSingleScanResult(ht, scan);
857     assertNullResult(result);
858 
859     scan = new Scan();
860     scan.addFamily(FAMILY);
861     result = getSingleScanResult(ht, scan);
862     assertNullResult(result);
863 
864     scan = new Scan();
865     scan.addColumn(FAMILY, QUALIFIER);
866     result = getSingleScanResult(ht, scan);
867     assertNullResult(result);
868 
869     // Insert a row
870 
871     Put put = new Put(ROWS[2]);
872     put.add(FAMILY, QUALIFIER, VALUE);
873     ht.put(put);
874 
875     // Try to get empty rows around it
876 
877     get = new Get(ROWS[1]);
878     result = ht.get(get);
879     assertEmptyResult(result);
880 
881     get = new Get(ROWS[0]);
882     get.addFamily(FAMILY);
883     result = ht.get(get);
884     assertEmptyResult(result);
885 
886     get = new Get(ROWS[3]);
887     get.addColumn(FAMILY, QUALIFIER);
888     result = ht.get(get);
889     assertEmptyResult(result);
890 
891     // Try to scan empty rows around it
892 
893     scan = new Scan(ROWS[3]);
894     result = getSingleScanResult(ht, scan);
895     assertNullResult(result);
896 
897     scan = new Scan(ROWS[0],ROWS[2]);
898     result = getSingleScanResult(ht, scan);
899     assertNullResult(result);
900 
901     // Make sure we can actually get the row
902 
903     get = new Get(ROWS[2]);
904     result = ht.get(get);
905     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
906 
907     get = new Get(ROWS[2]);
908     get.addFamily(FAMILY);
909     result = ht.get(get);
910     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
911 
912     get = new Get(ROWS[2]);
913     get.addColumn(FAMILY, QUALIFIER);
914     result = ht.get(get);
915     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
916 
917     // Make sure we can scan the row
918 
919     scan = new Scan();
920     result = getSingleScanResult(ht, scan);
921     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
922 
923     scan = new Scan(ROWS[0],ROWS[3]);
924     result = getSingleScanResult(ht, scan);
925     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
926 
927     scan = new Scan(ROWS[2],ROWS[3]);
928     result = getSingleScanResult(ht, scan);
929     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
930   }
931 
932   /**
933    * Test basic puts, gets, scans, and deletes for a single row
934    * in a multiple family table.
935    */
936   @Test
937   public void testSingleRowMultipleFamily() throws Exception {
938     byte [] TABLE = Bytes.toBytes("testSingleRowMultipleFamily");
939     byte [][] ROWS = makeN(ROW, 3);
940     byte [][] FAMILIES = makeNAscii(FAMILY, 10);
941     byte [][] QUALIFIERS = makeN(QUALIFIER, 10);
942     byte [][] VALUES = makeN(VALUE, 10);
943 
944     Table ht = TEST_UTIL.createTable(TABLE, FAMILIES);
945 
946     Get get;
947     Scan scan;
948     Delete delete;
949     Put put;
950     Result result;
951 
952     ////////////////////////////////////////////////////////////////////////////
953     // Insert one column to one family
954     ////////////////////////////////////////////////////////////////////////////
955 
956     put = new Put(ROWS[0]);
957     put.add(FAMILIES[4], QUALIFIERS[0], VALUES[0]);
958     ht.put(put);
959 
960     // Get the single column
961     getVerifySingleColumn(ht, ROWS, 0, FAMILIES, 4, QUALIFIERS, 0, VALUES, 0);
962 
963     // Scan the single column
964     scanVerifySingleColumn(ht, ROWS, 0, FAMILIES, 4, QUALIFIERS, 0, VALUES, 0);
965 
966     // Get empty results around inserted column
967     getVerifySingleEmpty(ht, ROWS, 0, FAMILIES, 4, QUALIFIERS, 0);
968 
969     // Scan empty results around inserted column
970     scanVerifySingleEmpty(ht, ROWS, 0, FAMILIES, 4, QUALIFIERS, 0);
971 
972     ////////////////////////////////////////////////////////////////////////////
973     // Flush memstore and run same tests from storefiles
974     ////////////////////////////////////////////////////////////////////////////
975 
976     TEST_UTIL.flush();
977 
978     // Redo get and scan tests from storefile
979     getVerifySingleColumn(ht, ROWS, 0, FAMILIES, 4, QUALIFIERS, 0, VALUES, 0);
980     scanVerifySingleColumn(ht, ROWS, 0, FAMILIES, 4, QUALIFIERS, 0, VALUES, 0);
981     getVerifySingleEmpty(ht, ROWS, 0, FAMILIES, 4, QUALIFIERS, 0);
982     scanVerifySingleEmpty(ht, ROWS, 0, FAMILIES, 4, QUALIFIERS, 0);
983 
984     ////////////////////////////////////////////////////////////////////////////
985     // Now, Test reading from memstore and storefiles at once
986     ////////////////////////////////////////////////////////////////////////////
987 
988     // Insert multiple columns to two other families
989     put = new Put(ROWS[0]);
990     put.add(FAMILIES[2], QUALIFIERS[2], VALUES[2]);
991     put.add(FAMILIES[2], QUALIFIERS[4], VALUES[4]);
992     put.add(FAMILIES[4], QUALIFIERS[4], VALUES[4]);
993     put.add(FAMILIES[6], QUALIFIERS[6], VALUES[6]);
994     put.add(FAMILIES[6], QUALIFIERS[7], VALUES[7]);
995     put.add(FAMILIES[7], QUALIFIERS[7], VALUES[7]);
996     put.add(FAMILIES[9], QUALIFIERS[0], VALUES[0]);
997     ht.put(put);
998 
999     // Get multiple columns across multiple families and get empties around it
1000     singleRowGetTest(ht, ROWS, FAMILIES, QUALIFIERS, VALUES);
1001 
1002     // Scan multiple columns across multiple families and scan empties around it
1003     singleRowScanTest(ht, ROWS, FAMILIES, QUALIFIERS, VALUES);
1004 
1005     ////////////////////////////////////////////////////////////////////////////
1006     // Flush the table again
1007     ////////////////////////////////////////////////////////////////////////////
1008 
1009     TEST_UTIL.flush();
1010 
1011     // Redo tests again
1012     singleRowGetTest(ht, ROWS, FAMILIES, QUALIFIERS, VALUES);
1013     singleRowScanTest(ht, ROWS, FAMILIES, QUALIFIERS, VALUES);
1014 
1015     // Insert more data to memstore
1016     put = new Put(ROWS[0]);
1017     put.add(FAMILIES[6], QUALIFIERS[5], VALUES[5]);
1018     put.add(FAMILIES[6], QUALIFIERS[8], VALUES[8]);
1019     put.add(FAMILIES[6], QUALIFIERS[9], VALUES[9]);
1020     put.add(FAMILIES[4], QUALIFIERS[3], VALUES[3]);
1021     ht.put(put);
1022 
1023     ////////////////////////////////////////////////////////////////////////////
1024     // Delete a storefile column
1025     ////////////////////////////////////////////////////////////////////////////
1026     delete = new Delete(ROWS[0]);
1027     delete.deleteColumns(FAMILIES[6], QUALIFIERS[7]);
1028     ht.delete(delete);
1029 
1030     // Try to get deleted column
1031     get = new Get(ROWS[0]);
1032     get.addColumn(FAMILIES[6], QUALIFIERS[7]);
1033     result = ht.get(get);
1034     assertEmptyResult(result);
1035 
1036     // Try to scan deleted column
1037     scan = new Scan();
1038     scan.addColumn(FAMILIES[6], QUALIFIERS[7]);
1039     result = getSingleScanResult(ht, scan);
1040     assertNullResult(result);
1041 
1042     // Make sure we can still get a column before it and after it
1043     get = new Get(ROWS[0]);
1044     get.addColumn(FAMILIES[6], QUALIFIERS[6]);
1045     result = ht.get(get);
1046     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[6], VALUES[6]);
1047 
1048     get = new Get(ROWS[0]);
1049     get.addColumn(FAMILIES[6], QUALIFIERS[8]);
1050     result = ht.get(get);
1051     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[8], VALUES[8]);
1052 
1053     // Make sure we can still scan a column before it and after it
1054     scan = new Scan();
1055     scan.addColumn(FAMILIES[6], QUALIFIERS[6]);
1056     result = getSingleScanResult(ht, scan);
1057     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[6], VALUES[6]);
1058 
1059     scan = new Scan();
1060     scan.addColumn(FAMILIES[6], QUALIFIERS[8]);
1061     result = getSingleScanResult(ht, scan);
1062     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[8], VALUES[8]);
1063 
1064     ////////////////////////////////////////////////////////////////////////////
1065     // Delete a memstore column
1066     ////////////////////////////////////////////////////////////////////////////
1067     delete = new Delete(ROWS[0]);
1068     delete.deleteColumns(FAMILIES[6], QUALIFIERS[8]);
1069     ht.delete(delete);
1070 
1071     // Try to get deleted column
1072     get = new Get(ROWS[0]);
1073     get.addColumn(FAMILIES[6], QUALIFIERS[8]);
1074     result = ht.get(get);
1075     assertEmptyResult(result);
1076 
1077     // Try to scan deleted column
1078     scan = new Scan();
1079     scan.addColumn(FAMILIES[6], QUALIFIERS[8]);
1080     result = getSingleScanResult(ht, scan);
1081     assertNullResult(result);
1082 
1083     // Make sure we can still get a column before it and after it
1084     get = new Get(ROWS[0]);
1085     get.addColumn(FAMILIES[6], QUALIFIERS[6]);
1086     result = ht.get(get);
1087     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[6], VALUES[6]);
1088 
1089     get = new Get(ROWS[0]);
1090     get.addColumn(FAMILIES[6], QUALIFIERS[9]);
1091     result = ht.get(get);
1092     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[9], VALUES[9]);
1093 
1094     // Make sure we can still scan a column before it and after it
1095     scan = new Scan();
1096     scan.addColumn(FAMILIES[6], QUALIFIERS[6]);
1097     result = getSingleScanResult(ht, scan);
1098     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[6], VALUES[6]);
1099 
1100     scan = new Scan();
1101     scan.addColumn(FAMILIES[6], QUALIFIERS[9]);
1102     result = getSingleScanResult(ht, scan);
1103     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[9], VALUES[9]);
1104 
1105     ////////////////////////////////////////////////////////////////////////////
1106     // Delete joint storefile/memstore family
1107     ////////////////////////////////////////////////////////////////////////////
1108 
1109     delete = new Delete(ROWS[0]);
1110     delete.deleteFamily(FAMILIES[4]);
1111     ht.delete(delete);
1112 
1113     // Try to get storefile column in deleted family
1114     get = new Get(ROWS[0]);
1115     get.addColumn(FAMILIES[4], QUALIFIERS[4]);
1116     result = ht.get(get);
1117     assertEmptyResult(result);
1118 
1119     // Try to get memstore column in deleted family
1120     get = new Get(ROWS[0]);
1121     get.addColumn(FAMILIES[4], QUALIFIERS[3]);
1122     result = ht.get(get);
1123     assertEmptyResult(result);
1124 
1125     // Try to get deleted family
1126     get = new Get(ROWS[0]);
1127     get.addFamily(FAMILIES[4]);
1128     result = ht.get(get);
1129     assertEmptyResult(result);
1130 
1131     // Try to scan storefile column in deleted family
1132     scan = new Scan();
1133     scan.addColumn(FAMILIES[4], QUALIFIERS[4]);
1134     result = getSingleScanResult(ht, scan);
1135     assertNullResult(result);
1136 
1137     // Try to scan memstore column in deleted family
1138     scan = new Scan();
1139     scan.addColumn(FAMILIES[4], QUALIFIERS[3]);
1140     result = getSingleScanResult(ht, scan);
1141     assertNullResult(result);
1142 
1143     // Try to scan deleted family
1144     scan = new Scan();
1145     scan.addFamily(FAMILIES[4]);
1146     result = getSingleScanResult(ht, scan);
1147     assertNullResult(result);
1148 
1149     // Make sure we can still get another family
1150     get = new Get(ROWS[0]);
1151     get.addColumn(FAMILIES[2], QUALIFIERS[2]);
1152     result = ht.get(get);
1153     assertSingleResult(result, ROWS[0], FAMILIES[2], QUALIFIERS[2], VALUES[2]);
1154 
1155     get = new Get(ROWS[0]);
1156     get.addColumn(FAMILIES[6], QUALIFIERS[9]);
1157     result = ht.get(get);
1158     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[9], VALUES[9]);
1159 
1160     // Make sure we can still scan another family
1161     scan = new Scan();
1162     scan.addColumn(FAMILIES[6], QUALIFIERS[6]);
1163     result = getSingleScanResult(ht, scan);
1164     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[6], VALUES[6]);
1165 
1166     scan = new Scan();
1167     scan.addColumn(FAMILIES[6], QUALIFIERS[9]);
1168     result = getSingleScanResult(ht, scan);
1169     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[9], VALUES[9]);
1170 
1171     ////////////////////////////////////////////////////////////////////////////
1172     // Flush everything and rerun delete tests
1173     ////////////////////////////////////////////////////////////////////////////
1174 
1175     TEST_UTIL.flush();
1176 
1177     // Try to get storefile column in deleted family
1178     get = new Get(ROWS[0]);
1179     get.addColumn(FAMILIES[4], QUALIFIERS[4]);
1180     result = ht.get(get);
1181     assertEmptyResult(result);
1182 
1183     // Try to get memstore column in deleted family
1184     get = new Get(ROWS[0]);
1185     get.addColumn(FAMILIES[4], QUALIFIERS[3]);
1186     result = ht.get(get);
1187     assertEmptyResult(result);
1188 
1189     // Try to get deleted family
1190     get = new Get(ROWS[0]);
1191     get.addFamily(FAMILIES[4]);
1192     result = ht.get(get);
1193     assertEmptyResult(result);
1194 
1195     // Try to scan storefile column in deleted family
1196     scan = new Scan();
1197     scan.addColumn(FAMILIES[4], QUALIFIERS[4]);
1198     result = getSingleScanResult(ht, scan);
1199     assertNullResult(result);
1200 
1201     // Try to scan memstore column in deleted family
1202     scan = new Scan();
1203     scan.addColumn(FAMILIES[4], QUALIFIERS[3]);
1204     result = getSingleScanResult(ht, scan);
1205     assertNullResult(result);
1206 
1207     // Try to scan deleted family
1208     scan = new Scan();
1209     scan.addFamily(FAMILIES[4]);
1210     result = getSingleScanResult(ht, scan);
1211     assertNullResult(result);
1212 
1213     // Make sure we can still get another family
1214     get = new Get(ROWS[0]);
1215     get.addColumn(FAMILIES[2], QUALIFIERS[2]);
1216     result = ht.get(get);
1217     assertSingleResult(result, ROWS[0], FAMILIES[2], QUALIFIERS[2], VALUES[2]);
1218 
1219     get = new Get(ROWS[0]);
1220     get.addColumn(FAMILIES[6], QUALIFIERS[9]);
1221     result = ht.get(get);
1222     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[9], VALUES[9]);
1223 
1224     // Make sure we can still scan another family
1225     scan = new Scan();
1226     scan.addColumn(FAMILIES[6], QUALIFIERS[6]);
1227     result = getSingleScanResult(ht, scan);
1228     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[6], VALUES[6]);
1229 
1230     scan = new Scan();
1231     scan.addColumn(FAMILIES[6], QUALIFIERS[9]);
1232     result = getSingleScanResult(ht, scan);
1233     assertSingleResult(result, ROWS[0], FAMILIES[6], QUALIFIERS[9], VALUES[9]);
1234 
1235   }
1236 
1237   @Test
1238   public void testNull() throws Exception {
1239     byte [] TABLE = Bytes.toBytes("testNull");
1240 
1241     // Null table name (should NOT work)
1242     try {
1243       TEST_UTIL.createTable((TableName)null, FAMILY);
1244       fail("Creating a table with null name passed, should have failed");
1245     } catch(Exception e) {}
1246 
1247     // Null family (should NOT work)
1248     try {
1249       TEST_UTIL.createTable(TABLE, new byte[][]{(byte[])null});
1250       fail("Creating a table with a null family passed, should fail");
1251     } catch(Exception e) {}
1252 
1253     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
1254 
1255     // Null row (should NOT work)
1256     try {
1257       Put put = new Put((byte[])null);
1258       put.add(FAMILY, QUALIFIER, VALUE);
1259       ht.put(put);
1260       fail("Inserting a null row worked, should throw exception");
1261     } catch(Exception e) {}
1262 
1263     // Null qualifier (should work)
1264     {
1265       Put put = new Put(ROW);
1266       put.add(FAMILY, null, VALUE);
1267       ht.put(put);
1268 
1269       getTestNull(ht, ROW, FAMILY, VALUE);
1270 
1271       scanTestNull(ht, ROW, FAMILY, VALUE);
1272 
1273       Delete delete = new Delete(ROW);
1274       delete.deleteColumns(FAMILY, null);
1275       ht.delete(delete);
1276 
1277       Get get = new Get(ROW);
1278       Result result = ht.get(get);
1279       assertEmptyResult(result);
1280     }
1281 
1282     // Use a new table
1283     byte [] TABLE2 = Bytes.toBytes("testNull2");
1284     ht = TEST_UTIL.createTable(TableName.valueOf(TABLE2), FAMILY);
1285 
1286     // Empty qualifier, byte[0] instead of null (should work)
1287     try {
1288       Put put = new Put(ROW);
1289       put.add(FAMILY, HConstants.EMPTY_BYTE_ARRAY, VALUE);
1290       ht.put(put);
1291 
1292       getTestNull(ht, ROW, FAMILY, VALUE);
1293 
1294       scanTestNull(ht, ROW, FAMILY, VALUE);
1295 
1296       // Flush and try again
1297 
1298       TEST_UTIL.flush();
1299 
1300       getTestNull(ht, ROW, FAMILY, VALUE);
1301 
1302       scanTestNull(ht, ROW, FAMILY, VALUE);
1303 
1304       Delete delete = new Delete(ROW);
1305       delete.deleteColumns(FAMILY, HConstants.EMPTY_BYTE_ARRAY);
1306       ht.delete(delete);
1307 
1308       Get get = new Get(ROW);
1309       Result result = ht.get(get);
1310       assertEmptyResult(result);
1311 
1312     } catch(Exception e) {
1313       throw new IOException("Using a row with null qualifier threw exception, should ");
1314     }
1315 
1316     // Null value
1317     try {
1318       Put put = new Put(ROW);
1319       put.add(FAMILY, QUALIFIER, null);
1320       ht.put(put);
1321 
1322       Get get = new Get(ROW);
1323       get.addColumn(FAMILY, QUALIFIER);
1324       Result result = ht.get(get);
1325       assertSingleResult(result, ROW, FAMILY, QUALIFIER, null);
1326 
1327       Scan scan = new Scan();
1328       scan.addColumn(FAMILY, QUALIFIER);
1329       result = getSingleScanResult(ht, scan);
1330       assertSingleResult(result, ROW, FAMILY, QUALIFIER, null);
1331 
1332       Delete delete = new Delete(ROW);
1333       delete.deleteColumns(FAMILY, QUALIFIER);
1334       ht.delete(delete);
1335 
1336       get = new Get(ROW);
1337       result = ht.get(get);
1338       assertEmptyResult(result);
1339 
1340     } catch(Exception e) {
1341       throw new IOException("Null values should be allowed, but threw exception");
1342     }
1343   }
1344 
1345   @Test
1346   public void testVersions() throws Exception {
1347     byte [] TABLE = Bytes.toBytes("testVersions");
1348 
1349     long [] STAMPS = makeStamps(20);
1350     byte [][] VALUES = makeNAscii(VALUE, 20);
1351 
1352     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 10);
1353 
1354     // Insert 4 versions of same column
1355     Put put = new Put(ROW);
1356     put.add(FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
1357     put.add(FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
1358     put.add(FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
1359     put.add(FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
1360     ht.put(put);
1361 
1362     // Verify we can get each one properly
1363     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
1364     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
1365     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
1366     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
1367     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
1368     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
1369     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
1370     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
1371 
1372     // Verify we don't accidentally get others
1373     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
1374     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[3]);
1375     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[6]);
1376     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
1377     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[3]);
1378     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[6]);
1379 
1380     // Ensure maxVersions in query is respected
1381     Get get = new Get(ROW);
1382     get.addColumn(FAMILY, QUALIFIER);
1383     get.setMaxVersions(2);
1384     Result result = ht.get(get);
1385     assertNResult(result, ROW, FAMILY, QUALIFIER,
1386         new long [] {STAMPS[4], STAMPS[5]},
1387         new byte[][] {VALUES[4], VALUES[5]},
1388         0, 1);
1389 
1390     Scan scan = new Scan(ROW);
1391     scan.addColumn(FAMILY, QUALIFIER);
1392     scan.setMaxVersions(2);
1393     result = getSingleScanResult(ht, scan);
1394     assertNResult(result, ROW, FAMILY, QUALIFIER,
1395         new long [] {STAMPS[4], STAMPS[5]},
1396         new byte[][] {VALUES[4], VALUES[5]},
1397         0, 1);
1398 
1399     // Flush and redo
1400 
1401     TEST_UTIL.flush();
1402 
1403     // Verify we can get each one properly
1404     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
1405     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
1406     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
1407     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
1408     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
1409     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
1410     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
1411     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
1412 
1413     // Verify we don't accidentally get others
1414     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
1415     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[3]);
1416     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[6]);
1417     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
1418     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[3]);
1419     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[6]);
1420 
1421     // Ensure maxVersions in query is respected
1422     get = new Get(ROW);
1423     get.addColumn(FAMILY, QUALIFIER);
1424     get.setMaxVersions(2);
1425     result = ht.get(get);
1426     assertNResult(result, ROW, FAMILY, QUALIFIER,
1427         new long [] {STAMPS[4], STAMPS[5]},
1428         new byte[][] {VALUES[4], VALUES[5]},
1429         0, 1);
1430 
1431     scan = new Scan(ROW);
1432     scan.addColumn(FAMILY, QUALIFIER);
1433     scan.setMaxVersions(2);
1434     result = getSingleScanResult(ht, scan);
1435     assertNResult(result, ROW, FAMILY, QUALIFIER,
1436         new long [] {STAMPS[4], STAMPS[5]},
1437         new byte[][] {VALUES[4], VALUES[5]},
1438         0, 1);
1439 
1440 
1441     // Add some memstore and retest
1442 
1443     // Insert 4 more versions of same column and a dupe
1444     put = new Put(ROW);
1445     put.add(FAMILY, QUALIFIER, STAMPS[3], VALUES[3]);
1446     put.add(FAMILY, QUALIFIER, STAMPS[6], VALUES[6]);
1447     put.add(FAMILY, QUALIFIER, STAMPS[7], VALUES[7]);
1448     put.add(FAMILY, QUALIFIER, STAMPS[8], VALUES[8]);
1449     ht.put(put);
1450 
1451     // Ensure maxVersions in query is respected
1452     get = new Get(ROW);
1453     get.addColumn(FAMILY, QUALIFIER);
1454     get.setMaxVersions();
1455     result = ht.get(get);
1456     assertNResult(result, ROW, FAMILY, QUALIFIER,
1457         new long [] {STAMPS[1], STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8]},
1458         new byte[][] {VALUES[1], VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6], VALUES[7], VALUES[8]},
1459         0, 7);
1460 
1461     scan = new Scan(ROW);
1462     scan.addColumn(FAMILY, QUALIFIER);
1463     scan.setMaxVersions();
1464     result = getSingleScanResult(ht, scan);
1465     assertNResult(result, ROW, FAMILY, QUALIFIER,
1466         new long [] {STAMPS[1], STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8]},
1467         new byte[][] {VALUES[1], VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6], VALUES[7], VALUES[8]},
1468         0, 7);
1469 
1470     get = new Get(ROW);
1471     get.setMaxVersions();
1472     result = ht.get(get);
1473     assertNResult(result, ROW, FAMILY, QUALIFIER,
1474         new long [] {STAMPS[1], STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8]},
1475         new byte[][] {VALUES[1], VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6], VALUES[7], VALUES[8]},
1476         0, 7);
1477 
1478     scan = new Scan(ROW);
1479     scan.setMaxVersions();
1480     result = getSingleScanResult(ht, scan);
1481     assertNResult(result, ROW, FAMILY, QUALIFIER,
1482         new long [] {STAMPS[1], STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8]},
1483         new byte[][] {VALUES[1], VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6], VALUES[7], VALUES[8]},
1484         0, 7);
1485 
1486     // Verify we can get each one properly
1487     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
1488     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
1489     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
1490     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[7], VALUES[7]);
1491     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
1492     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
1493     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
1494     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[7], VALUES[7]);
1495 
1496     // Verify we don't accidentally get others
1497     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
1498     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[9]);
1499     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
1500     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[9]);
1501 
1502     // Ensure maxVersions of table is respected
1503 
1504     TEST_UTIL.flush();
1505 
1506     // Insert 4 more versions of same column and a dupe
1507     put = new Put(ROW);
1508     put.add(FAMILY, QUALIFIER, STAMPS[9], VALUES[9]);
1509     put.add(FAMILY, QUALIFIER, STAMPS[11], VALUES[11]);
1510     put.add(FAMILY, QUALIFIER, STAMPS[13], VALUES[13]);
1511     put.add(FAMILY, QUALIFIER, STAMPS[15], VALUES[15]);
1512     ht.put(put);
1513 
1514     get = new Get(ROW);
1515     get.addColumn(FAMILY, QUALIFIER);
1516     get.setMaxVersions(Integer.MAX_VALUE);
1517     result = ht.get(get);
1518     assertNResult(result, ROW, FAMILY, QUALIFIER,
1519         new long [] {STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8], STAMPS[9], STAMPS[11], STAMPS[13], STAMPS[15]},
1520         new byte[][] {VALUES[3], VALUES[4], VALUES[5], VALUES[6], VALUES[7], VALUES[8], VALUES[9], VALUES[11], VALUES[13], VALUES[15]},
1521         0, 9);
1522 
1523     scan = new Scan(ROW);
1524     scan.addColumn(FAMILY, QUALIFIER);
1525     scan.setMaxVersions(Integer.MAX_VALUE);
1526     result = getSingleScanResult(ht, scan);
1527     assertNResult(result, ROW, FAMILY, QUALIFIER,
1528         new long [] {STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8], STAMPS[9], STAMPS[11], STAMPS[13], STAMPS[15]},
1529         new byte[][] {VALUES[3], VALUES[4], VALUES[5], VALUES[6], VALUES[7], VALUES[8], VALUES[9], VALUES[11], VALUES[13], VALUES[15]},
1530         0, 9);
1531 
1532     // Delete a version in the memstore and a version in a storefile
1533     Delete delete = new Delete(ROW);
1534     delete.deleteColumn(FAMILY, QUALIFIER, STAMPS[11]);
1535     delete.deleteColumn(FAMILY, QUALIFIER, STAMPS[7]);
1536     ht.delete(delete);
1537 
1538     // Test that it's gone
1539     get = new Get(ROW);
1540     get.addColumn(FAMILY, QUALIFIER);
1541     get.setMaxVersions(Integer.MAX_VALUE);
1542     result = ht.get(get);
1543     assertNResult(result, ROW, FAMILY, QUALIFIER,
1544         new long [] {STAMPS[1], STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[8], STAMPS[9], STAMPS[13], STAMPS[15]},
1545         new byte[][] {VALUES[1], VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6], VALUES[8], VALUES[9], VALUES[13], VALUES[15]},
1546         0, 9);
1547 
1548     scan = new Scan(ROW);
1549     scan.addColumn(FAMILY, QUALIFIER);
1550     scan.setMaxVersions(Integer.MAX_VALUE);
1551     result = getSingleScanResult(ht, scan);
1552     assertNResult(result, ROW, FAMILY, QUALIFIER,
1553         new long [] {STAMPS[1], STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[8], STAMPS[9], STAMPS[13], STAMPS[15]},
1554         new byte[][] {VALUES[1], VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6], VALUES[8], VALUES[9], VALUES[13], VALUES[15]},
1555         0, 9);
1556 
1557   }
1558 
1559   @Test
1560   public void testVersionLimits() throws Exception {
1561     byte [] TABLE = Bytes.toBytes("testVersionLimits");
1562     byte [][] FAMILIES = makeNAscii(FAMILY, 3);
1563     int [] LIMITS = {1,3,5};
1564     long [] STAMPS = makeStamps(10);
1565     byte [][] VALUES = makeNAscii(VALUE, 10);
1566     Table ht = TEST_UTIL.createTable(TABLE, FAMILIES, LIMITS);
1567 
1568     // Insert limit + 1 on each family
1569     Put put = new Put(ROW);
1570     put.add(FAMILIES[0], QUALIFIER, STAMPS[0], VALUES[0]);
1571     put.add(FAMILIES[0], QUALIFIER, STAMPS[1], VALUES[1]);
1572     put.add(FAMILIES[1], QUALIFIER, STAMPS[0], VALUES[0]);
1573     put.add(FAMILIES[1], QUALIFIER, STAMPS[1], VALUES[1]);
1574     put.add(FAMILIES[1], QUALIFIER, STAMPS[2], VALUES[2]);
1575     put.add(FAMILIES[1], QUALIFIER, STAMPS[3], VALUES[3]);
1576     put.add(FAMILIES[2], QUALIFIER, STAMPS[0], VALUES[0]);
1577     put.add(FAMILIES[2], QUALIFIER, STAMPS[1], VALUES[1]);
1578     put.add(FAMILIES[2], QUALIFIER, STAMPS[2], VALUES[2]);
1579     put.add(FAMILIES[2], QUALIFIER, STAMPS[3], VALUES[3]);
1580     put.add(FAMILIES[2], QUALIFIER, STAMPS[4], VALUES[4]);
1581     put.add(FAMILIES[2], QUALIFIER, STAMPS[5], VALUES[5]);
1582     put.add(FAMILIES[2], QUALIFIER, STAMPS[6], VALUES[6]);
1583     ht.put(put);
1584 
1585     // Verify we only get the right number out of each
1586 
1587     // Family0
1588 
1589     Get get = new Get(ROW);
1590     get.addColumn(FAMILIES[0], QUALIFIER);
1591     get.setMaxVersions(Integer.MAX_VALUE);
1592     Result result = ht.get(get);
1593     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
1594         new long [] {STAMPS[1]},
1595         new byte[][] {VALUES[1]},
1596         0, 0);
1597 
1598     get = new Get(ROW);
1599     get.addFamily(FAMILIES[0]);
1600     get.setMaxVersions(Integer.MAX_VALUE);
1601     result = ht.get(get);
1602     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
1603         new long [] {STAMPS[1]},
1604         new byte[][] {VALUES[1]},
1605         0, 0);
1606 
1607     Scan scan = new Scan(ROW);
1608     scan.addColumn(FAMILIES[0], QUALIFIER);
1609     scan.setMaxVersions(Integer.MAX_VALUE);
1610     result = getSingleScanResult(ht, scan);
1611     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
1612         new long [] {STAMPS[1]},
1613         new byte[][] {VALUES[1]},
1614         0, 0);
1615 
1616     scan = new Scan(ROW);
1617     scan.addFamily(FAMILIES[0]);
1618     scan.setMaxVersions(Integer.MAX_VALUE);
1619     result = getSingleScanResult(ht, scan);
1620     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
1621         new long [] {STAMPS[1]},
1622         new byte[][] {VALUES[1]},
1623         0, 0);
1624 
1625     // Family1
1626 
1627     get = new Get(ROW);
1628     get.addColumn(FAMILIES[1], QUALIFIER);
1629     get.setMaxVersions(Integer.MAX_VALUE);
1630     result = ht.get(get);
1631     assertNResult(result, ROW, FAMILIES[1], QUALIFIER,
1632         new long [] {STAMPS[1], STAMPS[2], STAMPS[3]},
1633         new byte[][] {VALUES[1], VALUES[2], VALUES[3]},
1634         0, 2);
1635 
1636     get = new Get(ROW);
1637     get.addFamily(FAMILIES[1]);
1638     get.setMaxVersions(Integer.MAX_VALUE);
1639     result = ht.get(get);
1640     assertNResult(result, ROW, FAMILIES[1], QUALIFIER,
1641         new long [] {STAMPS[1], STAMPS[2], STAMPS[3]},
1642         new byte[][] {VALUES[1], VALUES[2], VALUES[3]},
1643         0, 2);
1644 
1645     scan = new Scan(ROW);
1646     scan.addColumn(FAMILIES[1], QUALIFIER);
1647     scan.setMaxVersions(Integer.MAX_VALUE);
1648     result = getSingleScanResult(ht, scan);
1649     assertNResult(result, ROW, FAMILIES[1], QUALIFIER,
1650         new long [] {STAMPS[1], STAMPS[2], STAMPS[3]},
1651         new byte[][] {VALUES[1], VALUES[2], VALUES[3]},
1652         0, 2);
1653 
1654     scan = new Scan(ROW);
1655     scan.addFamily(FAMILIES[1]);
1656     scan.setMaxVersions(Integer.MAX_VALUE);
1657     result = getSingleScanResult(ht, scan);
1658     assertNResult(result, ROW, FAMILIES[1], QUALIFIER,
1659         new long [] {STAMPS[1], STAMPS[2], STAMPS[3]},
1660         new byte[][] {VALUES[1], VALUES[2], VALUES[3]},
1661         0, 2);
1662 
1663     // Family2
1664 
1665     get = new Get(ROW);
1666     get.addColumn(FAMILIES[2], QUALIFIER);
1667     get.setMaxVersions(Integer.MAX_VALUE);
1668     result = ht.get(get);
1669     assertNResult(result, ROW, FAMILIES[2], QUALIFIER,
1670         new long [] {STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6]},
1671         new byte[][] {VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6]},
1672         0, 4);
1673 
1674     get = new Get(ROW);
1675     get.addFamily(FAMILIES[2]);
1676     get.setMaxVersions(Integer.MAX_VALUE);
1677     result = ht.get(get);
1678     assertNResult(result, ROW, FAMILIES[2], QUALIFIER,
1679         new long [] {STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6]},
1680         new byte[][] {VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6]},
1681         0, 4);
1682 
1683     scan = new Scan(ROW);
1684     scan.addColumn(FAMILIES[2], QUALIFIER);
1685     scan.setMaxVersions(Integer.MAX_VALUE);
1686     result = getSingleScanResult(ht, scan);
1687     assertNResult(result, ROW, FAMILIES[2], QUALIFIER,
1688         new long [] {STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6]},
1689         new byte[][] {VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6]},
1690         0, 4);
1691 
1692     scan = new Scan(ROW);
1693     scan.addFamily(FAMILIES[2]);
1694     scan.setMaxVersions(Integer.MAX_VALUE);
1695     result = getSingleScanResult(ht, scan);
1696     assertNResult(result, ROW, FAMILIES[2], QUALIFIER,
1697         new long [] {STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6]},
1698         new byte[][] {VALUES[2], VALUES[3], VALUES[4], VALUES[5], VALUES[6]},
1699         0, 4);
1700 
1701     // Try all families
1702 
1703     get = new Get(ROW);
1704     get.setMaxVersions(Integer.MAX_VALUE);
1705     result = ht.get(get);
1706     assertTrue("Expected 9 keys but received " + result.size(),
1707         result.size() == 9);
1708 
1709     get = new Get(ROW);
1710     get.addFamily(FAMILIES[0]);
1711     get.addFamily(FAMILIES[1]);
1712     get.addFamily(FAMILIES[2]);
1713     get.setMaxVersions(Integer.MAX_VALUE);
1714     result = ht.get(get);
1715     assertTrue("Expected 9 keys but received " + result.size(),
1716         result.size() == 9);
1717 
1718     get = new Get(ROW);
1719     get.addColumn(FAMILIES[0], QUALIFIER);
1720     get.addColumn(FAMILIES[1], QUALIFIER);
1721     get.addColumn(FAMILIES[2], QUALIFIER);
1722     get.setMaxVersions(Integer.MAX_VALUE);
1723     result = ht.get(get);
1724     assertTrue("Expected 9 keys but received " + result.size(),
1725         result.size() == 9);
1726 
1727     scan = new Scan(ROW);
1728     scan.setMaxVersions(Integer.MAX_VALUE);
1729     result = getSingleScanResult(ht, scan);
1730     assertTrue("Expected 9 keys but received " + result.size(),
1731         result.size() == 9);
1732 
1733     scan = new Scan(ROW);
1734     scan.setMaxVersions(Integer.MAX_VALUE);
1735     scan.addFamily(FAMILIES[0]);
1736     scan.addFamily(FAMILIES[1]);
1737     scan.addFamily(FAMILIES[2]);
1738     result = getSingleScanResult(ht, scan);
1739     assertTrue("Expected 9 keys but received " + result.size(),
1740         result.size() == 9);
1741 
1742     scan = new Scan(ROW);
1743     scan.setMaxVersions(Integer.MAX_VALUE);
1744     scan.addColumn(FAMILIES[0], QUALIFIER);
1745     scan.addColumn(FAMILIES[1], QUALIFIER);
1746     scan.addColumn(FAMILIES[2], QUALIFIER);
1747     result = getSingleScanResult(ht, scan);
1748     assertTrue("Expected 9 keys but received " + result.size(),
1749         result.size() == 9);
1750 
1751   }
1752 
1753   @Test
1754   public void testDeleteFamilyVersion() throws Exception {
1755     HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
1756     byte [] TABLE = Bytes.toBytes("testDeleteFamilyVersion");
1757 
1758     byte [][] QUALIFIERS = makeNAscii(QUALIFIER, 1);
1759     byte [][] VALUES = makeN(VALUE, 5);
1760     long [] ts = {1000, 2000, 3000, 4000, 5000};
1761 
1762     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 5);
1763 
1764     Put put = new Put(ROW);
1765     for (int q = 0; q < 1; q++)
1766       for (int t = 0; t < 5; t++)
1767         put.add(FAMILY, QUALIFIERS[q], ts[t], VALUES[t]);
1768     ht.put(put);
1769     admin.flush(TABLE);
1770 
1771     Delete delete = new Delete(ROW);
1772     delete.deleteFamilyVersion(FAMILY, ts[1]);  // delete version '2000'
1773     delete.deleteFamilyVersion(FAMILY, ts[3]);  // delete version '4000'
1774     ht.delete(delete);
1775     admin.flush(TABLE);
1776 
1777     for (int i = 0; i < 1; i++) {
1778       Get get = new Get(ROW);
1779       get.addColumn(FAMILY, QUALIFIERS[i]);
1780       get.setMaxVersions(Integer.MAX_VALUE);
1781       Result result = ht.get(get);
1782       // verify version '1000'/'3000'/'5000' remains for all columns
1783       assertNResult(result, ROW, FAMILY, QUALIFIERS[i],
1784           new long [] {ts[0], ts[2], ts[4]},
1785           new byte[][] {VALUES[0], VALUES[2], VALUES[4]},
1786           0, 2);
1787     }
1788     ht.close();
1789     admin.close();
1790   }
1791 
1792   @Test
1793   public void testDeleteFamilyVersionWithOtherDeletes() throws Exception {
1794     byte [] TABLE = Bytes.toBytes("testDeleteFamilyVersionWithOtherDeletes");
1795 
1796     byte [][] QUALIFIERS = makeNAscii(QUALIFIER, 5);
1797     byte [][] VALUES = makeN(VALUE, 5);
1798     long [] ts = {1000, 2000, 3000, 4000, 5000};
1799 
1800     HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
1801     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 5);
1802     Put put = null;
1803     Result result = null;
1804     Get get = null;
1805     Delete delete = null;
1806 
1807     // 1. put on ROW
1808     put = new Put(ROW);
1809     for (int q = 0; q < 5; q++)
1810       for (int t = 0; t < 5; t++)
1811         put.add(FAMILY, QUALIFIERS[q], ts[t], VALUES[t]);
1812     ht.put(put);
1813     admin.flush(TABLE);
1814 
1815     // 2. put on ROWS[0]
1816     byte [] ROW2 = Bytes.toBytes("myRowForTest");
1817     put = new Put(ROW2);
1818     for (int q = 0; q < 5; q++)
1819       for (int t = 0; t < 5; t++)
1820         put.add(FAMILY, QUALIFIERS[q], ts[t], VALUES[t]);
1821     ht.put(put);
1822     admin.flush(TABLE);
1823 
1824     // 3. delete on ROW
1825     delete = new Delete(ROW);
1826     // delete version <= 2000 of all columns
1827     // note: deleteFamily must be the first since it will mask
1828     // the subsequent other type deletes!
1829     delete.deleteFamily(FAMILY, ts[1]);
1830     // delete version '4000' of all columns
1831     delete.deleteFamilyVersion(FAMILY, ts[3]);
1832    // delete version <= 3000 of column 0
1833     delete.deleteColumns(FAMILY, QUALIFIERS[0], ts[2]);
1834     // delete version <= 5000 of column 2
1835     delete.deleteColumns(FAMILY, QUALIFIERS[2], ts[4]);
1836     // delete version 5000 of column 4
1837     delete.deleteColumn(FAMILY, QUALIFIERS[4], ts[4]);
1838     ht.delete(delete);
1839     admin.flush(TABLE);
1840 
1841      // 4. delete on ROWS[0]
1842     delete = new Delete(ROW2);
1843     delete.deleteFamilyVersion(FAMILY, ts[1]);  // delete version '2000'
1844     delete.deleteFamilyVersion(FAMILY, ts[3]);  // delete version '4000'
1845     ht.delete(delete);
1846     admin.flush(TABLE);
1847 
1848     // 5. check ROW
1849     get = new Get(ROW);
1850     get.addColumn(FAMILY, QUALIFIERS[0]);
1851     get.setMaxVersions(Integer.MAX_VALUE);
1852     result = ht.get(get);
1853     assertNResult(result, ROW, FAMILY, QUALIFIERS[0],
1854         new long [] {ts[4]},
1855         new byte[][] {VALUES[4]},
1856         0, 0);
1857 
1858     get = new Get(ROW);
1859     get.addColumn(FAMILY, QUALIFIERS[1]);
1860     get.setMaxVersions(Integer.MAX_VALUE);
1861     result = ht.get(get);
1862     assertNResult(result, ROW, FAMILY, QUALIFIERS[1],
1863         new long [] {ts[2], ts[4]},
1864         new byte[][] {VALUES[2], VALUES[4]},
1865         0, 1);
1866 
1867     get = new Get(ROW);
1868     get.addColumn(FAMILY, QUALIFIERS[2]);
1869     get.setMaxVersions(Integer.MAX_VALUE);
1870     result = ht.get(get);
1871     assertEquals(0, result.size());
1872 
1873     get = new Get(ROW);
1874     get.addColumn(FAMILY, QUALIFIERS[3]);
1875     get.setMaxVersions(Integer.MAX_VALUE);
1876     result = ht.get(get);
1877     assertNResult(result, ROW, FAMILY, QUALIFIERS[3],
1878         new long [] {ts[2], ts[4]},
1879         new byte[][] {VALUES[2], VALUES[4]},
1880         0, 1);
1881 
1882     get = new Get(ROW);
1883     get.addColumn(FAMILY, QUALIFIERS[4]);
1884     get.setMaxVersions(Integer.MAX_VALUE);
1885     result = ht.get(get);
1886     assertNResult(result, ROW, FAMILY, QUALIFIERS[4],
1887         new long [] {ts[2]},
1888         new byte[][] {VALUES[2]},
1889         0, 0);
1890 
1891     // 6. check ROWS[0]
1892     for (int i = 0; i < 5; i++) {
1893       get = new Get(ROW2);
1894       get.addColumn(FAMILY, QUALIFIERS[i]);
1895       get.setMaxVersions(Integer.MAX_VALUE);
1896       result = ht.get(get);
1897       // verify version '1000'/'3000'/'5000' remains for all columns
1898       assertNResult(result, ROW2, FAMILY, QUALIFIERS[i],
1899           new long [] {ts[0], ts[2], ts[4]},
1900           new byte[][] {VALUES[0], VALUES[2], VALUES[4]},
1901           0, 2);
1902     }
1903     ht.close();
1904     admin.close();
1905   }
1906 
1907   @Test
1908   public void testDeletes() throws Exception {
1909     byte [] TABLE = Bytes.toBytes("testDeletes");
1910 
1911     byte [][] ROWS = makeNAscii(ROW, 6);
1912     byte [][] FAMILIES = makeNAscii(FAMILY, 3);
1913     byte [][] VALUES = makeN(VALUE, 5);
1914     long [] ts = {1000, 2000, 3000, 4000, 5000};
1915 
1916     Table ht = TEST_UTIL.createTable(TABLE, FAMILIES, 3);
1917 
1918     Put put = new Put(ROW);
1919     put.add(FAMILIES[0], QUALIFIER, ts[0], VALUES[0]);
1920     put.add(FAMILIES[0], QUALIFIER, ts[1], VALUES[1]);
1921     ht.put(put);
1922 
1923     Delete delete = new Delete(ROW);
1924     delete.deleteFamily(FAMILIES[0], ts[0]);
1925     ht.delete(delete);
1926 
1927     Get get = new Get(ROW);
1928     get.addFamily(FAMILIES[0]);
1929     get.setMaxVersions(Integer.MAX_VALUE);
1930     Result result = ht.get(get);
1931     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
1932         new long [] {ts[1]},
1933         new byte[][] {VALUES[1]},
1934         0, 0);
1935 
1936     Scan scan = new Scan(ROW);
1937     scan.addFamily(FAMILIES[0]);
1938     scan.setMaxVersions(Integer.MAX_VALUE);
1939     result = getSingleScanResult(ht, scan);
1940     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
1941         new long [] {ts[1]},
1942         new byte[][] {VALUES[1]},
1943         0, 0);
1944 
1945     // Test delete latest version
1946     put = new Put(ROW);
1947     put.add(FAMILIES[0], QUALIFIER, ts[4], VALUES[4]);
1948     put.add(FAMILIES[0], QUALIFIER, ts[2], VALUES[2]);
1949     put.add(FAMILIES[0], QUALIFIER, ts[3], VALUES[3]);
1950     put.add(FAMILIES[0], null, ts[4], VALUES[4]);
1951     put.add(FAMILIES[0], null, ts[2], VALUES[2]);
1952     put.add(FAMILIES[0], null, ts[3], VALUES[3]);
1953     ht.put(put);
1954 
1955     delete = new Delete(ROW);
1956     delete.deleteColumn(FAMILIES[0], QUALIFIER); // ts[4]
1957     ht.delete(delete);
1958 
1959     get = new Get(ROW);
1960     get.addColumn(FAMILIES[0], QUALIFIER);
1961     get.setMaxVersions(Integer.MAX_VALUE);
1962     result = ht.get(get);
1963     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
1964         new long [] {ts[1], ts[2], ts[3]},
1965         new byte[][] {VALUES[1], VALUES[2], VALUES[3]},
1966         0, 2);
1967 
1968     scan = new Scan(ROW);
1969     scan.addColumn(FAMILIES[0], QUALIFIER);
1970     scan.setMaxVersions(Integer.MAX_VALUE);
1971     result = getSingleScanResult(ht, scan);
1972     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
1973         new long [] {ts[1], ts[2], ts[3]},
1974         new byte[][] {VALUES[1], VALUES[2], VALUES[3]},
1975         0, 2);
1976 
1977     // Test for HBASE-1847
1978     delete = new Delete(ROW);
1979     delete.deleteColumn(FAMILIES[0], null);
1980     ht.delete(delete);
1981 
1982     // Cleanup null qualifier
1983     delete = new Delete(ROW);
1984     delete.deleteColumns(FAMILIES[0], null);
1985     ht.delete(delete);
1986 
1987     // Expected client behavior might be that you can re-put deleted values
1988     // But alas, this is not to be.  We can't put them back in either case.
1989 
1990     put = new Put(ROW);
1991     put.add(FAMILIES[0], QUALIFIER, ts[0], VALUES[0]); // 1000
1992     put.add(FAMILIES[0], QUALIFIER, ts[4], VALUES[4]); // 5000
1993     ht.put(put);
1994 
1995 
1996     // It used to be due to the internal implementation of Get, that
1997     // the Get() call would return ts[4] UNLIKE the Scan below. With
1998     // the switch to using Scan for Get this is no longer the case.
1999     get = new Get(ROW);
2000     get.addFamily(FAMILIES[0]);
2001     get.setMaxVersions(Integer.MAX_VALUE);
2002     result = ht.get(get);
2003     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
2004         new long [] {ts[1], ts[2], ts[3]},
2005         new byte[][] {VALUES[1], VALUES[2], VALUES[3]},
2006         0, 2);
2007 
2008     // The Scanner returns the previous values, the expected-naive-unexpected behavior
2009 
2010     scan = new Scan(ROW);
2011     scan.addFamily(FAMILIES[0]);
2012     scan.setMaxVersions(Integer.MAX_VALUE);
2013     result = getSingleScanResult(ht, scan);
2014     assertNResult(result, ROW, FAMILIES[0], QUALIFIER,
2015         new long [] {ts[1], ts[2], ts[3]},
2016         new byte[][] {VALUES[1], VALUES[2], VALUES[3]},
2017         0, 2);
2018 
2019     // Test deleting an entire family from one row but not the other various ways
2020 
2021     put = new Put(ROWS[0]);
2022     put.add(FAMILIES[1], QUALIFIER, ts[0], VALUES[0]);
2023     put.add(FAMILIES[1], QUALIFIER, ts[1], VALUES[1]);
2024     put.add(FAMILIES[2], QUALIFIER, ts[2], VALUES[2]);
2025     put.add(FAMILIES[2], QUALIFIER, ts[3], VALUES[3]);
2026     ht.put(put);
2027 
2028     put = new Put(ROWS[1]);
2029     put.add(FAMILIES[1], QUALIFIER, ts[0], VALUES[0]);
2030     put.add(FAMILIES[1], QUALIFIER, ts[1], VALUES[1]);
2031     put.add(FAMILIES[2], QUALIFIER, ts[2], VALUES[2]);
2032     put.add(FAMILIES[2], QUALIFIER, ts[3], VALUES[3]);
2033     ht.put(put);
2034 
2035     put = new Put(ROWS[2]);
2036     put.add(FAMILIES[1], QUALIFIER, ts[0], VALUES[0]);
2037     put.add(FAMILIES[1], QUALIFIER, ts[1], VALUES[1]);
2038     put.add(FAMILIES[2], QUALIFIER, ts[2], VALUES[2]);
2039     put.add(FAMILIES[2], QUALIFIER, ts[3], VALUES[3]);
2040     ht.put(put);
2041 
2042     // Assert that above went in.
2043     get = new Get(ROWS[2]);
2044     get.addFamily(FAMILIES[1]);
2045     get.addFamily(FAMILIES[2]);
2046     get.setMaxVersions(Integer.MAX_VALUE);
2047     result = ht.get(get);
2048     assertTrue("Expected 4 key but received " + result.size() + ": " + result,
2049         result.size() == 4);
2050 
2051     delete = new Delete(ROWS[0]);
2052     delete.deleteFamily(FAMILIES[2]);
2053     ht.delete(delete);
2054 
2055     delete = new Delete(ROWS[1]);
2056     delete.deleteColumns(FAMILIES[1], QUALIFIER);
2057     ht.delete(delete);
2058 
2059     delete = new Delete(ROWS[2]);
2060     delete.deleteColumn(FAMILIES[1], QUALIFIER);
2061     delete.deleteColumn(FAMILIES[1], QUALIFIER);
2062     delete.deleteColumn(FAMILIES[2], QUALIFIER);
2063     ht.delete(delete);
2064 
2065     get = new Get(ROWS[0]);
2066     get.addFamily(FAMILIES[1]);
2067     get.addFamily(FAMILIES[2]);
2068     get.setMaxVersions(Integer.MAX_VALUE);
2069     result = ht.get(get);
2070     assertTrue("Expected 2 keys but received " + result.size(),
2071         result.size() == 2);
2072     assertNResult(result, ROWS[0], FAMILIES[1], QUALIFIER,
2073         new long [] {ts[0], ts[1]},
2074         new byte[][] {VALUES[0], VALUES[1]},
2075         0, 1);
2076 
2077     scan = new Scan(ROWS[0]);
2078     scan.addFamily(FAMILIES[1]);
2079     scan.addFamily(FAMILIES[2]);
2080     scan.setMaxVersions(Integer.MAX_VALUE);
2081     result = getSingleScanResult(ht, scan);
2082     assertTrue("Expected 2 keys but received " + result.size(),
2083         result.size() == 2);
2084     assertNResult(result, ROWS[0], FAMILIES[1], QUALIFIER,
2085         new long [] {ts[0], ts[1]},
2086         new byte[][] {VALUES[0], VALUES[1]},
2087         0, 1);
2088 
2089     get = new Get(ROWS[1]);
2090     get.addFamily(FAMILIES[1]);
2091     get.addFamily(FAMILIES[2]);
2092     get.setMaxVersions(Integer.MAX_VALUE);
2093     result = ht.get(get);
2094     assertTrue("Expected 2 keys but received " + result.size(),
2095         result.size() == 2);
2096 
2097     scan = new Scan(ROWS[1]);
2098     scan.addFamily(FAMILIES[1]);
2099     scan.addFamily(FAMILIES[2]);
2100     scan.setMaxVersions(Integer.MAX_VALUE);
2101     result = getSingleScanResult(ht, scan);
2102     assertTrue("Expected 2 keys but received " + result.size(),
2103         result.size() == 2);
2104 
2105     get = new Get(ROWS[2]);
2106     get.addFamily(FAMILIES[1]);
2107     get.addFamily(FAMILIES[2]);
2108     get.setMaxVersions(Integer.MAX_VALUE);
2109     result = ht.get(get);
2110     assertEquals(1, result.size());
2111     assertNResult(result, ROWS[2], FAMILIES[2], QUALIFIER,
2112         new long [] {ts[2]},
2113         new byte[][] {VALUES[2]},
2114         0, 0);
2115 
2116     scan = new Scan(ROWS[2]);
2117     scan.addFamily(FAMILIES[1]);
2118     scan.addFamily(FAMILIES[2]);
2119     scan.setMaxVersions(Integer.MAX_VALUE);
2120     result = getSingleScanResult(ht, scan);
2121     assertEquals(1, result.size());
2122     assertNResult(result, ROWS[2], FAMILIES[2], QUALIFIER,
2123         new long [] {ts[2]},
2124         new byte[][] {VALUES[2]},
2125         0, 0);
2126 
2127     // Test if we delete the family first in one row (HBASE-1541)
2128 
2129     delete = new Delete(ROWS[3]);
2130     delete.deleteFamily(FAMILIES[1]);
2131     ht.delete(delete);
2132 
2133     put = new Put(ROWS[3]);
2134     put.add(FAMILIES[2], QUALIFIER, VALUES[0]);
2135     ht.put(put);
2136 
2137     put = new Put(ROWS[4]);
2138     put.add(FAMILIES[1], QUALIFIER, VALUES[1]);
2139     put.add(FAMILIES[2], QUALIFIER, VALUES[2]);
2140     ht.put(put);
2141 
2142     get = new Get(ROWS[3]);
2143     get.addFamily(FAMILIES[1]);
2144     get.addFamily(FAMILIES[2]);
2145     get.setMaxVersions(Integer.MAX_VALUE);
2146     result = ht.get(get);
2147     assertTrue("Expected 1 key but received " + result.size(),
2148         result.size() == 1);
2149 
2150     get = new Get(ROWS[4]);
2151     get.addFamily(FAMILIES[1]);
2152     get.addFamily(FAMILIES[2]);
2153     get.setMaxVersions(Integer.MAX_VALUE);
2154     result = ht.get(get);
2155     assertTrue("Expected 2 keys but received " + result.size(),
2156         result.size() == 2);
2157 
2158     scan = new Scan(ROWS[3]);
2159     scan.addFamily(FAMILIES[1]);
2160     scan.addFamily(FAMILIES[2]);
2161     scan.setMaxVersions(Integer.MAX_VALUE);
2162     ResultScanner scanner = ht.getScanner(scan);
2163     result = scanner.next();
2164     assertTrue("Expected 1 key but received " + result.size(),
2165         result.size() == 1);
2166     assertTrue(Bytes.equals(CellUtil.cloneRow(result.rawCells()[0]), ROWS[3]));
2167     assertTrue(Bytes.equals(CellUtil.cloneValue(result.rawCells()[0]), VALUES[0]));
2168     result = scanner.next();
2169     assertTrue("Expected 2 keys but received " + result.size(),
2170         result.size() == 2);
2171     assertTrue(Bytes.equals(CellUtil.cloneRow(result.rawCells()[0]), ROWS[4]));
2172     assertTrue(Bytes.equals(CellUtil.cloneRow(result.rawCells()[1]), ROWS[4]));
2173     assertTrue(Bytes.equals(CellUtil.cloneValue(result.rawCells()[0]), VALUES[1]));
2174     assertTrue(Bytes.equals(CellUtil.cloneValue(result.rawCells()[1]), VALUES[2]));
2175     scanner.close();
2176 
2177     // Add test of bulk deleting.
2178     for (int i = 0; i < 10; i++) {
2179       byte [] bytes = Bytes.toBytes(i);
2180       put = new Put(bytes);
2181       put.setDurability(Durability.SKIP_WAL);
2182       put.add(FAMILIES[0], QUALIFIER, bytes);
2183       ht.put(put);
2184     }
2185     for (int i = 0; i < 10; i++) {
2186       byte [] bytes = Bytes.toBytes(i);
2187       get = new Get(bytes);
2188       get.addFamily(FAMILIES[0]);
2189       result = ht.get(get);
2190       assertTrue(result.size() == 1);
2191     }
2192     ArrayList<Delete> deletes = new ArrayList<Delete>();
2193     for (int i = 0; i < 10; i++) {
2194       byte [] bytes = Bytes.toBytes(i);
2195       delete = new Delete(bytes);
2196       delete.deleteFamily(FAMILIES[0]);
2197       deletes.add(delete);
2198     }
2199     ht.delete(deletes);
2200     for (int i = 0; i < 10; i++) {
2201       byte [] bytes = Bytes.toBytes(i);
2202       get = new Get(bytes);
2203       get.addFamily(FAMILIES[0]);
2204       result = ht.get(get);
2205       assertTrue(result.size() == 0);
2206     }
2207   }
2208 
2209   /*
2210    * Baseline "scalability" test.
2211    *
2212    * Tests one hundred families, one million columns, one million versions
2213    */
2214   @Ignore @Test
2215   public void testMillions() throws Exception {
2216 
2217     // 100 families
2218 
2219     // millions of columns
2220 
2221     // millions of versions
2222 
2223   }
2224 
2225   @Ignore @Test
2226   public void testMultipleRegionsAndBatchPuts() throws Exception {
2227     // Two family table
2228 
2229     // Insert lots of rows
2230 
2231     // Insert to the same row with batched puts
2232 
2233     // Insert to multiple rows with batched puts
2234 
2235     // Split the table
2236 
2237     // Get row from first region
2238 
2239     // Get row from second region
2240 
2241     // Scan all rows
2242 
2243     // Insert to multiple regions with batched puts
2244 
2245     // Get row from first region
2246 
2247     // Get row from second region
2248 
2249     // Scan all rows
2250 
2251 
2252   }
2253 
2254   @Ignore @Test
2255   public void testMultipleRowMultipleFamily() throws Exception {
2256 
2257   }
2258 
2259   //
2260   // JIRA Testers
2261   //
2262 
2263   /**
2264    * HBASE-867
2265    *    If millions of columns in a column family, hbase scanner won't come up
2266    *
2267    *    Test will create numRows rows, each with numColsPerRow columns
2268    *    (1 version each), and attempt to scan them all.
2269    *
2270    *    To test at scale, up numColsPerRow to the millions
2271    *    (have not gotten that to work running as junit though)
2272    */
2273   @Test
2274   public void testJiraTest867() throws Exception {
2275     int numRows = 10;
2276     int numColsPerRow = 2000;
2277 
2278     byte [] TABLE = Bytes.toBytes("testJiraTest867");
2279 
2280     byte [][] ROWS = makeN(ROW, numRows);
2281     byte [][] QUALIFIERS = makeN(QUALIFIER, numColsPerRow);
2282 
2283     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
2284 
2285     // Insert rows
2286 
2287     for(int i=0;i<numRows;i++) {
2288       Put put = new Put(ROWS[i]);
2289       put.setDurability(Durability.SKIP_WAL);
2290       for(int j=0;j<numColsPerRow;j++) {
2291         put.add(FAMILY, QUALIFIERS[j], QUALIFIERS[j]);
2292       }
2293       assertTrue("Put expected to contain " + numColsPerRow + " columns but " +
2294           "only contains " + put.size(), put.size() == numColsPerRow);
2295       ht.put(put);
2296     }
2297 
2298     // Get a row
2299     Get get = new Get(ROWS[numRows-1]);
2300     Result result = ht.get(get);
2301     assertNumKeys(result, numColsPerRow);
2302     Cell [] keys = result.rawCells();
2303     for(int i=0;i<result.size();i++) {
2304       assertKey(keys[i], ROWS[numRows-1], FAMILY, QUALIFIERS[i], QUALIFIERS[i]);
2305     }
2306 
2307     // Scan the rows
2308     Scan scan = new Scan();
2309     ResultScanner scanner = ht.getScanner(scan);
2310     int rowCount = 0;
2311     while((result = scanner.next()) != null) {
2312       assertNumKeys(result, numColsPerRow);
2313       Cell [] kvs = result.rawCells();
2314       for(int i=0;i<numColsPerRow;i++) {
2315         assertKey(kvs[i], ROWS[rowCount], FAMILY, QUALIFIERS[i], QUALIFIERS[i]);
2316       }
2317       rowCount++;
2318     }
2319     scanner.close();
2320     assertTrue("Expected to scan " + numRows + " rows but actually scanned "
2321         + rowCount + " rows", rowCount == numRows);
2322 
2323     // flush and try again
2324 
2325     TEST_UTIL.flush();
2326 
2327     // Get a row
2328     get = new Get(ROWS[numRows-1]);
2329     result = ht.get(get);
2330     assertNumKeys(result, numColsPerRow);
2331     keys = result.rawCells();
2332     for(int i=0;i<result.size();i++) {
2333       assertKey(keys[i], ROWS[numRows-1], FAMILY, QUALIFIERS[i], QUALIFIERS[i]);
2334     }
2335 
2336     // Scan the rows
2337     scan = new Scan();
2338     scanner = ht.getScanner(scan);
2339     rowCount = 0;
2340     while((result = scanner.next()) != null) {
2341       assertNumKeys(result, numColsPerRow);
2342       Cell [] kvs = result.rawCells();
2343       for(int i=0;i<numColsPerRow;i++) {
2344         assertKey(kvs[i], ROWS[rowCount], FAMILY, QUALIFIERS[i], QUALIFIERS[i]);
2345       }
2346       rowCount++;
2347     }
2348     scanner.close();
2349     assertTrue("Expected to scan " + numRows + " rows but actually scanned "
2350         + rowCount + " rows", rowCount == numRows);
2351 
2352   }
2353 
2354   /**
2355    * HBASE-861
2356    *    get with timestamp will return a value if there is a version with an
2357    *    earlier timestamp
2358    */
2359   @Test
2360   public void testJiraTest861() throws Exception {
2361 
2362     byte [] TABLE = Bytes.toBytes("testJiraTest861");
2363     byte [][] VALUES = makeNAscii(VALUE, 7);
2364     long [] STAMPS = makeStamps(7);
2365 
2366     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 10);
2367 
2368     // Insert three versions
2369 
2370     Put put = new Put(ROW);
2371     put.add(FAMILY, QUALIFIER, STAMPS[3], VALUES[3]);
2372     put.add(FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
2373     put.add(FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
2374     ht.put(put);
2375 
2376     // Get the middle value
2377     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
2378 
2379     // Try to get one version before (expect fail)
2380     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[1]);
2381 
2382     // Try to get one version after (expect fail)
2383     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[5]);
2384 
2385     // Try same from storefile
2386     TEST_UTIL.flush();
2387     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
2388     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[1]);
2389     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[5]);
2390 
2391     // Insert two more versions surrounding others, into memstore
2392     put = new Put(ROW);
2393     put.add(FAMILY, QUALIFIER, STAMPS[0], VALUES[0]);
2394     put.add(FAMILY, QUALIFIER, STAMPS[6], VALUES[6]);
2395     ht.put(put);
2396 
2397     // Check we can get everything we should and can't get what we shouldn't
2398     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[0], VALUES[0]);
2399     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[1]);
2400     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
2401     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[3], VALUES[3]);
2402     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
2403     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[5]);
2404     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[6], VALUES[6]);
2405 
2406     // Try same from two storefiles
2407     TEST_UTIL.flush();
2408     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[0], VALUES[0]);
2409     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[1]);
2410     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
2411     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[3], VALUES[3]);
2412     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
2413     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[5]);
2414     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[6], VALUES[6]);
2415 
2416   }
2417 
2418   /**
2419    * HBASE-33
2420    *    Add a HTable get/obtainScanner method that retrieves all versions of a
2421    *    particular column and row between two timestamps
2422    */
2423   @Test
2424   public void testJiraTest33() throws Exception {
2425 
2426     byte [] TABLE = Bytes.toBytes("testJiraTest33");
2427     byte [][] VALUES = makeNAscii(VALUE, 7);
2428     long [] STAMPS = makeStamps(7);
2429 
2430     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 10);
2431 
2432     // Insert lots versions
2433 
2434     Put put = new Put(ROW);
2435     put.add(FAMILY, QUALIFIER, STAMPS[0], VALUES[0]);
2436     put.add(FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
2437     put.add(FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
2438     put.add(FAMILY, QUALIFIER, STAMPS[3], VALUES[3]);
2439     put.add(FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
2440     put.add(FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
2441     ht.put(put);
2442 
2443     getVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2444     getVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 2);
2445     getVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 4, 5);
2446     getVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 2, 3);
2447 
2448     scanVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2449     scanVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 2);
2450     scanVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 4, 5);
2451     scanVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 2, 3);
2452 
2453     // Try same from storefile
2454     TEST_UTIL.flush();
2455 
2456     getVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2457     getVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 2);
2458     getVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 4, 5);
2459     getVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 2, 3);
2460 
2461     scanVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2462     scanVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 2);
2463     scanVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 4, 5);
2464     scanVersionRangeAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 2, 3);
2465 
2466   }
2467 
2468   /**
2469    * HBASE-1014
2470    *    commit(BatchUpdate) method should return timestamp
2471    */
2472   @Test
2473   public void testJiraTest1014() throws Exception {
2474 
2475     byte [] TABLE = Bytes.toBytes("testJiraTest1014");
2476 
2477     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 10);
2478 
2479     long manualStamp = 12345;
2480 
2481     // Insert lots versions
2482 
2483     Put put = new Put(ROW);
2484     put.add(FAMILY, QUALIFIER, manualStamp, VALUE);
2485     ht.put(put);
2486 
2487     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, manualStamp, VALUE);
2488     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, manualStamp-1);
2489     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, manualStamp+1);
2490 
2491   }
2492 
2493   /**
2494    * HBASE-1182
2495    *    Scan for columns > some timestamp
2496    */
2497   @Test
2498   public void testJiraTest1182() throws Exception {
2499 
2500     byte [] TABLE = Bytes.toBytes("testJiraTest1182");
2501     byte [][] VALUES = makeNAscii(VALUE, 7);
2502     long [] STAMPS = makeStamps(7);
2503 
2504     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 10);
2505 
2506     // Insert lots versions
2507 
2508     Put put = new Put(ROW);
2509     put.add(FAMILY, QUALIFIER, STAMPS[0], VALUES[0]);
2510     put.add(FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
2511     put.add(FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
2512     put.add(FAMILY, QUALIFIER, STAMPS[3], VALUES[3]);
2513     put.add(FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
2514     put.add(FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
2515     ht.put(put);
2516 
2517     getVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2518     getVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 2, 5);
2519     getVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 4, 5);
2520 
2521     scanVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2522     scanVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 2, 5);
2523     scanVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 4, 5);
2524 
2525     // Try same from storefile
2526     TEST_UTIL.flush();
2527 
2528     getVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2529     getVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 2, 5);
2530     getVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 4, 5);
2531 
2532     scanVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2533     scanVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 2, 5);
2534     scanVersionRangeAndVerifyGreaterThan(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 4, 5);
2535   }
2536 
2537   /**
2538    * HBASE-52
2539    *    Add a means of scanning over all versions
2540    */
2541   @Test
2542   public void testJiraTest52() throws Exception {
2543     byte [] TABLE = Bytes.toBytes("testJiraTest52");
2544     byte [][] VALUES = makeNAscii(VALUE, 7);
2545     long [] STAMPS = makeStamps(7);
2546 
2547     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 10);
2548 
2549     // Insert lots versions
2550 
2551     Put put = new Put(ROW);
2552     put.add(FAMILY, QUALIFIER, STAMPS[0], VALUES[0]);
2553     put.add(FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
2554     put.add(FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
2555     put.add(FAMILY, QUALIFIER, STAMPS[3], VALUES[3]);
2556     put.add(FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
2557     put.add(FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
2558     ht.put(put);
2559 
2560     getAllVersionsAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2561 
2562     scanAllVersionsAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2563 
2564     // Try same from storefile
2565     TEST_UTIL.flush();
2566 
2567     getAllVersionsAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2568 
2569     scanAllVersionsAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS, VALUES, 0, 5);
2570   }
2571 
2572   //
2573   // Bulk Testers
2574   //
2575 
2576   private void getVersionRangeAndVerifyGreaterThan(Table ht, byte [] row,
2577       byte [] family, byte [] qualifier, long [] stamps, byte [][] values,
2578       int start, int end)
2579   throws IOException {
2580     Get get = new Get(row);
2581     get.addColumn(family, qualifier);
2582     get.setMaxVersions(Integer.MAX_VALUE);
2583     get.setTimeRange(stamps[start+1], Long.MAX_VALUE);
2584     Result result = ht.get(get);
2585     assertNResult(result, row, family, qualifier, stamps, values, start+1, end);
2586   }
2587 
2588   private void getVersionRangeAndVerify(Table ht, byte [] row, byte [] family,
2589       byte [] qualifier, long [] stamps, byte [][] values, int start, int end)
2590   throws IOException {
2591     Get get = new Get(row);
2592     get.addColumn(family, qualifier);
2593     get.setMaxVersions(Integer.MAX_VALUE);
2594     get.setTimeRange(stamps[start], stamps[end]+1);
2595     Result result = ht.get(get);
2596     assertNResult(result, row, family, qualifier, stamps, values, start, end);
2597   }
2598 
2599   private void getAllVersionsAndVerify(Table ht, byte [] row, byte [] family,
2600       byte [] qualifier, long [] stamps, byte [][] values, int start, int end)
2601   throws IOException {
2602     Get get = new Get(row);
2603     get.addColumn(family, qualifier);
2604     get.setMaxVersions(Integer.MAX_VALUE);
2605     Result result = ht.get(get);
2606     assertNResult(result, row, family, qualifier, stamps, values, start, end);
2607   }
2608 
2609   private void scanVersionRangeAndVerifyGreaterThan(Table ht, byte [] row,
2610       byte [] family, byte [] qualifier, long [] stamps, byte [][] values,
2611       int start, int end)
2612   throws IOException {
2613     Scan scan = new Scan(row);
2614     scan.addColumn(family, qualifier);
2615     scan.setMaxVersions(Integer.MAX_VALUE);
2616     scan.setTimeRange(stamps[start+1], Long.MAX_VALUE);
2617     Result result = getSingleScanResult(ht, scan);
2618     assertNResult(result, row, family, qualifier, stamps, values, start+1, end);
2619   }
2620 
2621   private void scanVersionRangeAndVerify(Table ht, byte [] row, byte [] family,
2622       byte [] qualifier, long [] stamps, byte [][] values, int start, int end)
2623   throws IOException {
2624     Scan scan = new Scan(row);
2625     scan.addColumn(family, qualifier);
2626     scan.setMaxVersions(Integer.MAX_VALUE);
2627     scan.setTimeRange(stamps[start], stamps[end]+1);
2628     Result result = getSingleScanResult(ht, scan);
2629     assertNResult(result, row, family, qualifier, stamps, values, start, end);
2630   }
2631 
2632   private void scanAllVersionsAndVerify(Table ht, byte [] row, byte [] family,
2633       byte [] qualifier, long [] stamps, byte [][] values, int start, int end)
2634   throws IOException {
2635     Scan scan = new Scan(row);
2636     scan.addColumn(family, qualifier);
2637     scan.setMaxVersions(Integer.MAX_VALUE);
2638     Result result = getSingleScanResult(ht, scan);
2639     assertNResult(result, row, family, qualifier, stamps, values, start, end);
2640   }
2641 
2642   private void getVersionAndVerify(Table ht, byte [] row, byte [] family,
2643       byte [] qualifier, long stamp, byte [] value)
2644   throws Exception {
2645     Get get = new Get(row);
2646     get.addColumn(family, qualifier);
2647     get.setTimeStamp(stamp);
2648     get.setMaxVersions(Integer.MAX_VALUE);
2649     Result result = ht.get(get);
2650     assertSingleResult(result, row, family, qualifier, stamp, value);
2651   }
2652 
2653   private void getVersionAndVerifyMissing(Table ht, byte [] row, byte [] family,
2654       byte [] qualifier, long stamp)
2655   throws Exception {
2656     Get get = new Get(row);
2657     get.addColumn(family, qualifier);
2658     get.setTimeStamp(stamp);
2659     get.setMaxVersions(Integer.MAX_VALUE);
2660     Result result = ht.get(get);
2661     assertEmptyResult(result);
2662   }
2663 
2664   private void scanVersionAndVerify(Table ht, byte [] row, byte [] family,
2665       byte [] qualifier, long stamp, byte [] value)
2666   throws Exception {
2667     Scan scan = new Scan(row);
2668     scan.addColumn(family, qualifier);
2669     scan.setTimeStamp(stamp);
2670     scan.setMaxVersions(Integer.MAX_VALUE);
2671     Result result = getSingleScanResult(ht, scan);
2672     assertSingleResult(result, row, family, qualifier, stamp, value);
2673   }
2674 
2675   private void scanVersionAndVerifyMissing(Table ht, byte [] row,
2676       byte [] family, byte [] qualifier, long stamp)
2677   throws Exception {
2678     Scan scan = new Scan(row);
2679     scan.addColumn(family, qualifier);
2680     scan.setTimeStamp(stamp);
2681     scan.setMaxVersions(Integer.MAX_VALUE);
2682     Result result = getSingleScanResult(ht, scan);
2683     assertNullResult(result);
2684   }
2685 
2686   private void getTestNull(Table ht, byte [] row, byte [] family,
2687       byte [] value)
2688   throws Exception {
2689 
2690     Get get = new Get(row);
2691     get.addColumn(family, null);
2692     Result result = ht.get(get);
2693     assertSingleResult(result, row, family, null, value);
2694 
2695     get = new Get(row);
2696     get.addColumn(family, HConstants.EMPTY_BYTE_ARRAY);
2697     result = ht.get(get);
2698     assertSingleResult(result, row, family, HConstants.EMPTY_BYTE_ARRAY, value);
2699 
2700     get = new Get(row);
2701     get.addFamily(family);
2702     result = ht.get(get);
2703     assertSingleResult(result, row, family, HConstants.EMPTY_BYTE_ARRAY, value);
2704 
2705     get = new Get(row);
2706     result = ht.get(get);
2707     assertSingleResult(result, row, family, HConstants.EMPTY_BYTE_ARRAY, value);
2708 
2709   }
2710 
2711   private void scanTestNull(Table ht, byte[] row, byte[] family, byte[] value)
2712       throws Exception {
2713     scanTestNull(ht, row, family, value, false);
2714   }
2715 
2716   private void scanTestNull(Table ht, byte[] row, byte[] family, byte[] value,
2717       boolean isReversedScan) throws Exception {
2718 
2719     Scan scan = new Scan();
2720     scan.setReversed(isReversedScan);
2721     scan.addColumn(family, null);
2722     Result result = getSingleScanResult(ht, scan);
2723     assertSingleResult(result, row, family, HConstants.EMPTY_BYTE_ARRAY, value);
2724 
2725     scan = new Scan();
2726     scan.setReversed(isReversedScan);
2727     scan.addColumn(family, HConstants.EMPTY_BYTE_ARRAY);
2728     result = getSingleScanResult(ht, scan);
2729     assertSingleResult(result, row, family, HConstants.EMPTY_BYTE_ARRAY, value);
2730 
2731     scan = new Scan();
2732     scan.setReversed(isReversedScan);
2733     scan.addFamily(family);
2734     result = getSingleScanResult(ht, scan);
2735     assertSingleResult(result, row, family, HConstants.EMPTY_BYTE_ARRAY, value);
2736 
2737     scan = new Scan();
2738     scan.setReversed(isReversedScan);
2739     result = getSingleScanResult(ht, scan);
2740     assertSingleResult(result, row, family, HConstants.EMPTY_BYTE_ARRAY, value);
2741 
2742   }
2743 
2744   private void singleRowGetTest(Table ht, byte [][] ROWS, byte [][] FAMILIES,
2745       byte [][] QUALIFIERS, byte [][] VALUES)
2746   throws Exception {
2747 
2748     // Single column from memstore
2749     Get get = new Get(ROWS[0]);
2750     get.addColumn(FAMILIES[4], QUALIFIERS[0]);
2751     Result result = ht.get(get);
2752     assertSingleResult(result, ROWS[0], FAMILIES[4], QUALIFIERS[0], VALUES[0]);
2753 
2754     // Single column from storefile
2755     get = new Get(ROWS[0]);
2756     get.addColumn(FAMILIES[2], QUALIFIERS[2]);
2757     result = ht.get(get);
2758     assertSingleResult(result, ROWS[0], FAMILIES[2], QUALIFIERS[2], VALUES[2]);
2759 
2760     // Single column from storefile, family match
2761     get = new Get(ROWS[0]);
2762     get.addFamily(FAMILIES[7]);
2763     result = ht.get(get);
2764     assertSingleResult(result, ROWS[0], FAMILIES[7], QUALIFIERS[7], VALUES[7]);
2765 
2766     // Two columns, one from memstore one from storefile, same family,
2767     // wildcard match
2768     get = new Get(ROWS[0]);
2769     get.addFamily(FAMILIES[4]);
2770     result = ht.get(get);
2771     assertDoubleResult(result, ROWS[0], FAMILIES[4], QUALIFIERS[0], VALUES[0],
2772         FAMILIES[4], QUALIFIERS[4], VALUES[4]);
2773 
2774     // Two columns, one from memstore one from storefile, same family,
2775     // explicit match
2776     get = new Get(ROWS[0]);
2777     get.addColumn(FAMILIES[4], QUALIFIERS[0]);
2778     get.addColumn(FAMILIES[4], QUALIFIERS[4]);
2779     result = ht.get(get);
2780     assertDoubleResult(result, ROWS[0], FAMILIES[4], QUALIFIERS[0], VALUES[0],
2781         FAMILIES[4], QUALIFIERS[4], VALUES[4]);
2782 
2783     // Three column, one from memstore two from storefile, different families,
2784     // wildcard match
2785     get = new Get(ROWS[0]);
2786     get.addFamily(FAMILIES[4]);
2787     get.addFamily(FAMILIES[7]);
2788     result = ht.get(get);
2789     assertNResult(result, ROWS[0], FAMILIES, QUALIFIERS, VALUES,
2790         new int [][] { {4, 0, 0}, {4, 4, 4}, {7, 7, 7} });
2791 
2792     // Multiple columns from everywhere storefile, many family, wildcard
2793     get = new Get(ROWS[0]);
2794     get.addFamily(FAMILIES[2]);
2795     get.addFamily(FAMILIES[4]);
2796     get.addFamily(FAMILIES[6]);
2797     get.addFamily(FAMILIES[7]);
2798     result = ht.get(get);
2799     assertNResult(result, ROWS[0], FAMILIES, QUALIFIERS, VALUES,
2800         new int [][] {
2801           {2, 2, 2}, {2, 4, 4}, {4, 0, 0}, {4, 4, 4}, {6, 6, 6}, {6, 7, 7}, {7, 7, 7}
2802     });
2803 
2804     // Multiple columns from everywhere storefile, many family, wildcard
2805     get = new Get(ROWS[0]);
2806     get.addColumn(FAMILIES[2], QUALIFIERS[2]);
2807     get.addColumn(FAMILIES[2], QUALIFIERS[4]);
2808     get.addColumn(FAMILIES[4], QUALIFIERS[0]);
2809     get.addColumn(FAMILIES[4], QUALIFIERS[4]);
2810     get.addColumn(FAMILIES[6], QUALIFIERS[6]);
2811     get.addColumn(FAMILIES[6], QUALIFIERS[7]);
2812     get.addColumn(FAMILIES[7], QUALIFIERS[7]);
2813     get.addColumn(FAMILIES[7], QUALIFIERS[8]);
2814     result = ht.get(get);
2815     assertNResult(result, ROWS[0], FAMILIES, QUALIFIERS, VALUES,
2816         new int [][] {
2817           {2, 2, 2}, {2, 4, 4}, {4, 0, 0}, {4, 4, 4}, {6, 6, 6}, {6, 7, 7}, {7, 7, 7}
2818     });
2819 
2820     // Everything
2821     get = new Get(ROWS[0]);
2822     result = ht.get(get);
2823     assertNResult(result, ROWS[0], FAMILIES, QUALIFIERS, VALUES,
2824         new int [][] {
2825           {2, 2, 2}, {2, 4, 4}, {4, 0, 0}, {4, 4, 4}, {6, 6, 6}, {6, 7, 7}, {7, 7, 7}, {9, 0, 0}
2826     });
2827 
2828     // Get around inserted columns
2829 
2830     get = new Get(ROWS[1]);
2831     result = ht.get(get);
2832     assertEmptyResult(result);
2833 
2834     get = new Get(ROWS[0]);
2835     get.addColumn(FAMILIES[4], QUALIFIERS[3]);
2836     get.addColumn(FAMILIES[2], QUALIFIERS[3]);
2837     result = ht.get(get);
2838     assertEmptyResult(result);
2839 
2840   }
2841 
2842   private void singleRowScanTest(Table ht, byte [][] ROWS, byte [][] FAMILIES,
2843       byte [][] QUALIFIERS, byte [][] VALUES)
2844   throws Exception {
2845 
2846     // Single column from memstore
2847     Scan scan = new Scan();
2848     scan.addColumn(FAMILIES[4], QUALIFIERS[0]);
2849     Result result = getSingleScanResult(ht, scan);
2850     assertSingleResult(result, ROWS[0], FAMILIES[4], QUALIFIERS[0], VALUES[0]);
2851 
2852     // Single column from storefile
2853     scan = new Scan();
2854     scan.addColumn(FAMILIES[2], QUALIFIERS[2]);
2855     result = getSingleScanResult(ht, scan);
2856     assertSingleResult(result, ROWS[0], FAMILIES[2], QUALIFIERS[2], VALUES[2]);
2857 
2858     // Single column from storefile, family match
2859     scan = new Scan();
2860     scan.addFamily(FAMILIES[7]);
2861     result = getSingleScanResult(ht, scan);
2862     assertSingleResult(result, ROWS[0], FAMILIES[7], QUALIFIERS[7], VALUES[7]);
2863 
2864     // Two columns, one from memstore one from storefile, same family,
2865     // wildcard match
2866     scan = new Scan();
2867     scan.addFamily(FAMILIES[4]);
2868     result = getSingleScanResult(ht, scan);
2869     assertDoubleResult(result, ROWS[0], FAMILIES[4], QUALIFIERS[0], VALUES[0],
2870         FAMILIES[4], QUALIFIERS[4], VALUES[4]);
2871 
2872     // Two columns, one from memstore one from storefile, same family,
2873     // explicit match
2874     scan = new Scan();
2875     scan.addColumn(FAMILIES[4], QUALIFIERS[0]);
2876     scan.addColumn(FAMILIES[4], QUALIFIERS[4]);
2877     result = getSingleScanResult(ht, scan);
2878     assertDoubleResult(result, ROWS[0], FAMILIES[4], QUALIFIERS[0], VALUES[0],
2879         FAMILIES[4], QUALIFIERS[4], VALUES[4]);
2880 
2881     // Three column, one from memstore two from storefile, different families,
2882     // wildcard match
2883     scan = new Scan();
2884     scan.addFamily(FAMILIES[4]);
2885     scan.addFamily(FAMILIES[7]);
2886     result = getSingleScanResult(ht, scan);
2887     assertNResult(result, ROWS[0], FAMILIES, QUALIFIERS, VALUES,
2888         new int [][] { {4, 0, 0}, {4, 4, 4}, {7, 7, 7} });
2889 
2890     // Multiple columns from everywhere storefile, many family, wildcard
2891     scan = new Scan();
2892     scan.addFamily(FAMILIES[2]);
2893     scan.addFamily(FAMILIES[4]);
2894     scan.addFamily(FAMILIES[6]);
2895     scan.addFamily(FAMILIES[7]);
2896     result = getSingleScanResult(ht, scan);
2897     assertNResult(result, ROWS[0], FAMILIES, QUALIFIERS, VALUES,
2898         new int [][] {
2899           {2, 2, 2}, {2, 4, 4}, {4, 0, 0}, {4, 4, 4}, {6, 6, 6}, {6, 7, 7}, {7, 7, 7}
2900     });
2901 
2902     // Multiple columns from everywhere storefile, many family, wildcard
2903     scan = new Scan();
2904     scan.addColumn(FAMILIES[2], QUALIFIERS[2]);
2905     scan.addColumn(FAMILIES[2], QUALIFIERS[4]);
2906     scan.addColumn(FAMILIES[4], QUALIFIERS[0]);
2907     scan.addColumn(FAMILIES[4], QUALIFIERS[4]);
2908     scan.addColumn(FAMILIES[6], QUALIFIERS[6]);
2909     scan.addColumn(FAMILIES[6], QUALIFIERS[7]);
2910     scan.addColumn(FAMILIES[7], QUALIFIERS[7]);
2911     scan.addColumn(FAMILIES[7], QUALIFIERS[8]);
2912     result = getSingleScanResult(ht, scan);
2913     assertNResult(result, ROWS[0], FAMILIES, QUALIFIERS, VALUES,
2914         new int [][] {
2915           {2, 2, 2}, {2, 4, 4}, {4, 0, 0}, {4, 4, 4}, {6, 6, 6}, {6, 7, 7}, {7, 7, 7}
2916     });
2917 
2918     // Everything
2919     scan = new Scan();
2920     result = getSingleScanResult(ht, scan);
2921     assertNResult(result, ROWS[0], FAMILIES, QUALIFIERS, VALUES,
2922         new int [][] {
2923           {2, 2, 2}, {2, 4, 4}, {4, 0, 0}, {4, 4, 4}, {6, 6, 6}, {6, 7, 7}, {7, 7, 7}, {9, 0, 0}
2924     });
2925 
2926     // Scan around inserted columns
2927 
2928     scan = new Scan(ROWS[1]);
2929     result = getSingleScanResult(ht, scan);
2930     assertNullResult(result);
2931 
2932     scan = new Scan();
2933     scan.addColumn(FAMILIES[4], QUALIFIERS[3]);
2934     scan.addColumn(FAMILIES[2], QUALIFIERS[3]);
2935     result = getSingleScanResult(ht, scan);
2936     assertNullResult(result);
2937   }
2938 
2939   /**
2940    * Verify a single column using gets.
2941    * Expects family and qualifier arrays to be valid for at least
2942    * the range:  idx-2 < idx < idx+2
2943    */
2944   private void getVerifySingleColumn(Table ht,
2945       byte [][] ROWS, int ROWIDX,
2946       byte [][] FAMILIES, int FAMILYIDX,
2947       byte [][] QUALIFIERS, int QUALIFIERIDX,
2948       byte [][] VALUES, int VALUEIDX)
2949   throws Exception {
2950 
2951     Get get = new Get(ROWS[ROWIDX]);
2952     Result result = ht.get(get);
2953     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
2954         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
2955 
2956     get = new Get(ROWS[ROWIDX]);
2957     get.addFamily(FAMILIES[FAMILYIDX]);
2958     result = ht.get(get);
2959     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
2960         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
2961 
2962     get = new Get(ROWS[ROWIDX]);
2963     get.addFamily(FAMILIES[FAMILYIDX-2]);
2964     get.addFamily(FAMILIES[FAMILYIDX]);
2965     get.addFamily(FAMILIES[FAMILYIDX+2]);
2966     result = ht.get(get);
2967     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
2968         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
2969 
2970     get = new Get(ROWS[ROWIDX]);
2971     get.addColumn(FAMILIES[FAMILYIDX], QUALIFIERS[0]);
2972     result = ht.get(get);
2973     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
2974         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
2975 
2976     get = new Get(ROWS[ROWIDX]);
2977     get.addColumn(FAMILIES[FAMILYIDX], QUALIFIERS[1]);
2978     get.addFamily(FAMILIES[FAMILYIDX]);
2979     result = ht.get(get);
2980     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
2981         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
2982 
2983     get = new Get(ROWS[ROWIDX]);
2984     get.addFamily(FAMILIES[FAMILYIDX]);
2985     get.addColumn(FAMILIES[FAMILYIDX+1], QUALIFIERS[1]);
2986     get.addColumn(FAMILIES[FAMILYIDX-2], QUALIFIERS[1]);
2987     get.addFamily(FAMILIES[FAMILYIDX-1]);
2988     get.addFamily(FAMILIES[FAMILYIDX+2]);
2989     result = ht.get(get);
2990     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
2991         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
2992 
2993   }
2994 
2995 
2996   /**
2997    * Verify a single column using scanners.
2998    * Expects family and qualifier arrays to be valid for at least
2999    * the range:  idx-2 to idx+2
3000    * Expects row array to be valid for at least idx to idx+2
3001    */
3002   private void scanVerifySingleColumn(Table ht,
3003       byte [][] ROWS, int ROWIDX,
3004       byte [][] FAMILIES, int FAMILYIDX,
3005       byte [][] QUALIFIERS, int QUALIFIERIDX,
3006       byte [][] VALUES, int VALUEIDX)
3007   throws Exception {
3008 
3009     Scan scan = new Scan();
3010     Result result = getSingleScanResult(ht, scan);
3011     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
3012         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
3013 
3014     scan = new Scan(ROWS[ROWIDX]);
3015     result = getSingleScanResult(ht, scan);
3016     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
3017         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
3018 
3019     scan = new Scan(ROWS[ROWIDX], ROWS[ROWIDX+1]);
3020     result = getSingleScanResult(ht, scan);
3021     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
3022         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
3023 
3024     scan = new Scan(HConstants.EMPTY_START_ROW, ROWS[ROWIDX+1]);
3025     result = getSingleScanResult(ht, scan);
3026     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
3027         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
3028 
3029     scan = new Scan();
3030     scan.addFamily(FAMILIES[FAMILYIDX]);
3031     result = getSingleScanResult(ht, scan);
3032     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
3033         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
3034 
3035     scan = new Scan();
3036     scan.addColumn(FAMILIES[FAMILYIDX], QUALIFIERS[QUALIFIERIDX]);
3037     result = getSingleScanResult(ht, scan);
3038     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
3039         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
3040 
3041     scan = new Scan();
3042     scan.addColumn(FAMILIES[FAMILYIDX], QUALIFIERS[QUALIFIERIDX+1]);
3043     scan.addFamily(FAMILIES[FAMILYIDX]);
3044     result = getSingleScanResult(ht, scan);
3045     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
3046         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
3047 
3048     scan = new Scan();
3049     scan.addColumn(FAMILIES[FAMILYIDX-1], QUALIFIERS[QUALIFIERIDX+1]);
3050     scan.addColumn(FAMILIES[FAMILYIDX], QUALIFIERS[QUALIFIERIDX]);
3051     scan.addFamily(FAMILIES[FAMILYIDX+1]);
3052     result = getSingleScanResult(ht, scan);
3053     assertSingleResult(result, ROWS[ROWIDX], FAMILIES[FAMILYIDX],
3054         QUALIFIERS[QUALIFIERIDX], VALUES[VALUEIDX]);
3055 
3056   }
3057 
3058   /**
3059    * Verify we do not read any values by accident around a single column
3060    * Same requirements as getVerifySingleColumn
3061    */
3062   private void getVerifySingleEmpty(Table ht,
3063       byte [][] ROWS, int ROWIDX,
3064       byte [][] FAMILIES, int FAMILYIDX,
3065       byte [][] QUALIFIERS, int QUALIFIERIDX)
3066   throws Exception {
3067 
3068     Get get = new Get(ROWS[ROWIDX]);
3069     get.addFamily(FAMILIES[4]);
3070     get.addColumn(FAMILIES[4], QUALIFIERS[1]);
3071     Result result = ht.get(get);
3072     assertEmptyResult(result);
3073 
3074     get = new Get(ROWS[ROWIDX]);
3075     get.addFamily(FAMILIES[4]);
3076     get.addColumn(FAMILIES[4], QUALIFIERS[2]);
3077     result = ht.get(get);
3078     assertEmptyResult(result);
3079 
3080     get = new Get(ROWS[ROWIDX]);
3081     get.addFamily(FAMILIES[3]);
3082     get.addColumn(FAMILIES[4], QUALIFIERS[2]);
3083     get.addFamily(FAMILIES[5]);
3084     result = ht.get(get);
3085     assertEmptyResult(result);
3086 
3087     get = new Get(ROWS[ROWIDX+1]);
3088     result = ht.get(get);
3089     assertEmptyResult(result);
3090 
3091   }
3092 
3093   private void scanVerifySingleEmpty(Table ht,
3094       byte [][] ROWS, int ROWIDX,
3095       byte [][] FAMILIES, int FAMILYIDX,
3096       byte [][] QUALIFIERS, int QUALIFIERIDX)
3097   throws Exception {
3098 
3099     Scan scan = new Scan(ROWS[ROWIDX+1]);
3100     Result result = getSingleScanResult(ht, scan);
3101     assertNullResult(result);
3102 
3103     scan = new Scan(ROWS[ROWIDX+1],ROWS[ROWIDX+2]);
3104     result = getSingleScanResult(ht, scan);
3105     assertNullResult(result);
3106 
3107     scan = new Scan(HConstants.EMPTY_START_ROW, ROWS[ROWIDX]);
3108     result = getSingleScanResult(ht, scan);
3109     assertNullResult(result);
3110 
3111     scan = new Scan();
3112     scan.addColumn(FAMILIES[FAMILYIDX], QUALIFIERS[QUALIFIERIDX+1]);
3113     scan.addFamily(FAMILIES[FAMILYIDX-1]);
3114     result = getSingleScanResult(ht, scan);
3115     assertNullResult(result);
3116 
3117   }
3118 
3119   //
3120   // Verifiers
3121   //
3122 
3123   private void assertKey(Cell key, byte [] row, byte [] family,
3124       byte [] qualifier, byte [] value)
3125   throws Exception {
3126     assertTrue("Expected row [" + Bytes.toString(row) + "] " +
3127         "Got row [" + Bytes.toString(CellUtil.cloneRow(key)) +"]",
3128         equals(row, CellUtil.cloneRow(key)));
3129     assertTrue("Expected family [" + Bytes.toString(family) + "] " +
3130         "Got family [" + Bytes.toString(CellUtil.cloneFamily(key)) + "]",
3131         equals(family, CellUtil.cloneFamily(key)));
3132     assertTrue("Expected qualifier [" + Bytes.toString(qualifier) + "] " +
3133         "Got qualifier [" + Bytes.toString(CellUtil.cloneQualifier(key)) + "]",
3134         equals(qualifier, CellUtil.cloneQualifier(key)));
3135     assertTrue("Expected value [" + Bytes.toString(value) + "] " +
3136         "Got value [" + Bytes.toString(CellUtil.cloneValue(key)) + "]",
3137         equals(value, CellUtil.cloneValue(key)));
3138   }
3139 
3140   private void assertIncrementKey(Cell key, byte [] row, byte [] family,
3141       byte [] qualifier, long value)
3142   throws Exception {
3143     assertTrue("Expected row [" + Bytes.toString(row) + "] " +
3144         "Got row [" + Bytes.toString(CellUtil.cloneRow(key)) +"]",
3145         equals(row, CellUtil.cloneRow(key)));
3146     assertTrue("Expected family [" + Bytes.toString(family) + "] " +
3147         "Got family [" + Bytes.toString(CellUtil.cloneFamily(key)) + "]",
3148         equals(family, CellUtil.cloneFamily(key)));
3149     assertTrue("Expected qualifier [" + Bytes.toString(qualifier) + "] " +
3150         "Got qualifier [" + Bytes.toString(CellUtil.cloneQualifier(key)) + "]",
3151         equals(qualifier, CellUtil.cloneQualifier(key)));
3152     assertTrue("Expected value [" + value + "] " +
3153         "Got value [" + Bytes.toLong(CellUtil.cloneValue(key)) + "]",
3154         Bytes.toLong(CellUtil.cloneValue(key)) == value);
3155   }
3156 
3157   private void assertNumKeys(Result result, int n) throws Exception {
3158     assertTrue("Expected " + n + " keys but got " + result.size(),
3159         result.size() == n);
3160   }
3161 
3162   private void assertNResult(Result result, byte [] row,
3163       byte [][] families, byte [][] qualifiers, byte [][] values,
3164       int [][] idxs)
3165   throws Exception {
3166     assertTrue("Expected row [" + Bytes.toString(row) + "] " +
3167         "Got row [" + Bytes.toString(result.getRow()) +"]",
3168         equals(row, result.getRow()));
3169     assertTrue("Expected " + idxs.length + " keys but result contains "
3170         + result.size(), result.size() == idxs.length);
3171 
3172     Cell [] keys = result.rawCells();
3173 
3174     for(int i=0;i<keys.length;i++) {
3175       byte [] family = families[idxs[i][0]];
3176       byte [] qualifier = qualifiers[idxs[i][1]];
3177       byte [] value = values[idxs[i][2]];
3178       Cell key = keys[i];
3179 
3180       byte[] famb = CellUtil.cloneFamily(key);
3181       byte[] qualb = CellUtil.cloneQualifier(key);
3182       byte[] valb = CellUtil.cloneValue(key);
3183       assertTrue("(" + i + ") Expected family [" + Bytes.toString(family)
3184           + "] " + "Got family [" + Bytes.toString(famb) + "]",
3185           equals(family, famb));
3186       assertTrue("(" + i + ") Expected qualifier [" + Bytes.toString(qualifier)
3187           + "] " + "Got qualifier [" + Bytes.toString(qualb) + "]",
3188           equals(qualifier, qualb));
3189       assertTrue("(" + i + ") Expected value [" + Bytes.toString(value) + "] "
3190           + "Got value [" + Bytes.toString(valb) + "]",
3191           equals(value, valb));
3192     }
3193   }
3194 
3195   private void assertNResult(Result result, byte [] row,
3196       byte [] family, byte [] qualifier, long [] stamps, byte [][] values,
3197       int start, int end)
3198   throws IOException {
3199     assertTrue("Expected row [" + Bytes.toString(row) + "] " +
3200         "Got row [" + Bytes.toString(result.getRow()) +"]",
3201         equals(row, result.getRow()));
3202     int expectedResults = end - start + 1;
3203     assertEquals(expectedResults, result.size());
3204 
3205     Cell[] keys = result.rawCells();
3206 
3207     for (int i=0; i<keys.length; i++) {
3208       byte [] value = values[end-i];
3209       long ts = stamps[end-i];
3210       Cell key = keys[i];
3211 
3212       assertTrue("(" + i + ") Expected family [" + Bytes.toString(family)
3213           + "] " + "Got family [" + Bytes.toString(CellUtil.cloneFamily(key)) + "]",
3214           CellUtil.matchingFamily(key, family));
3215       assertTrue("(" + i + ") Expected qualifier [" + Bytes.toString(qualifier)
3216           + "] " + "Got qualifier [" + Bytes.toString(CellUtil.cloneQualifier(key))+ "]",
3217           CellUtil.matchingQualifier(key, qualifier));
3218       assertTrue("Expected ts [" + ts + "] " +
3219           "Got ts [" + key.getTimestamp() + "]", ts == key.getTimestamp());
3220       assertTrue("(" + i + ") Expected value [" + Bytes.toString(value) + "] "
3221           + "Got value [" + Bytes.toString(CellUtil.cloneValue(key)) + "]",
3222           CellUtil.matchingValue(key,  value));
3223     }
3224   }
3225 
3226   /**
3227    * Validate that result contains two specified keys, exactly.
3228    * It is assumed key A sorts before key B.
3229    */
3230   private void assertDoubleResult(Result result, byte [] row,
3231       byte [] familyA, byte [] qualifierA, byte [] valueA,
3232       byte [] familyB, byte [] qualifierB, byte [] valueB)
3233   throws Exception {
3234     assertTrue("Expected row [" + Bytes.toString(row) + "] " +
3235         "Got row [" + Bytes.toString(result.getRow()) +"]",
3236         equals(row, result.getRow()));
3237     assertTrue("Expected two keys but result contains " + result.size(),
3238         result.size() == 2);
3239     Cell [] kv = result.rawCells();
3240     Cell kvA = kv[0];
3241     assertTrue("(A) Expected family [" + Bytes.toString(familyA) + "] " +
3242         "Got family [" + Bytes.toString(CellUtil.cloneFamily(kvA)) + "]",
3243         equals(familyA, CellUtil.cloneFamily(kvA)));
3244     assertTrue("(A) Expected qualifier [" + Bytes.toString(qualifierA) + "] " +
3245         "Got qualifier [" + Bytes.toString(CellUtil.cloneQualifier(kvA)) + "]",
3246         equals(qualifierA, CellUtil.cloneQualifier(kvA)));
3247     assertTrue("(A) Expected value [" + Bytes.toString(valueA) + "] " +
3248         "Got value [" + Bytes.toString(CellUtil.cloneValue(kvA)) + "]",
3249         equals(valueA, CellUtil.cloneValue(kvA)));
3250     Cell kvB = kv[1];
3251     assertTrue("(B) Expected family [" + Bytes.toString(familyB) + "] " +
3252         "Got family [" + Bytes.toString(CellUtil.cloneFamily(kvB)) + "]",
3253         equals(familyB, CellUtil.cloneFamily(kvB)));
3254     assertTrue("(B) Expected qualifier [" + Bytes.toString(qualifierB) + "] " +
3255         "Got qualifier [" + Bytes.toString(CellUtil.cloneQualifier(kvB)) + "]",
3256         equals(qualifierB, CellUtil.cloneQualifier(kvB)));
3257     assertTrue("(B) Expected value [" + Bytes.toString(valueB) + "] " +
3258         "Got value [" + Bytes.toString(CellUtil.cloneValue(kvB)) + "]",
3259         equals(valueB, CellUtil.cloneValue(kvB)));
3260   }
3261 
3262   private void assertSingleResult(Result result, byte [] row, byte [] family,
3263       byte [] qualifier, byte [] value)
3264   throws Exception {
3265     assertTrue("Expected row [" + Bytes.toString(row) + "] " +
3266         "Got row [" + Bytes.toString(result.getRow()) +"]",
3267         equals(row, result.getRow()));
3268     assertTrue("Expected a single key but result contains " + result.size(),
3269         result.size() == 1);
3270     Cell kv = result.rawCells()[0];
3271     assertTrue("Expected family [" + Bytes.toString(family) + "] " +
3272         "Got family [" + Bytes.toString(CellUtil.cloneFamily(kv)) + "]",
3273         equals(family, CellUtil.cloneFamily(kv)));
3274     assertTrue("Expected qualifier [" + Bytes.toString(qualifier) + "] " +
3275         "Got qualifier [" + Bytes.toString(CellUtil.cloneQualifier(kv)) + "]",
3276         equals(qualifier, CellUtil.cloneQualifier(kv)));
3277     assertTrue("Expected value [" + Bytes.toString(value) + "] " +
3278         "Got value [" + Bytes.toString(CellUtil.cloneValue(kv)) + "]",
3279         equals(value, CellUtil.cloneValue(kv)));
3280   }
3281 
3282   private void assertSingleResult(Result result, byte [] row, byte [] family,
3283       byte [] qualifier, long ts, byte [] value)
3284   throws Exception {
3285     assertTrue("Expected row [" + Bytes.toString(row) + "] " +
3286         "Got row [" + Bytes.toString(result.getRow()) +"]",
3287         equals(row, result.getRow()));
3288     assertTrue("Expected a single key but result contains " + result.size(),
3289         result.size() == 1);
3290     Cell kv = result.rawCells()[0];
3291     assertTrue("Expected family [" + Bytes.toString(family) + "] " +
3292         "Got family [" + Bytes.toString(CellUtil.cloneFamily(kv)) + "]",
3293         equals(family, CellUtil.cloneFamily(kv)));
3294     assertTrue("Expected qualifier [" + Bytes.toString(qualifier) + "] " +
3295         "Got qualifier [" + Bytes.toString(CellUtil.cloneQualifier(kv)) + "]",
3296         equals(qualifier, CellUtil.cloneQualifier(kv)));
3297     assertTrue("Expected ts [" + ts + "] " +
3298         "Got ts [" + kv.getTimestamp() + "]", ts == kv.getTimestamp());
3299     assertTrue("Expected value [" + Bytes.toString(value) + "] " +
3300         "Got value [" + Bytes.toString(CellUtil.cloneValue(kv)) + "]",
3301         equals(value, CellUtil.cloneValue(kv)));
3302   }
3303 
3304   private void assertEmptyResult(Result result) throws Exception {
3305     assertTrue("expected an empty result but result contains " +
3306         result.size() + " keys", result.isEmpty());
3307   }
3308 
3309   private void assertNullResult(Result result) throws Exception {
3310     assertTrue("expected null result but received a non-null result",
3311         result == null);
3312   }
3313 
3314   //
3315   // Helpers
3316   //
3317 
3318   private Result getSingleScanResult(Table ht, Scan scan) throws IOException {
3319     ResultScanner scanner = ht.getScanner(scan);
3320     Result result = scanner.next();
3321     scanner.close();
3322     return result;
3323   }
3324 
3325   private byte [][] makeNAscii(byte [] base, int n) {
3326     if(n > 256) {
3327       return makeNBig(base, n);
3328     }
3329     byte [][] ret = new byte[n][];
3330     for(int i=0;i<n;i++) {
3331       byte [] tail = Bytes.toBytes(Integer.toString(i));
3332       ret[i] = Bytes.add(base, tail);
3333     }
3334     return ret;
3335   }
3336 
3337   private byte [][] makeN(byte [] base, int n) {
3338     if (n > 256) {
3339       return makeNBig(base, n);
3340     }
3341     byte [][] ret = new byte[n][];
3342     for(int i=0;i<n;i++) {
3343       ret[i] = Bytes.add(base, new byte[]{(byte)i});
3344     }
3345     return ret;
3346   }
3347 
3348   private byte [][] makeNBig(byte [] base, int n) {
3349     byte [][] ret = new byte[n][];
3350     for(int i=0;i<n;i++) {
3351       int byteA = (i % 256);
3352       int byteB = (i >> 8);
3353       ret[i] = Bytes.add(base, new byte[]{(byte)byteB,(byte)byteA});
3354     }
3355     return ret;
3356   }
3357 
3358   private long [] makeStamps(int n) {
3359     long [] stamps = new long[n];
3360     for(int i=0;i<n;i++) stamps[i] = i+1;
3361     return stamps;
3362   }
3363 
3364   private boolean equals(byte [] left, byte [] right) {
3365     if (left == null && right == null) return true;
3366     if (left == null && right.length == 0) return true;
3367     if (right == null && left.length == 0) return true;
3368     return Bytes.equals(left, right);
3369   }
3370 
3371   @Test
3372   public void testDuplicateVersions() throws Exception {
3373     byte [] TABLE = Bytes.toBytes("testDuplicateVersions");
3374 
3375     long [] STAMPS = makeStamps(20);
3376     byte [][] VALUES = makeNAscii(VALUE, 20);
3377 
3378     Table ht = TEST_UTIL.createTable(TABLE, FAMILY, 10);
3379 
3380     // Insert 4 versions of same column
3381     Put put = new Put(ROW);
3382     put.add(FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
3383     put.add(FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
3384     put.add(FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
3385     put.add(FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
3386     ht.put(put);
3387 
3388     // Verify we can get each one properly
3389     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
3390     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
3391     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
3392     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
3393     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
3394     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
3395     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
3396     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
3397 
3398     // Verify we don't accidentally get others
3399     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
3400     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[3]);
3401     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[6]);
3402     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
3403     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[3]);
3404     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[6]);
3405 
3406     // Ensure maxVersions in query is respected
3407     Get get = new Get(ROW);
3408     get.addColumn(FAMILY, QUALIFIER);
3409     get.setMaxVersions(2);
3410     Result result = ht.get(get);
3411     assertNResult(result, ROW, FAMILY, QUALIFIER,
3412         new long [] {STAMPS[4], STAMPS[5]},
3413         new byte[][] {VALUES[4], VALUES[5]},
3414         0, 1);
3415 
3416     Scan scan = new Scan(ROW);
3417     scan.addColumn(FAMILY, QUALIFIER);
3418     scan.setMaxVersions(2);
3419     result = getSingleScanResult(ht, scan);
3420     assertNResult(result, ROW, FAMILY, QUALIFIER,
3421         new long [] {STAMPS[4], STAMPS[5]},
3422         new byte[][] {VALUES[4], VALUES[5]},
3423         0, 1);
3424 
3425     // Flush and redo
3426 
3427     TEST_UTIL.flush();
3428 
3429     // Verify we can get each one properly
3430     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
3431     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
3432     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
3433     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
3434     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
3435     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
3436     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[4]);
3437     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[5], VALUES[5]);
3438 
3439     // Verify we don't accidentally get others
3440     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
3441     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[3]);
3442     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[6]);
3443     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
3444     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[3]);
3445     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[6]);
3446 
3447     // Ensure maxVersions in query is respected
3448     get = new Get(ROW);
3449     get.addColumn(FAMILY, QUALIFIER);
3450     get.setMaxVersions(2);
3451     result = ht.get(get);
3452     assertNResult(result, ROW, FAMILY, QUALIFIER,
3453         new long [] {STAMPS[4], STAMPS[5]},
3454         new byte[][] {VALUES[4], VALUES[5]},
3455         0, 1);
3456 
3457     scan = new Scan(ROW);
3458     scan.addColumn(FAMILY, QUALIFIER);
3459     scan.setMaxVersions(2);
3460     result = getSingleScanResult(ht, scan);
3461     assertNResult(result, ROW, FAMILY, QUALIFIER,
3462         new long [] {STAMPS[4], STAMPS[5]},
3463         new byte[][] {VALUES[4], VALUES[5]},
3464         0, 1);
3465 
3466 
3467     // Add some memstore and retest
3468 
3469     // Insert 4 more versions of same column and a dupe
3470     put = new Put(ROW);
3471     put.add(FAMILY, QUALIFIER, STAMPS[3], VALUES[3]);
3472     put.add(FAMILY, QUALIFIER, STAMPS[4], VALUES[14]);
3473     put.add(FAMILY, QUALIFIER, STAMPS[6], VALUES[6]);
3474     put.add(FAMILY, QUALIFIER, STAMPS[7], VALUES[7]);
3475     put.add(FAMILY, QUALIFIER, STAMPS[8], VALUES[8]);
3476     ht.put(put);
3477 
3478     // Ensure maxVersions in query is respected
3479     get = new Get(ROW);
3480     get.addColumn(FAMILY, QUALIFIER);
3481     get.setMaxVersions(7);
3482     result = ht.get(get);
3483     assertNResult(result, ROW, FAMILY, QUALIFIER,
3484         new long [] {STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8]},
3485         new byte[][] {VALUES[2], VALUES[3], VALUES[14], VALUES[5], VALUES[6], VALUES[7], VALUES[8]},
3486         0, 6);
3487 
3488     scan = new Scan(ROW);
3489     scan.addColumn(FAMILY, QUALIFIER);
3490     scan.setMaxVersions(7);
3491     result = getSingleScanResult(ht, scan);
3492     assertNResult(result, ROW, FAMILY, QUALIFIER,
3493         new long [] {STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8]},
3494         new byte[][] {VALUES[2], VALUES[3], VALUES[14], VALUES[5], VALUES[6], VALUES[7], VALUES[8]},
3495         0, 6);
3496 
3497     get = new Get(ROW);
3498     get.setMaxVersions(7);
3499     result = ht.get(get);
3500     assertNResult(result, ROW, FAMILY, QUALIFIER,
3501         new long [] {STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8]},
3502         new byte[][] {VALUES[2], VALUES[3], VALUES[14], VALUES[5], VALUES[6], VALUES[7], VALUES[8]},
3503         0, 6);
3504 
3505     scan = new Scan(ROW);
3506     scan.setMaxVersions(7);
3507     result = getSingleScanResult(ht, scan);
3508     assertNResult(result, ROW, FAMILY, QUALIFIER,
3509         new long [] {STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8]},
3510         new byte[][] {VALUES[2], VALUES[3], VALUES[14], VALUES[5], VALUES[6], VALUES[7], VALUES[8]},
3511         0, 6);
3512 
3513     // Verify we can get each one properly
3514     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
3515     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
3516     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[14]);
3517     getVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[7], VALUES[7]);
3518     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[1], VALUES[1]);
3519     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[2], VALUES[2]);
3520     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[4], VALUES[14]);
3521     scanVersionAndVerify(ht, ROW, FAMILY, QUALIFIER, STAMPS[7], VALUES[7]);
3522 
3523     // Verify we don't accidentally get others
3524     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
3525     getVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[9]);
3526     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[0]);
3527     scanVersionAndVerifyMissing(ht, ROW, FAMILY, QUALIFIER, STAMPS[9]);
3528 
3529     // Ensure maxVersions of table is respected
3530 
3531     TEST_UTIL.flush();
3532 
3533     // Insert 4 more versions of same column and a dupe
3534     put = new Put(ROW);
3535     put.add(FAMILY, QUALIFIER, STAMPS[9], VALUES[9]);
3536     put.add(FAMILY, QUALIFIER, STAMPS[11], VALUES[11]);
3537     put.add(FAMILY, QUALIFIER, STAMPS[13], VALUES[13]);
3538     put.add(FAMILY, QUALIFIER, STAMPS[15], VALUES[15]);
3539     ht.put(put);
3540 
3541     get = new Get(ROW);
3542     get.addColumn(FAMILY, QUALIFIER);
3543     get.setMaxVersions(Integer.MAX_VALUE);
3544     result = ht.get(get);
3545     assertNResult(result, ROW, FAMILY, QUALIFIER,
3546         new long [] {STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8], STAMPS[9], STAMPS[11], STAMPS[13], STAMPS[15]},
3547         new byte[][] {VALUES[3], VALUES[14], VALUES[5], VALUES[6], VALUES[7], VALUES[8], VALUES[9], VALUES[11], VALUES[13], VALUES[15]},
3548         0, 9);
3549 
3550     scan = new Scan(ROW);
3551     scan.addColumn(FAMILY, QUALIFIER);
3552     scan.setMaxVersions(Integer.MAX_VALUE);
3553     result = getSingleScanResult(ht, scan);
3554     assertNResult(result, ROW, FAMILY, QUALIFIER,
3555         new long [] {STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[7], STAMPS[8], STAMPS[9], STAMPS[11], STAMPS[13], STAMPS[15]},
3556         new byte[][] {VALUES[3], VALUES[14], VALUES[5], VALUES[6], VALUES[7], VALUES[8], VALUES[9], VALUES[11], VALUES[13], VALUES[15]},
3557         0, 9);
3558 
3559     // Delete a version in the memstore and a version in a storefile
3560     Delete delete = new Delete(ROW);
3561     delete.deleteColumn(FAMILY, QUALIFIER, STAMPS[11]);
3562     delete.deleteColumn(FAMILY, QUALIFIER, STAMPS[7]);
3563     ht.delete(delete);
3564 
3565     // Test that it's gone
3566     get = new Get(ROW);
3567     get.addColumn(FAMILY, QUALIFIER);
3568     get.setMaxVersions(Integer.MAX_VALUE);
3569     result = ht.get(get);
3570     assertNResult(result, ROW, FAMILY, QUALIFIER,
3571         new long [] {STAMPS[1], STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[8], STAMPS[9], STAMPS[13], STAMPS[15]},
3572         new byte[][] {VALUES[1], VALUES[2], VALUES[3], VALUES[14], VALUES[5], VALUES[6], VALUES[8], VALUES[9], VALUES[13], VALUES[15]},
3573         0, 9);
3574 
3575     scan = new Scan(ROW);
3576     scan.addColumn(FAMILY, QUALIFIER);
3577     scan.setMaxVersions(Integer.MAX_VALUE);
3578     result = getSingleScanResult(ht, scan);
3579     assertNResult(result, ROW, FAMILY, QUALIFIER,
3580         new long [] {STAMPS[1], STAMPS[2], STAMPS[3], STAMPS[4], STAMPS[5], STAMPS[6], STAMPS[8], STAMPS[9], STAMPS[13], STAMPS[15]},
3581         new byte[][] {VALUES[1], VALUES[2], VALUES[3], VALUES[14], VALUES[5], VALUES[6], VALUES[8], VALUES[9], VALUES[13], VALUES[15]},
3582         0, 9);
3583   }
3584 
3585   @Test
3586   public void testUpdates() throws Exception {
3587 
3588     byte [] TABLE = Bytes.toBytes("testUpdates");
3589     Table hTable = TEST_UTIL.createTable(TABLE, FAMILY, 10);
3590 
3591     // Write a column with values at timestamp 1, 2 and 3
3592     byte[] row = Bytes.toBytes("row1");
3593     byte[] qualifier = Bytes.toBytes("myCol");
3594     Put put = new Put(row);
3595     put.add(FAMILY, qualifier, 1L, Bytes.toBytes("AAA"));
3596     hTable.put(put);
3597 
3598     put = new Put(row);
3599     put.add(FAMILY, qualifier, 2L, Bytes.toBytes("BBB"));
3600     hTable.put(put);
3601 
3602     put = new Put(row);
3603     put.add(FAMILY, qualifier, 3L, Bytes.toBytes("EEE"));
3604     hTable.put(put);
3605 
3606     Get get = new Get(row);
3607     get.addColumn(FAMILY, qualifier);
3608     get.setMaxVersions();
3609 
3610     // Check that the column indeed has the right values at timestamps 1 and
3611     // 2
3612     Result result = hTable.get(get);
3613     NavigableMap<Long, byte[]> navigableMap =
3614         result.getMap().get(FAMILY).get(qualifier);
3615     assertEquals("AAA", Bytes.toString(navigableMap.get(1L)));
3616     assertEquals("BBB", Bytes.toString(navigableMap.get(2L)));
3617 
3618     // Update the value at timestamp 1
3619     put = new Put(row);
3620     put.add(FAMILY, qualifier, 1L, Bytes.toBytes("CCC"));
3621     hTable.put(put);
3622 
3623     // Update the value at timestamp 2
3624     put = new Put(row);
3625     put.add(FAMILY, qualifier, 2L, Bytes.toBytes("DDD"));
3626     hTable.put(put);
3627 
3628     // Check that the values at timestamp 2 and 1 got updated
3629     result = hTable.get(get);
3630     navigableMap = result.getMap().get(FAMILY).get(qualifier);
3631     assertEquals("CCC", Bytes.toString(navigableMap.get(1L)));
3632     assertEquals("DDD", Bytes.toString(navigableMap.get(2L)));
3633   }
3634 
3635   @Test
3636   public void testUpdatesWithMajorCompaction() throws Exception {
3637 
3638     TableName TABLE = TableName.valueOf("testUpdatesWithMajorCompaction");
3639     Table hTable = TEST_UTIL.createTable(TABLE, FAMILY, 10);
3640     HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
3641 
3642     // Write a column with values at timestamp 1, 2 and 3
3643     byte[] row = Bytes.toBytes("row2");
3644     byte[] qualifier = Bytes.toBytes("myCol");
3645     Put put = new Put(row);
3646     put.add(FAMILY, qualifier, 1L, Bytes.toBytes("AAA"));
3647     hTable.put(put);
3648 
3649     put = new Put(row);
3650     put.add(FAMILY, qualifier, 2L, Bytes.toBytes("BBB"));
3651     hTable.put(put);
3652 
3653     put = new Put(row);
3654     put.add(FAMILY, qualifier, 3L, Bytes.toBytes("EEE"));
3655     hTable.put(put);
3656 
3657     Get get = new Get(row);
3658     get.addColumn(FAMILY, qualifier);
3659     get.setMaxVersions();
3660 
3661     // Check that the column indeed has the right values at timestamps 1 and
3662     // 2
3663     Result result = hTable.get(get);
3664     NavigableMap<Long, byte[]> navigableMap =
3665         result.getMap().get(FAMILY).get(qualifier);
3666     assertEquals("AAA", Bytes.toString(navigableMap.get(1L)));
3667     assertEquals("BBB", Bytes.toString(navigableMap.get(2L)));
3668 
3669     // Trigger a major compaction
3670     admin.flush(TABLE);
3671     admin.majorCompact(TABLE);
3672     Thread.sleep(6000);
3673 
3674     // Update the value at timestamp 1
3675     put = new Put(row);
3676     put.add(FAMILY, qualifier, 1L, Bytes.toBytes("CCC"));
3677     hTable.put(put);
3678 
3679     // Update the value at timestamp 2
3680     put = new Put(row);
3681     put.add(FAMILY, qualifier, 2L, Bytes.toBytes("DDD"));
3682     hTable.put(put);
3683 
3684     // Trigger a major compaction
3685     admin.flush(TABLE);
3686     admin.majorCompact(TABLE);
3687     Thread.sleep(6000);
3688 
3689     // Check that the values at timestamp 2 and 1 got updated
3690     result = hTable.get(get);
3691     navigableMap = result.getMap().get(FAMILY).get(qualifier);
3692     assertEquals("CCC", Bytes.toString(navigableMap.get(1L)));
3693     assertEquals("DDD", Bytes.toString(navigableMap.get(2L)));
3694   }
3695 
3696   @Test
3697   public void testMajorCompactionBetweenTwoUpdates() throws Exception {
3698 
3699     String tableName = "testMajorCompactionBetweenTwoUpdates";
3700     byte [] TABLE = Bytes.toBytes(tableName);
3701     Table hTable = TEST_UTIL.createTable(TABLE, FAMILY, 10);
3702     HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
3703 
3704     // Write a column with values at timestamp 1, 2 and 3
3705     byte[] row = Bytes.toBytes("row3");
3706     byte[] qualifier = Bytes.toBytes("myCol");
3707     Put put = new Put(row);
3708     put.add(FAMILY, qualifier, 1L, Bytes.toBytes("AAA"));
3709     hTable.put(put);
3710 
3711     put = new Put(row);
3712     put.add(FAMILY, qualifier, 2L, Bytes.toBytes("BBB"));
3713     hTable.put(put);
3714 
3715     put = new Put(row);
3716     put.add(FAMILY, qualifier, 3L, Bytes.toBytes("EEE"));
3717     hTable.put(put);
3718 
3719     Get get = new Get(row);
3720     get.addColumn(FAMILY, qualifier);
3721     get.setMaxVersions();
3722 
3723     // Check that the column indeed has the right values at timestamps 1 and
3724     // 2
3725     Result result = hTable.get(get);
3726     NavigableMap<Long, byte[]> navigableMap =
3727         result.getMap().get(FAMILY).get(qualifier);
3728     assertEquals("AAA", Bytes.toString(navigableMap.get(1L)));
3729     assertEquals("BBB", Bytes.toString(navigableMap.get(2L)));
3730 
3731     // Trigger a major compaction
3732     admin.flush(tableName);
3733     admin.majorCompact(tableName);
3734     Thread.sleep(6000);
3735 
3736     // Update the value at timestamp 1
3737     put = new Put(row);
3738     put.add(FAMILY, qualifier, 1L, Bytes.toBytes("CCC"));
3739     hTable.put(put);
3740 
3741     // Trigger a major compaction
3742     admin.flush(tableName);
3743     admin.majorCompact(tableName);
3744     Thread.sleep(6000);
3745 
3746     // Update the value at timestamp 2
3747     put = new Put(row);
3748     put.add(FAMILY, qualifier, 2L, Bytes.toBytes("DDD"));
3749     hTable.put(put);
3750 
3751     // Trigger a major compaction
3752     admin.flush(tableName);
3753     admin.majorCompact(tableName);
3754     Thread.sleep(6000);
3755 
3756     // Check that the values at timestamp 2 and 1 got updated
3757     result = hTable.get(get);
3758     navigableMap = result.getMap().get(FAMILY).get(qualifier);
3759 
3760     assertEquals("CCC", Bytes.toString(navigableMap.get(1L)));
3761     assertEquals("DDD", Bytes.toString(navigableMap.get(2L)));
3762   }
3763 
3764   @Test
3765   public void testGet_EmptyTable() throws IOException {
3766     Table table = TEST_UTIL.createTable(TableName.valueOf("testGet_EmptyTable"), FAMILY);
3767     Get get = new Get(ROW);
3768     get.addFamily(FAMILY);
3769     Result r = table.get(get);
3770     assertTrue(r.isEmpty());
3771   }
3772 
3773   @Test
3774   public void testGet_NullQualifier() throws IOException {
3775     Table table = TEST_UTIL.createTable(TableName.valueOf("testGet_NullQualifier"), FAMILY);
3776     Put put = new Put(ROW);
3777     put.add(FAMILY, QUALIFIER, VALUE);
3778     table.put(put);
3779 
3780     put = new Put(ROW);
3781     put.add(FAMILY, null, VALUE);
3782     table.put(put);
3783     LOG.info("Row put");
3784 
3785     Get get = new Get(ROW);
3786     get.addColumn(FAMILY, null);
3787     Result r = table.get(get);
3788     assertEquals(1, r.size());
3789 
3790     get = new Get(ROW);
3791     get.addFamily(FAMILY);
3792     r = table.get(get);
3793     assertEquals(2, r.size());
3794   }
3795 
3796   @Test
3797   public void testGet_NonExistentRow() throws IOException {
3798     Table table = TEST_UTIL.createTable(TableName.valueOf("testGet_NonExistentRow"), FAMILY);
3799     Put put = new Put(ROW);
3800     put.add(FAMILY, QUALIFIER, VALUE);
3801     table.put(put);
3802     LOG.info("Row put");
3803 
3804     Get get = new Get(ROW);
3805     get.addFamily(FAMILY);
3806     Result r = table.get(get);
3807     assertFalse(r.isEmpty());
3808     System.out.println("Row retrieved successfully");
3809 
3810     byte [] missingrow = Bytes.toBytes("missingrow");
3811     get = new Get(missingrow);
3812     get.addFamily(FAMILY);
3813     r = table.get(get);
3814     assertTrue(r.isEmpty());
3815     LOG.info("Row missing as it should be");
3816   }
3817 
3818   @Test
3819   public void testPut() throws IOException {
3820     final byte [] CONTENTS_FAMILY = Bytes.toBytes("contents");
3821     final byte [] SMALL_FAMILY = Bytes.toBytes("smallfam");
3822     final byte [] row1 = Bytes.toBytes("row1");
3823     final byte [] row2 = Bytes.toBytes("row2");
3824     final byte [] value = Bytes.toBytes("abcd");
3825     Table table = TEST_UTIL.createTable(Bytes.toBytes("testPut"),
3826       new byte [][] {CONTENTS_FAMILY, SMALL_FAMILY});
3827     Put put = new Put(row1);
3828     put.add(CONTENTS_FAMILY, null, value);
3829     table.put(put);
3830 
3831     put = new Put(row2);
3832     put.add(CONTENTS_FAMILY, null, value);
3833 
3834     assertEquals(put.size(), 1);
3835     assertEquals(put.getFamilyCellMap().get(CONTENTS_FAMILY).size(), 1);
3836 
3837     // KeyValue v1 expectation.  Cast for now until we go all Cell all the time. TODO
3838     KeyValue kv = (KeyValue)put.getFamilyCellMap().get(CONTENTS_FAMILY).get(0);
3839 
3840     assertTrue(Bytes.equals(kv.getFamily(), CONTENTS_FAMILY));
3841     // will it return null or an empty byte array?
3842     assertTrue(Bytes.equals(kv.getQualifier(), new byte[0]));
3843 
3844     assertTrue(Bytes.equals(kv.getValue(), value));
3845 
3846     table.put(put);
3847 
3848     Scan scan = new Scan();
3849     scan.addColumn(CONTENTS_FAMILY, null);
3850     ResultScanner scanner = table.getScanner(scan);
3851     for (Result r : scanner) {
3852       for(Cell key : r.rawCells()) {
3853         System.out.println(Bytes.toString(r.getRow()) + ": " + key.toString());
3854       }
3855     }
3856   }
3857 
3858   @Test
3859   public void testPutNoCF() throws IOException {
3860     final byte[] BAD_FAM = Bytes.toBytes("BAD_CF");
3861     final byte[] VAL = Bytes.toBytes(100);
3862     Table table = TEST_UTIL.createTable(Bytes.toBytes("testPutNoCF"), FAMILY);
3863 
3864     boolean caughtNSCFE = false;
3865 
3866     try {
3867       Put p = new Put(ROW);
3868       p.add(BAD_FAM, QUALIFIER, VAL);
3869       table.put(p);
3870     } catch (RetriesExhaustedWithDetailsException e) {
3871       caughtNSCFE = e.getCause(0) instanceof NoSuchColumnFamilyException;
3872     }
3873     assertTrue("Should throw NoSuchColumnFamilyException", caughtNSCFE);
3874 
3875   }
3876 
3877   @Test
3878   public void testRowsPut() throws IOException {
3879     final byte[] CONTENTS_FAMILY = Bytes.toBytes("contents");
3880     final byte[] SMALL_FAMILY = Bytes.toBytes("smallfam");
3881     final int NB_BATCH_ROWS = 10;
3882     final byte[] value = Bytes.toBytes("abcd");
3883     Table table = TEST_UTIL.createTable(Bytes.toBytes("testRowsPut"),
3884       new byte[][] {CONTENTS_FAMILY, SMALL_FAMILY });
3885     ArrayList<Put> rowsUpdate = new ArrayList<Put>();
3886     for (int i = 0; i < NB_BATCH_ROWS; i++) {
3887       byte[] row = Bytes.toBytes("row" + i);
3888       Put put = new Put(row);
3889       put.setDurability(Durability.SKIP_WAL);
3890       put.add(CONTENTS_FAMILY, null, value);
3891       rowsUpdate.add(put);
3892     }
3893     table.put(rowsUpdate);
3894     Scan scan = new Scan();
3895     scan.addFamily(CONTENTS_FAMILY);
3896     ResultScanner scanner = table.getScanner(scan);
3897     int nbRows = 0;
3898     for (@SuppressWarnings("unused")
3899     Result row : scanner)
3900       nbRows++;
3901     assertEquals(NB_BATCH_ROWS, nbRows);
3902   }
3903 
3904   @Test
3905   public void testRowsPutBufferedOneFlush() throws IOException {
3906     final byte [] CONTENTS_FAMILY = Bytes.toBytes("contents");
3907     final byte [] SMALL_FAMILY = Bytes.toBytes("smallfam");
3908     final byte [] value = Bytes.toBytes("abcd");
3909     final int NB_BATCH_ROWS = 10;
3910     HTable table = TEST_UTIL.createTable(Bytes.toBytes("testRowsPutBufferedOneFlush"),
3911       new byte [][] {CONTENTS_FAMILY, SMALL_FAMILY});
3912     table.setAutoFlush(false);
3913     ArrayList<Put> rowsUpdate = new ArrayList<Put>();
3914     for (int i = 0; i < NB_BATCH_ROWS * 10; i++) {
3915       byte[] row = Bytes.toBytes("row" + i);
3916       Put put = new Put(row);
3917       put.setDurability(Durability.SKIP_WAL);
3918       put.add(CONTENTS_FAMILY, null, value);
3919       rowsUpdate.add(put);
3920     }
3921     table.put(rowsUpdate);
3922 
3923     Scan scan = new Scan();
3924     scan.addFamily(CONTENTS_FAMILY);
3925     ResultScanner scanner = table.getScanner(scan);
3926     int nbRows = 0;
3927     for (@SuppressWarnings("unused")
3928     Result row : scanner)
3929       nbRows++;
3930     assertEquals(0, nbRows);
3931     scanner.close();
3932 
3933     table.flushCommits();
3934 
3935     scan = new Scan();
3936     scan.addFamily(CONTENTS_FAMILY);
3937     scanner = table.getScanner(scan);
3938     nbRows = 0;
3939     for (@SuppressWarnings("unused")
3940     Result row : scanner)
3941       nbRows++;
3942     assertEquals(NB_BATCH_ROWS * 10, nbRows);
3943     table.close();
3944   }
3945 
3946   @Test
3947   public void testRowsPutBufferedManyManyFlushes() throws IOException {
3948     final byte[] CONTENTS_FAMILY = Bytes.toBytes("contents");
3949     final byte[] SMALL_FAMILY = Bytes.toBytes("smallfam");
3950     final byte[] value = Bytes.toBytes("abcd");
3951     final int NB_BATCH_ROWS = 10;
3952     HTable table = TEST_UTIL.createTable(Bytes.toBytes("testRowsPutBufferedManyManyFlushes"),
3953       new byte[][] {CONTENTS_FAMILY, SMALL_FAMILY });
3954     table.setWriteBufferSize(10);
3955     ArrayList<Put> rowsUpdate = new ArrayList<Put>();
3956     for (int i = 0; i < NB_BATCH_ROWS * 10; i++) {
3957       byte[] row = Bytes.toBytes("row" + i);
3958       Put put = new Put(row);
3959       put.setDurability(Durability.SKIP_WAL);
3960       put.add(CONTENTS_FAMILY, null, value);
3961       rowsUpdate.add(put);
3962     }
3963     table.put(rowsUpdate);
3964 
3965     Scan scan = new Scan();
3966     scan.addFamily(CONTENTS_FAMILY);
3967     ResultScanner scanner = table.getScanner(scan);
3968     int nbRows = 0;
3969     for (@SuppressWarnings("unused")
3970     Result row : scanner)
3971       nbRows++;
3972     assertEquals(NB_BATCH_ROWS * 10, nbRows);
3973   }
3974 
3975   @Test
3976   public void testAddKeyValue() throws IOException {
3977     final byte[] CONTENTS_FAMILY = Bytes.toBytes("contents");
3978     final byte[] value = Bytes.toBytes("abcd");
3979     final byte[] row1 = Bytes.toBytes("row1");
3980     final byte[] row2 = Bytes.toBytes("row2");
3981     byte[] qualifier = Bytes.toBytes("qf1");
3982     Put put = new Put(row1);
3983 
3984     // Adding KeyValue with the same row
3985     KeyValue kv = new KeyValue(row1, CONTENTS_FAMILY, qualifier, value);
3986     boolean ok = true;
3987     try {
3988       put.add(kv);
3989     } catch (IOException e) {
3990       ok = false;
3991     }
3992     assertEquals(true, ok);
3993 
3994     // Adding KeyValue with the different row
3995     kv = new KeyValue(row2, CONTENTS_FAMILY, qualifier, value);
3996     ok = false;
3997     try {
3998       put.add(kv);
3999     } catch (IOException e) {
4000       ok = true;
4001     }
4002     assertEquals(true, ok);
4003   }
4004 
4005   /**
4006    * test for HBASE-737
4007    * @throws IOException
4008    */
4009   @Test
4010   public void testHBase737 () throws IOException {
4011     final byte [] FAM1 = Bytes.toBytes("fam1");
4012     final byte [] FAM2 = Bytes.toBytes("fam2");
4013     // Open table
4014     Table table = TEST_UTIL.createTable(Bytes.toBytes("testHBase737"),
4015       new byte [][] {FAM1, FAM2});
4016     // Insert some values
4017     Put put = new Put(ROW);
4018     put.add(FAM1, Bytes.toBytes("letters"), Bytes.toBytes("abcdefg"));
4019     table.put(put);
4020     try {
4021       Thread.sleep(1000);
4022     } catch (InterruptedException i) {
4023       //ignore
4024     }
4025 
4026     put = new Put(ROW);
4027     put.add(FAM1, Bytes.toBytes("numbers"), Bytes.toBytes("123456"));
4028     table.put(put);
4029 
4030     try {
4031       Thread.sleep(1000);
4032     } catch (InterruptedException i) {
4033       //ignore
4034     }
4035 
4036     put = new Put(ROW);
4037     put.add(FAM2, Bytes.toBytes("letters"), Bytes.toBytes("hijklmnop"));
4038     table.put(put);
4039 
4040     long times[] = new long[3];
4041 
4042     // First scan the memstore
4043 
4044     Scan scan = new Scan();
4045     scan.addFamily(FAM1);
4046     scan.addFamily(FAM2);
4047     ResultScanner s = table.getScanner(scan);
4048     try {
4049       int index = 0;
4050       Result r = null;
4051       while ((r = s.next()) != null) {
4052         for(Cell key : r.rawCells()) {
4053           times[index++] = key.getTimestamp();
4054         }
4055       }
4056     } finally {
4057       s.close();
4058     }
4059     for (int i = 0; i < times.length - 1; i++) {
4060       for (int j = i + 1; j < times.length; j++) {
4061         assertTrue(times[j] > times[i]);
4062       }
4063     }
4064 
4065     // Flush data to disk and try again
4066     TEST_UTIL.flush();
4067 
4068     // Reset times
4069     for(int i=0;i<times.length;i++) {
4070       times[i] = 0;
4071     }
4072 
4073     try {
4074       Thread.sleep(1000);
4075     } catch (InterruptedException i) {
4076       //ignore
4077     }
4078     scan = new Scan();
4079     scan.addFamily(FAM1);
4080     scan.addFamily(FAM2);
4081     s = table.getScanner(scan);
4082     try {
4083       int index = 0;
4084       Result r = null;
4085       while ((r = s.next()) != null) {
4086         for(Cell key : r.rawCells()) {
4087           times[index++] = key.getTimestamp();
4088         }
4089       }
4090     } finally {
4091       s.close();
4092     }
4093     for (int i = 0; i < times.length - 1; i++) {
4094       for (int j = i + 1; j < times.length; j++) {
4095         assertTrue(times[j] > times[i]);
4096       }
4097     }
4098   }
4099 
4100   @Test
4101   public void testListTables() throws IOException, InterruptedException {
4102     TableName t1 = TableName.valueOf("testListTables1");
4103     TableName t2 = TableName.valueOf("testListTables2");
4104     TableName t3 = TableName.valueOf("testListTables3");
4105     TableName [] tables = new TableName[] { t1, t2, t3 };
4106     for (int i = 0; i < tables.length; i++) {
4107       TEST_UTIL.createTable(tables[i], FAMILY);
4108     }
4109     Admin admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
4110     HTableDescriptor[] ts = admin.listTables();
4111     HashSet<HTableDescriptor> result = new HashSet<HTableDescriptor>(ts.length);
4112     Collections.addAll(result, ts);
4113     int size = result.size();
4114     assertTrue(size >= tables.length);
4115     for (int i = 0; i < tables.length && i < size; i++) {
4116       boolean found = false;
4117       for (int j = 0; j < ts.length; j++) {
4118         if (ts[j].getTableName().equals(tables[i])) {
4119           found = true;
4120           break;
4121         }
4122       }
4123       assertTrue("Not found: " + tables[i], found);
4124     }
4125   }
4126 
4127   /**
4128    * creates an HTable for tableName using an unmanaged HConnection.
4129    *
4130    * @param tableName - table to create
4131    * @return the created HTable object
4132    * @throws IOException
4133    */
4134   HTable createUnmangedHConnectionHTable(final TableName tableName) throws IOException {
4135     TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY);
4136     HConnection conn = HConnectionManager.createConnection(TEST_UTIL.getConfiguration());
4137     return (HTable)conn.getTable(tableName);
4138   }
4139 
4140   /**
4141    * simple test that just executes parts of the client
4142    * API that accept a pre-created HConnection instance
4143    *
4144    * @throws IOException
4145    */
4146   @Test
4147   public void testUnmanagedHConnection() throws IOException {
4148     final TableName tableName = TableName.valueOf("testUnmanagedHConnection");
4149     HTable t = createUnmangedHConnectionHTable(tableName);
4150     HBaseAdmin ha = new HBaseAdmin(t.getConnection());
4151     assertTrue(ha.tableExists(tableName));
4152     assertTrue(t.get(new Get(ROW)).isEmpty());
4153     ha.close();
4154   }
4155 
4156   /**
4157    * test of that unmanaged HConnections are able to reconnect
4158    * properly (see HBASE-5058)
4159    *
4160    * @throws Exception
4161    */
4162   @Test
4163   public void testUnmanagedHConnectionReconnect() throws Exception {
4164     final TableName tableName = TableName.valueOf("testUnmanagedHConnectionReconnect");
4165     HTable t = createUnmangedHConnectionHTable(tableName);
4166     Connection conn = t.getConnection();
4167     try (HBaseAdmin ha = new HBaseAdmin(conn)) {
4168       assertTrue(ha.tableExists(tableName));
4169       assertTrue(t.get(new Get(ROW)).isEmpty());
4170     }
4171 
4172     // stop the master
4173     MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
4174     cluster.stopMaster(0, false);
4175     cluster.waitOnMaster(0);
4176 
4177     // start up a new master
4178     cluster.startMaster();
4179     assertTrue(cluster.waitForActiveAndReadyMaster());
4180 
4181     // test that the same unmanaged connection works with a new
4182     // HBaseAdmin and can connect to the new master;
4183     try (HBaseAdmin newAdmin = new HBaseAdmin(conn)) {
4184       assertTrue(newAdmin.tableExists(tableName));
4185       assertTrue(newAdmin.getClusterStatus().getServersSize() == SLAVES);
4186     }
4187   }
4188 
4189   @Test
4190   public void testMiscHTableStuff() throws IOException {
4191     final TableName tableAname = TableName.valueOf("testMiscHTableStuffA");
4192     final TableName tableBname = TableName.valueOf("testMiscHTableStuffB");
4193     final byte[] attrName = Bytes.toBytes("TESTATTR");
4194     final byte[] attrValue = Bytes.toBytes("somevalue");
4195     byte[] value = Bytes.toBytes("value");
4196 
4197     Table a = TEST_UTIL.createTable(tableAname, HConstants.CATALOG_FAMILY);
4198     Table b = TEST_UTIL.createTable(tableBname, HConstants.CATALOG_FAMILY);
4199     Put put = new Put(ROW);
4200     put.add(HConstants.CATALOG_FAMILY, null, value);
4201     a.put(put);
4202 
4203     // open a new connection to A and a connection to b
4204     Table newA = new HTable(TEST_UTIL.getConfiguration(), tableAname);
4205 
4206     // copy data from A to B
4207     Scan scan = new Scan();
4208     scan.addFamily(HConstants.CATALOG_FAMILY);
4209     ResultScanner s = newA.getScanner(scan);
4210     try {
4211       for (Result r : s) {
4212         put = new Put(r.getRow());
4213         put.setDurability(Durability.SKIP_WAL);
4214         for (Cell kv : r.rawCells()) {
4215           put.add(kv);
4216         }
4217         b.put(put);
4218       }
4219     } finally {
4220       s.close();
4221     }
4222 
4223     // Opening a new connection to A will cause the tables to be reloaded
4224     Table anotherA = new HTable(TEST_UTIL.getConfiguration(), tableAname);
4225     Get get = new Get(ROW);
4226     get.addFamily(HConstants.CATALOG_FAMILY);
4227     anotherA.get(get);
4228 
4229     // We can still access A through newA because it has the table information
4230     // cached. And if it needs to recalibrate, that will cause the information
4231     // to be reloaded.
4232 
4233     // Test user metadata
4234     Admin admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
4235     // make a modifiable descriptor
4236     HTableDescriptor desc = new HTableDescriptor(a.getTableDescriptor());
4237     // offline the table
4238     admin.disableTable(tableAname);
4239     // add a user attribute to HTD
4240     desc.setValue(attrName, attrValue);
4241     // add a user attribute to HCD
4242     for (HColumnDescriptor c : desc.getFamilies())
4243       c.setValue(attrName, attrValue);
4244     // update metadata for all regions of this table
4245     admin.modifyTable(tableAname, desc);
4246     // enable the table
4247     admin.enableTable(tableAname);
4248 
4249     // Test that attribute changes were applied
4250     desc = a.getTableDescriptor();
4251     assertEquals("wrong table descriptor returned", desc.getTableName(), tableAname);
4252     // check HTD attribute
4253     value = desc.getValue(attrName);
4254     assertFalse("missing HTD attribute value", value == null);
4255     assertFalse("HTD attribute value is incorrect",
4256       Bytes.compareTo(value, attrValue) != 0);
4257     // check HCD attribute
4258     for (HColumnDescriptor c : desc.getFamilies()) {
4259       value = c.getValue(attrName);
4260       assertFalse("missing HCD attribute value", value == null);
4261       assertFalse("HCD attribute value is incorrect",
4262         Bytes.compareTo(value, attrValue) != 0);
4263     }
4264   }
4265 
4266   @Test
4267   public void testGetClosestRowBefore() throws IOException, InterruptedException {
4268     final TableName tableAname = TableName.valueOf("testGetClosestRowBefore");
4269     final byte[] firstRow = Bytes.toBytes("row111");
4270     final byte[] secondRow = Bytes.toBytes("row222");
4271     final byte[] thirdRow = Bytes.toBytes("row333");
4272     final byte[] forthRow = Bytes.toBytes("row444");
4273     final byte[] beforeFirstRow = Bytes.toBytes("row");
4274     final byte[] beforeSecondRow = Bytes.toBytes("row22");
4275     final byte[] beforeThirdRow = Bytes.toBytes("row33");
4276     final byte[] beforeForthRow = Bytes.toBytes("row44");
4277 
4278     HTable table =
4279         TEST_UTIL.createTable(tableAname,
4280           new byte[][] { HConstants.CATALOG_FAMILY, Bytes.toBytes("info2") }, 1, 1024);
4281     // set block size to 64 to making 2 kvs into one block, bypassing the walkForwardInSingleRow
4282     // in Store.rowAtOrBeforeFromStoreFile
4283     String regionName = table.getRegionLocations().firstKey().getEncodedName();
4284     Region region =
4285         TEST_UTIL.getRSForFirstRegionInTable(tableAname).getFromOnlineRegions(regionName);
4286     Put put1 = new Put(firstRow);
4287     Put put2 = new Put(secondRow);
4288     Put put3 = new Put(thirdRow);
4289     Put put4 = new Put(forthRow);
4290     byte[] one = new byte[] { 1 };
4291     byte[] two = new byte[] { 2 };
4292     byte[] three = new byte[] { 3 };
4293     byte[] four = new byte[] { 4 };
4294 
4295     put1.add(HConstants.CATALOG_FAMILY, null, one);
4296     put2.add(HConstants.CATALOG_FAMILY, null, two);
4297     put3.add(HConstants.CATALOG_FAMILY, null, three);
4298     put4.add(HConstants.CATALOG_FAMILY, null, four);
4299     table.put(put1);
4300     table.put(put2);
4301     table.put(put3);
4302     table.put(put4);
4303     region.flush(true);
4304     Result result = null;
4305 
4306     // Test before first that null is returned
4307     result = table.getRowOrBefore(beforeFirstRow, HConstants.CATALOG_FAMILY);
4308     assertTrue(result == null);
4309 
4310     // Test at first that first is returned
4311     result = table.getRowOrBefore(firstRow, HConstants.CATALOG_FAMILY);
4312     assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
4313     assertTrue(Bytes.equals(result.getRow(), firstRow));
4314     assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), one));
4315 
4316     // Test in between first and second that first is returned
4317     result = table.getRowOrBefore(beforeSecondRow, HConstants.CATALOG_FAMILY);
4318     assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
4319     assertTrue(Bytes.equals(result.getRow(), firstRow));
4320     assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), one));
4321 
4322     // Test at second make sure second is returned
4323     result = table.getRowOrBefore(secondRow, HConstants.CATALOG_FAMILY);
4324     assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
4325     assertTrue(Bytes.equals(result.getRow(), secondRow));
4326     assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), two));
4327 
4328     // Test in second and third, make sure second is returned
4329     result = table.getRowOrBefore(beforeThirdRow, HConstants.CATALOG_FAMILY);
4330     assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
4331     assertTrue(Bytes.equals(result.getRow(), secondRow));
4332     assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), two));
4333 
4334     // Test at third make sure third is returned
4335     result = table.getRowOrBefore(thirdRow, HConstants.CATALOG_FAMILY);
4336     assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
4337     assertTrue(Bytes.equals(result.getRow(), thirdRow));
4338     assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), three));
4339 
4340     // Test in third and forth, make sure third is returned
4341     result = table.getRowOrBefore(beforeForthRow, HConstants.CATALOG_FAMILY);
4342     assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
4343     assertTrue(Bytes.equals(result.getRow(), thirdRow));
4344     assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), three));
4345 
4346     // Test at forth make sure forth is returned
4347     result = table.getRowOrBefore(forthRow, HConstants.CATALOG_FAMILY);
4348     assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
4349     assertTrue(Bytes.equals(result.getRow(), forthRow));
4350     assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), four));
4351 
4352     // Test after forth make sure forth is returned
4353     result = table.getRowOrBefore(Bytes.add(forthRow, one), HConstants.CATALOG_FAMILY);
4354     assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
4355     assertTrue(Bytes.equals(result.getRow(), forthRow));
4356     assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), four));
4357 
4358     table.close();
4359   }
4360 
4361   /**
4362    * For HBASE-2156
4363    * @throws Exception
4364    */
4365   @Test
4366   public void testScanVariableReuse() throws Exception {
4367     Scan scan = new Scan();
4368     scan.addFamily(FAMILY);
4369     scan.addColumn(FAMILY, ROW);
4370 
4371     assertTrue(scan.getFamilyMap().get(FAMILY).size() == 1);
4372 
4373     scan = new Scan();
4374     scan.addFamily(FAMILY);
4375 
4376     assertTrue(scan.getFamilyMap().get(FAMILY) == null);
4377     assertTrue(scan.getFamilyMap().containsKey(FAMILY));
4378   }
4379 
4380   @Test
4381   public void testMultiRowMutation() throws Exception {
4382     LOG.info("Starting testMultiRowMutation");
4383     final TableName TABLENAME = TableName.valueOf("testMultiRowMutation");
4384     final byte [] ROW1 = Bytes.toBytes("testRow1");
4385 
4386     Table t = TEST_UTIL.createTable(TABLENAME, FAMILY);
4387     Put p = new Put(ROW);
4388     p.add(FAMILY, QUALIFIER, VALUE);
4389     MutationProto m1 = ProtobufUtil.toMutation(MutationType.PUT, p);
4390 
4391     p = new Put(ROW1);
4392     p.add(FAMILY, QUALIFIER, VALUE);
4393     MutationProto m2 = ProtobufUtil.toMutation(MutationType.PUT, p);
4394 
4395     MutateRowsRequest.Builder mrmBuilder = MutateRowsRequest.newBuilder();
4396     mrmBuilder.addMutationRequest(m1);
4397     mrmBuilder.addMutationRequest(m2);
4398     MutateRowsRequest mrm = mrmBuilder.build();
4399     CoprocessorRpcChannel channel = t.coprocessorService(ROW);
4400     MultiRowMutationService.BlockingInterface service =
4401        MultiRowMutationService.newBlockingStub(channel);
4402     service.mutateRows(null, mrm);
4403     Get g = new Get(ROW);
4404     Result r = t.get(g);
4405     assertEquals(0, Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIER)));
4406     g = new Get(ROW1);
4407     r = t.get(g);
4408     assertEquals(0, Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIER)));
4409   }
4410 
4411   @Test
4412   public void testRowMutation() throws Exception {
4413     LOG.info("Starting testRowMutation");
4414     final TableName TABLENAME = TableName.valueOf("testRowMutation");
4415     Table t = TEST_UTIL.createTable(TABLENAME, FAMILY);
4416     byte [][] QUALIFIERS = new byte [][] {
4417         Bytes.toBytes("a"), Bytes.toBytes("b")
4418     };
4419     RowMutations arm = new RowMutations(ROW);
4420     Put p = new Put(ROW);
4421     p.add(FAMILY, QUALIFIERS[0], VALUE);
4422     arm.add(p);
4423     t.mutateRow(arm);
4424 
4425     Get g = new Get(ROW);
4426     Result r = t.get(g);
4427     assertEquals(0, Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIERS[0])));
4428 
4429     arm = new RowMutations(ROW);
4430     p = new Put(ROW);
4431     p.add(FAMILY, QUALIFIERS[1], VALUE);
4432     arm.add(p);
4433     Delete d = new Delete(ROW);
4434     d.deleteColumns(FAMILY, QUALIFIERS[0]);
4435     arm.add(d);
4436     // TODO: Trying mutateRow again.  The batch was failing with a one try only.
4437     t.mutateRow(arm);
4438     r = t.get(g);
4439     assertEquals(0, Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIERS[1])));
4440     assertNull(r.getValue(FAMILY, QUALIFIERS[0]));
4441 
4442     //Test that we get a region level exception
4443     try {
4444       arm = new RowMutations(ROW);
4445       p = new Put(ROW);
4446       p.add(new byte[]{'b', 'o', 'g', 'u', 's'}, QUALIFIERS[0], VALUE);
4447       arm.add(p);
4448       t.mutateRow(arm);
4449       fail("Expected NoSuchColumnFamilyException");
4450     } catch(NoSuchColumnFamilyException e) {
4451     }
4452   }
4453 
4454   @Test
4455   public void testAppend() throws Exception {
4456     LOG.info("Starting testAppend");
4457     final TableName TABLENAME = TableName.valueOf("testAppend");
4458     Table t = TEST_UTIL.createTable(TABLENAME, FAMILY);
4459     byte[] v1 = Bytes.toBytes("42");
4460     byte[] v2 = Bytes.toBytes("23");
4461     byte [][] QUALIFIERS = new byte [][] {
4462         Bytes.toBytes("b"), Bytes.toBytes("a"), Bytes.toBytes("c")
4463     };
4464     Append a = new Append(ROW);
4465     a.add(FAMILY, QUALIFIERS[0], v1);
4466     a.add(FAMILY, QUALIFIERS[1], v2);
4467     a.setReturnResults(false);
4468     assertNullResult(t.append(a));
4469 
4470     a = new Append(ROW);
4471     a.add(FAMILY, QUALIFIERS[0], v2);
4472     a.add(FAMILY, QUALIFIERS[1], v1);
4473     a.add(FAMILY, QUALIFIERS[2], v2);
4474     Result r = t.append(a);
4475     assertEquals(0, Bytes.compareTo(Bytes.add(v1,v2), r.getValue(FAMILY, QUALIFIERS[0])));
4476     assertEquals(0, Bytes.compareTo(Bytes.add(v2,v1), r.getValue(FAMILY, QUALIFIERS[1])));
4477     // QUALIFIERS[2] previously not exist, verify both value and timestamp are correct
4478     assertEquals(0, Bytes.compareTo(v2, r.getValue(FAMILY, QUALIFIERS[2])));
4479     assertEquals(r.getColumnLatest(FAMILY, QUALIFIERS[0]).getTimestamp(),
4480         r.getColumnLatest(FAMILY, QUALIFIERS[2]).getTimestamp());
4481   }
4482 
4483   @Test
4484   public void testIncrementWithDeletes() throws Exception {
4485     LOG.info("Starting testIncrementWithDeletes");
4486     final TableName TABLENAME =
4487         TableName.valueOf("testIncrementWithDeletes");
4488     Table ht = TEST_UTIL.createTable(TABLENAME, FAMILY);
4489     final byte[] COLUMN = Bytes.toBytes("column");
4490 
4491     ht.incrementColumnValue(ROW, FAMILY, COLUMN, 5);
4492     TEST_UTIL.flush(TABLENAME);
4493 
4494     Delete del = new Delete(ROW);
4495     ht.delete(del);
4496 
4497     ht.incrementColumnValue(ROW, FAMILY, COLUMN, 5);
4498 
4499     Get get = new Get(ROW);
4500     Result r = ht.get(get);
4501     assertEquals(1, r.size());
4502     assertEquals(5, Bytes.toLong(r.getValue(FAMILY, COLUMN)));
4503   }
4504 
4505   @Test
4506   public void testIncrementingInvalidValue() throws Exception {
4507     LOG.info("Starting testIncrementingInvalidValue");
4508     final TableName TABLENAME = TableName.valueOf("testIncrementingInvalidValue");
4509     Table ht = TEST_UTIL.createTable(TABLENAME, FAMILY);
4510     final byte[] COLUMN = Bytes.toBytes("column");
4511     Put p = new Put(ROW);
4512     // write an integer here (not a Long)
4513     p.add(FAMILY, COLUMN, Bytes.toBytes(5));
4514     ht.put(p);
4515     try {
4516       ht.incrementColumnValue(ROW, FAMILY, COLUMN, 5);
4517       fail("Should have thrown DoNotRetryIOException");
4518     } catch (DoNotRetryIOException iox) {
4519       // success
4520     }
4521     Increment inc = new Increment(ROW);
4522     inc.addColumn(FAMILY, COLUMN, 5);
4523     try {
4524       ht.increment(inc);
4525       fail("Should have thrown DoNotRetryIOException");
4526     } catch (DoNotRetryIOException iox) {
4527       // success
4528     }
4529   }
4530 
4531   @Test
4532   public void testIncrementInvalidArguments() throws Exception {
4533     LOG.info("Starting testIncrementInvalidArguments");
4534     final TableName TABLENAME = TableName.valueOf("testIncrementInvalidArguments");
4535     Table ht = TEST_UTIL.createTable(TABLENAME, FAMILY);
4536     final byte[] COLUMN = Bytes.toBytes("column");
4537     try {
4538       // try null row
4539       ht.incrementColumnValue(null, FAMILY, COLUMN, 5);
4540       fail("Should have thrown IOException");
4541     } catch (IOException iox) {
4542       // success
4543     }
4544     try {
4545       // try null family
4546       ht.incrementColumnValue(ROW, null, COLUMN, 5);
4547       fail("Should have thrown IOException");
4548     } catch (IOException iox) {
4549       // success
4550     }
4551     try {
4552       // try null qualifier
4553       ht.incrementColumnValue(ROW, FAMILY, null, 5);
4554       fail("Should have thrown IOException");
4555     } catch (IOException iox) {
4556       // success
4557     }
4558     // try null row
4559     try {
4560       Increment incNoRow = new Increment((byte [])null);
4561       incNoRow.addColumn(FAMILY, COLUMN, 5);
4562       fail("Should have thrown IllegalArgumentException");
4563     } catch (IllegalArgumentException iax) {
4564       // success
4565     } catch (NullPointerException npe) {
4566       // success
4567     }
4568     // try null family
4569     try {
4570       Increment incNoFamily = new Increment(ROW);
4571       incNoFamily.addColumn(null, COLUMN, 5);
4572       fail("Should have thrown IllegalArgumentException");
4573     } catch (IllegalArgumentException iax) {
4574       // success
4575     }
4576     // try null qualifier
4577     try {
4578       Increment incNoQualifier = new Increment(ROW);
4579       incNoQualifier.addColumn(FAMILY, null, 5);
4580       fail("Should have thrown IllegalArgumentException");
4581     } catch (IllegalArgumentException iax) {
4582       // success
4583     }
4584   }
4585 
4586   @Test
4587   public void testIncrementOutOfOrder() throws Exception {
4588     LOG.info("Starting testIncrementOutOfOrder");
4589     final TableName TABLENAME = TableName.valueOf("testIncrementOutOfOrder");
4590     Table ht = TEST_UTIL.createTable(TABLENAME, FAMILY);
4591 
4592     byte [][] QUALIFIERS = new byte [][] {
4593       Bytes.toBytes("B"), Bytes.toBytes("A"), Bytes.toBytes("C")
4594     };
4595 
4596     Increment inc = new Increment(ROW);
4597     for (int i=0; i<QUALIFIERS.length; i++) {
4598       inc.addColumn(FAMILY, QUALIFIERS[i], 1);
4599     }
4600     ht.increment(inc);
4601 
4602     // Verify expected results
4603     Result r = ht.get(new Get(ROW));
4604     Cell [] kvs = r.rawCells();
4605     assertEquals(3, kvs.length);
4606     assertIncrementKey(kvs[0], ROW, FAMILY, QUALIFIERS[1], 1);
4607     assertIncrementKey(kvs[1], ROW, FAMILY, QUALIFIERS[0], 1);
4608     assertIncrementKey(kvs[2], ROW, FAMILY, QUALIFIERS[2], 1);
4609 
4610     // Now try multiple columns again
4611     inc = new Increment(ROW);
4612     for (int i=0; i<QUALIFIERS.length; i++) {
4613       inc.addColumn(FAMILY, QUALIFIERS[i], 1);
4614     }
4615     ht.increment(inc);
4616 
4617     // Verify
4618     r = ht.get(new Get(ROW));
4619     kvs = r.rawCells();
4620     assertEquals(3, kvs.length);
4621     assertIncrementKey(kvs[0], ROW, FAMILY, QUALIFIERS[1], 2);
4622     assertIncrementKey(kvs[1], ROW, FAMILY, QUALIFIERS[0], 2);
4623     assertIncrementKey(kvs[2], ROW, FAMILY, QUALIFIERS[2], 2);
4624   }
4625 
4626   @Test
4627   public void testIncrementOnSameColumn() throws Exception {
4628     LOG.info("Starting testIncrementOnSameColumn");
4629     final byte[] TABLENAME = Bytes.toBytes("testIncrementOnSameColumn");
4630     HTable ht = TEST_UTIL.createTable(TABLENAME, FAMILY);
4631 
4632     byte[][] QUALIFIERS =
4633         new byte[][] { Bytes.toBytes("A"), Bytes.toBytes("B"), Bytes.toBytes("C") };
4634 
4635     Increment inc = new Increment(ROW);
4636     for (int i = 0; i < QUALIFIERS.length; i++) {
4637       inc.addColumn(FAMILY, QUALIFIERS[i], 1);
4638       inc.addColumn(FAMILY, QUALIFIERS[i], 1);
4639     }
4640     ht.increment(inc);
4641 
4642     // Verify expected results
4643     Result r = ht.get(new Get(ROW));
4644     Cell[] kvs = r.rawCells();
4645     assertEquals(3, kvs.length);
4646     assertIncrementKey(kvs[0], ROW, FAMILY, QUALIFIERS[0], 1);
4647     assertIncrementKey(kvs[1], ROW, FAMILY, QUALIFIERS[1], 1);
4648     assertIncrementKey(kvs[2], ROW, FAMILY, QUALIFIERS[2], 1);
4649 
4650     // Now try multiple columns again
4651     inc = new Increment(ROW);
4652     for (int i = 0; i < QUALIFIERS.length; i++) {
4653       inc.addColumn(FAMILY, QUALIFIERS[i], 1);
4654       inc.addColumn(FAMILY, QUALIFIERS[i], 1);
4655     }
4656     ht.increment(inc);
4657 
4658     // Verify
4659     r = ht.get(new Get(ROW));
4660     kvs = r.rawCells();
4661     assertEquals(3, kvs.length);
4662     assertIncrementKey(kvs[0], ROW, FAMILY, QUALIFIERS[0], 2);
4663     assertIncrementKey(kvs[1], ROW, FAMILY, QUALIFIERS[1], 2);
4664     assertIncrementKey(kvs[2], ROW, FAMILY, QUALIFIERS[2], 2);
4665     
4666     ht.close();
4667   }
4668 
4669   @Test
4670   public void testIncrement() throws Exception {
4671     LOG.info("Starting testIncrement");
4672     final TableName TABLENAME = TableName.valueOf("testIncrement");
4673     Table ht = TEST_UTIL.createTable(TABLENAME, FAMILY);
4674 
4675     byte [][] ROWS = new byte [][] {
4676         Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c"),
4677         Bytes.toBytes("d"), Bytes.toBytes("e"), Bytes.toBytes("f"),
4678         Bytes.toBytes("g"), Bytes.toBytes("h"), Bytes.toBytes("i")
4679     };
4680     byte [][] QUALIFIERS = new byte [][] {
4681         Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c"),
4682         Bytes.toBytes("d"), Bytes.toBytes("e"), Bytes.toBytes("f"),
4683         Bytes.toBytes("g"), Bytes.toBytes("h"), Bytes.toBytes("i")
4684     };
4685 
4686     // Do some simple single-column increments
4687 
4688     // First with old API
4689     ht.incrementColumnValue(ROW, FAMILY, QUALIFIERS[0], 1);
4690     ht.incrementColumnValue(ROW, FAMILY, QUALIFIERS[1], 2);
4691     ht.incrementColumnValue(ROW, FAMILY, QUALIFIERS[2], 3);
4692     ht.incrementColumnValue(ROW, FAMILY, QUALIFIERS[3], 4);
4693 
4694     // Now increment things incremented with old and do some new
4695     Increment inc = new Increment(ROW);
4696     inc.addColumn(FAMILY, QUALIFIERS[1], 1);
4697     inc.addColumn(FAMILY, QUALIFIERS[3], 1);
4698     inc.addColumn(FAMILY, QUALIFIERS[4], 1);
4699     ht.increment(inc);
4700 
4701     // Verify expected results
4702     Result r = ht.get(new Get(ROW));
4703     Cell [] kvs = r.rawCells();
4704     assertEquals(5, kvs.length);
4705     assertIncrementKey(kvs[0], ROW, FAMILY, QUALIFIERS[0], 1);
4706     assertIncrementKey(kvs[1], ROW, FAMILY, QUALIFIERS[1], 3);
4707     assertIncrementKey(kvs[2], ROW, FAMILY, QUALIFIERS[2], 3);
4708     assertIncrementKey(kvs[3], ROW, FAMILY, QUALIFIERS[3], 5);
4709     assertIncrementKey(kvs[4], ROW, FAMILY, QUALIFIERS[4], 1);
4710 
4711     // Now try multiple columns by different amounts
4712     inc = new Increment(ROWS[0]);
4713     for (int i=0;i<QUALIFIERS.length;i++) {
4714       inc.addColumn(FAMILY, QUALIFIERS[i], i+1);
4715     }
4716     ht.increment(inc);
4717     // Verify
4718     r = ht.get(new Get(ROWS[0]));
4719     kvs = r.rawCells();
4720     assertEquals(QUALIFIERS.length, kvs.length);
4721     for (int i=0;i<QUALIFIERS.length;i++) {
4722       assertIncrementKey(kvs[i], ROWS[0], FAMILY, QUALIFIERS[i], i+1);
4723     }
4724 
4725     // Re-increment them
4726     inc = new Increment(ROWS[0]);
4727     for (int i=0;i<QUALIFIERS.length;i++) {
4728       inc.addColumn(FAMILY, QUALIFIERS[i], i+1);
4729     }
4730     ht.increment(inc);
4731     // Verify
4732     r = ht.get(new Get(ROWS[0]));
4733     kvs = r.rawCells();
4734     assertEquals(QUALIFIERS.length, kvs.length);
4735     for (int i=0;i<QUALIFIERS.length;i++) {
4736       assertIncrementKey(kvs[i], ROWS[0], FAMILY, QUALIFIERS[i], 2*(i+1));
4737     }
4738   }
4739 
4740 
4741   @Test
4742   public void testClientPoolRoundRobin() throws IOException {
4743     final TableName tableName = TableName.valueOf("testClientPoolRoundRobin");
4744 
4745     int poolSize = 3;
4746     int numVersions = poolSize * 2;
4747     Configuration conf = TEST_UTIL.getConfiguration();
4748     conf.set(HConstants.HBASE_CLIENT_IPC_POOL_TYPE, "round-robin");
4749     conf.setInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, poolSize);
4750 
4751     Table table = TEST_UTIL.createTable(tableName, new byte[][] { FAMILY }, conf, Integer.MAX_VALUE);
4752 
4753     final long ts = EnvironmentEdgeManager.currentTime();
4754     Get get = new Get(ROW);
4755     get.addColumn(FAMILY, QUALIFIER);
4756     get.setMaxVersions();
4757 
4758     for (int versions = 1; versions <= numVersions; versions++) {
4759       Put put = new Put(ROW);
4760       put.add(FAMILY, QUALIFIER, ts + versions, VALUE);
4761       table.put(put);
4762 
4763       Result result = table.get(get);
4764       NavigableMap<Long, byte[]> navigableMap = result.getMap().get(FAMILY)
4765           .get(QUALIFIER);
4766 
4767       assertEquals("The number of versions of '" + FAMILY + ":" + QUALIFIER
4768           + " did not match " + versions, versions, navigableMap.size());
4769       for (Map.Entry<Long, byte[]> entry : navigableMap.entrySet()) {
4770         assertTrue("The value at time " + entry.getKey()
4771             + " did not match what was put",
4772             Bytes.equals(VALUE, entry.getValue()));
4773       }
4774     }
4775   }
4776 
4777   @Ignore ("Flakey: HBASE-8989") @Test
4778   public void testClientPoolThreadLocal() throws IOException {
4779     final TableName tableName = TableName.valueOf("testClientPoolThreadLocal");
4780 
4781     int poolSize = Integer.MAX_VALUE;
4782     int numVersions = 3;
4783     Configuration conf = TEST_UTIL.getConfiguration();
4784     conf.set(HConstants.HBASE_CLIENT_IPC_POOL_TYPE, "thread-local");
4785     conf.setInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, poolSize);
4786 
4787     final Table table = TEST_UTIL.createTable(tableName,
4788         new byte[][] { FAMILY }, conf, 3);
4789 
4790     final long ts = EnvironmentEdgeManager.currentTime();
4791     final Get get = new Get(ROW);
4792     get.addColumn(FAMILY, QUALIFIER);
4793     get.setMaxVersions();
4794 
4795     for (int versions = 1; versions <= numVersions; versions++) {
4796       Put put = new Put(ROW);
4797       put.add(FAMILY, QUALIFIER, ts + versions, VALUE);
4798       table.put(put);
4799 
4800       Result result = table.get(get);
4801       NavigableMap<Long, byte[]> navigableMap = result.getMap().get(FAMILY)
4802           .get(QUALIFIER);
4803 
4804       assertEquals("The number of versions of '" + FAMILY + ":" + QUALIFIER + " did not match " +
4805         versions + "; " + put.toString() + ", " + get.toString(), versions, navigableMap.size());
4806       for (Map.Entry<Long, byte[]> entry : navigableMap.entrySet()) {
4807         assertTrue("The value at time " + entry.getKey()
4808             + " did not match what was put",
4809             Bytes.equals(VALUE, entry.getValue()));
4810       }
4811     }
4812 
4813     final Object waitLock = new Object();
4814     ExecutorService executorService = Executors.newFixedThreadPool(numVersions);
4815     final AtomicReference<AssertionError> error = new AtomicReference<AssertionError>(null);
4816     for (int versions = numVersions; versions < numVersions * 2; versions++) {
4817       final int versionsCopy = versions;
4818       executorService.submit(new Callable<Void>() {
4819         @Override
4820         public Void call() {
4821           try {
4822             Put put = new Put(ROW);
4823             put.add(FAMILY, QUALIFIER, ts + versionsCopy, VALUE);
4824             table.put(put);
4825 
4826             Result result = table.get(get);
4827             NavigableMap<Long, byte[]> navigableMap = result.getMap()
4828                 .get(FAMILY).get(QUALIFIER);
4829 
4830             assertEquals("The number of versions of '" + Bytes.toString(FAMILY) + ":"
4831                 + Bytes.toString(QUALIFIER) + " did not match " + versionsCopy, versionsCopy,
4832                 navigableMap.size());
4833             for (Map.Entry<Long, byte[]> entry : navigableMap.entrySet()) {
4834               assertTrue("The value at time " + entry.getKey()
4835                   + " did not match what was put",
4836                   Bytes.equals(VALUE, entry.getValue()));
4837             }
4838             synchronized (waitLock) {
4839               waitLock.wait();
4840             }
4841           } catch (Exception e) {
4842           } catch (AssertionError e) {
4843             // the error happens in a thread, it won't fail the test,
4844             // need to pass it to the caller for proper handling.
4845             error.set(e);
4846             LOG.error(e);
4847           }
4848 
4849           return null;
4850         }
4851       });
4852     }
4853     synchronized (waitLock) {
4854       waitLock.notifyAll();
4855     }
4856     executorService.shutdownNow();
4857     assertNull(error.get());
4858   }
4859 
4860   @Test
4861   public void testCheckAndPut() throws IOException {
4862     final byte [] anotherrow = Bytes.toBytes("anotherrow");
4863     final byte [] value2 = Bytes.toBytes("abcd");
4864 
4865     Table table = TEST_UTIL.createTable(TableName.valueOf("testCheckAndPut"), FAMILY);
4866     Put put1 = new Put(ROW);
4867     put1.add(FAMILY, QUALIFIER, VALUE);
4868 
4869     // row doesn't exist, so using non-null value should be considered "not match".
4870     boolean ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, VALUE, put1);
4871     assertEquals(ok, false);
4872 
4873     // row doesn't exist, so using "null" to check for existence should be considered "match".
4874     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, null, put1);
4875     assertEquals(ok, true);
4876 
4877     // row now exists, so using "null" to check for existence should be considered "not match".
4878     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, null, put1);
4879     assertEquals(ok, false);
4880 
4881     Put put2 = new Put(ROW);
4882     put2.add(FAMILY, QUALIFIER, value2);
4883 
4884     // row now exists, use the matching value to check
4885     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, VALUE, put2);
4886     assertEquals(ok, true);
4887 
4888     Put put3 = new Put(anotherrow);
4889     put3.add(FAMILY, QUALIFIER, VALUE);
4890 
4891     // try to do CheckAndPut on different rows
4892     try {
4893         ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, value2, put3);
4894         fail("trying to check and modify different rows should have failed.");
4895     } catch(Exception e) {}
4896 
4897   }
4898 
4899   @Test
4900   public void testCheckAndPutWithCompareOp() throws IOException {
4901     final byte [] value1 = Bytes.toBytes("aaaa");
4902     final byte [] value2 = Bytes.toBytes("bbbb");
4903     final byte [] value3 = Bytes.toBytes("cccc");
4904     final byte [] value4 = Bytes.toBytes("dddd");
4905 
4906     Table table = TEST_UTIL.createTable(TableName.valueOf("testCheckAndPutWithCompareOp"), FAMILY);
4907 
4908     Put put2 = new Put(ROW);
4909     put2.add(FAMILY, QUALIFIER, value2);
4910 
4911     Put put3 = new Put(ROW);
4912     put3.add(FAMILY, QUALIFIER, value3);
4913 
4914     // row doesn't exist, so using "null" to check for existence should be considered "match".
4915     boolean ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, null, put2);
4916     assertEquals(ok, true);
4917 
4918     // cell = "bbbb", using "aaaa" to compare only LESS/LESS_OR_EQUAL/NOT_EQUAL
4919     // turns out "match"
4920     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.GREATER, value1, put2);
4921     assertEquals(ok, false);
4922     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.EQUAL, value1, put2);
4923     assertEquals(ok, false);
4924     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.GREATER_OR_EQUAL, value1, put2);
4925     assertEquals(ok, false);
4926     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.LESS, value1, put2);
4927     assertEquals(ok, true);
4928     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.LESS_OR_EQUAL, value1, put2);
4929     assertEquals(ok, true);
4930     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.NOT_EQUAL, value1, put3);
4931     assertEquals(ok, true);
4932 
4933     // cell = "cccc", using "dddd" to compare only LARGER/LARGER_OR_EQUAL/NOT_EQUAL
4934     // turns out "match"
4935     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.LESS, value4, put3);
4936     assertEquals(ok, false);
4937     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.LESS_OR_EQUAL, value4, put3);
4938     assertEquals(ok, false);
4939     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.EQUAL, value4, put3);
4940     assertEquals(ok, false);
4941     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.GREATER, value4, put3);
4942     assertEquals(ok, true);
4943     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.GREATER_OR_EQUAL, value4, put3);
4944     assertEquals(ok, true);
4945     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.NOT_EQUAL, value4, put2);
4946     assertEquals(ok, true);
4947 
4948     // cell = "bbbb", using "bbbb" to compare only GREATER_OR_EQUAL/LESS_OR_EQUAL/EQUAL
4949     // turns out "match"
4950     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.GREATER, value2, put2);
4951     assertEquals(ok, false);
4952     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.NOT_EQUAL, value2, put2);
4953     assertEquals(ok, false);
4954     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.LESS, value2, put2);
4955     assertEquals(ok, false);
4956     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.GREATER_OR_EQUAL, value2, put2);
4957     assertEquals(ok, true);
4958     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.LESS_OR_EQUAL, value2, put2);
4959     assertEquals(ok, true);
4960     ok = table.checkAndPut(ROW, FAMILY, QUALIFIER, CompareOp.EQUAL, value2, put3);
4961     assertEquals(ok, true);
4962   }
4963 
4964   @Test
4965   public void testCheckAndDeleteWithCompareOp() throws IOException {
4966     final byte [] value1 = Bytes.toBytes("aaaa");
4967     final byte [] value2 = Bytes.toBytes("bbbb");
4968     final byte [] value3 = Bytes.toBytes("cccc");
4969     final byte [] value4 = Bytes.toBytes("dddd");
4970 
4971     Table table = TEST_UTIL.createTable(TableName.valueOf("testCheckAndDeleteWithCompareOp"),
4972         FAMILY);
4973 
4974     Put put2 = new Put(ROW);
4975     put2.add(FAMILY, QUALIFIER, value2);
4976     table.put(put2);
4977 
4978     Put put3 = new Put(ROW);
4979     put3.add(FAMILY, QUALIFIER, value3);
4980 
4981     Delete delete = new Delete(ROW);
4982     delete.deleteColumns(FAMILY, QUALIFIER);
4983 
4984     // cell = "bbbb", using "aaaa" to compare only LESS/LESS_OR_EQUAL/NOT_EQUAL
4985     // turns out "match"
4986     boolean ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.GREATER, value1, delete);
4987     assertEquals(ok, false);
4988     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.EQUAL, value1, delete);
4989     assertEquals(ok, false);
4990     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.GREATER_OR_EQUAL, value1, delete);
4991     assertEquals(ok, false);
4992     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.LESS, value1, delete);
4993     assertEquals(ok, true);
4994     table.put(put2);
4995     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.LESS_OR_EQUAL, value1, delete);
4996     assertEquals(ok, true);
4997     table.put(put2);
4998     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.NOT_EQUAL, value1, delete);
4999     assertEquals(ok, true);
5000 
5001     // cell = "cccc", using "dddd" to compare only LARGER/LARGER_OR_EQUAL/NOT_EQUAL
5002     // turns out "match"
5003     table.put(put3);
5004     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.LESS, value4, delete);
5005     assertEquals(ok, false);
5006     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.LESS_OR_EQUAL, value4, delete);
5007     assertEquals(ok, false);
5008     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.EQUAL, value4, delete);
5009     assertEquals(ok, false);
5010     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.GREATER, value4, delete);
5011     assertEquals(ok, true);
5012     table.put(put3);
5013     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.GREATER_OR_EQUAL, value4, delete);
5014     assertEquals(ok, true);
5015     table.put(put3);
5016     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.NOT_EQUAL, value4, delete);
5017     assertEquals(ok, true);
5018 
5019     // cell = "bbbb", using "bbbb" to compare only GREATER_OR_EQUAL/LESS_OR_EQUAL/EQUAL
5020     // turns out "match"
5021     table.put(put2);
5022     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.GREATER, value2, delete);
5023     assertEquals(ok, false);
5024     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.NOT_EQUAL, value2, delete);
5025     assertEquals(ok, false);
5026     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.LESS, value2, delete);
5027     assertEquals(ok, false);
5028     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.GREATER_OR_EQUAL, value2, delete);
5029     assertEquals(ok, true);
5030     table.put(put2);
5031     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.LESS_OR_EQUAL, value2, delete);
5032     assertEquals(ok, true);
5033     table.put(put2);
5034     ok = table.checkAndDelete(ROW, FAMILY, QUALIFIER, CompareOp.EQUAL, value2, delete);
5035     assertEquals(ok, true);
5036   }
5037 
5038   /**
5039   * Test ScanMetrics
5040   * @throws Exception
5041   */
5042   @Test
5043   @SuppressWarnings ("unused")
5044   public void testScanMetrics() throws Exception {
5045     TableName TABLENAME = TableName.valueOf("testScanMetrics");
5046 
5047     Configuration conf = TEST_UTIL.getConfiguration();
5048 
5049     // Set up test table:
5050     // Create table:
5051     HTable ht = TEST_UTIL.createMultiRegionTable(TABLENAME, FAMILY);
5052     int numOfRegions = -1;
5053     try (RegionLocator r = ht.getRegionLocator()) {
5054       numOfRegions = r.getStartKeys().length;
5055     }
5056     // Create 3 rows in the table, with rowkeys starting with "zzz*" so that
5057     // scan are forced to hit all the regions.
5058     Put put1 = new Put(Bytes.toBytes("zzz1"));
5059     put1.add(FAMILY, QUALIFIER, VALUE);
5060     Put put2 = new Put(Bytes.toBytes("zzz2"));
5061     put2.add(FAMILY, QUALIFIER, VALUE);
5062     Put put3 = new Put(Bytes.toBytes("zzz3"));
5063     put3.add(FAMILY, QUALIFIER, VALUE);
5064     ht.put(Arrays.asList(put1, put2, put3));
5065 
5066     Scan scan1 = new Scan();
5067     int numRecords = 0;
5068     ResultScanner scanner = ht.getScanner(scan1);
5069     for(Result result : scanner) {
5070       numRecords++;
5071     }
5072     scanner.close();
5073     LOG.info("test data has " + numRecords + " records.");
5074 
5075     // by default, scan metrics collection is turned off
5076     assertEquals(null, scan1.getScanMetrics());
5077 
5078     // turn on scan metrics
5079     Scan scan2 = new Scan();
5080     scan2.setScanMetricsEnabled(true);
5081     scan2.setCaching(numRecords+1);
5082     scanner = ht.getScanner(scan2);
5083     for (Result result : scanner.next(numRecords - 1)) {
5084     }
5085     scanner.close();
5086     // closing the scanner will set the metrics.
5087     assertNotNull(scan2.getScanMetrics());
5088 
5089     // set caching to 1, because metrics are collected in each roundtrip only
5090     scan2 = new Scan();
5091     scan2.setScanMetricsEnabled(true);
5092     scan2.setCaching(1);
5093     scanner = ht.getScanner(scan2);
5094     // per HBASE-5717, this should still collect even if you don't run all the way to
5095     // the end of the scanner. So this is asking for 2 of the 3 rows we inserted.
5096     for (Result result : scanner.next(numRecords - 1)) {
5097     }
5098     scanner.close();
5099 
5100     ScanMetrics scanMetrics = scan2.getScanMetrics();
5101     assertEquals("Did not access all the regions in the table", numOfRegions,
5102         scanMetrics.countOfRegions.get());
5103 
5104     // now, test that the metrics are still collected even if you don't call close, but do
5105     // run past the end of all the records
5106     /** There seems to be a timing issue here.  Comment out for now. Fix when time.
5107     Scan scanWithoutClose = new Scan();
5108     scanWithoutClose.setCaching(1);
5109     scanWithoutClose.setScanMetricsEnabled(true);
5110     ResultScanner scannerWithoutClose = ht.getScanner(scanWithoutClose);
5111     for (Result result : scannerWithoutClose.next(numRecords + 1)) {
5112     }
5113     ScanMetrics scanMetricsWithoutClose = getScanMetrics(scanWithoutClose);
5114     assertEquals("Did not access all the regions in the table", numOfRegions,
5115         scanMetricsWithoutClose.countOfRegions.get());
5116     */
5117 
5118     // finally, test that the metrics are collected correctly if you both run past all the records,
5119     // AND close the scanner
5120     Scan scanWithClose = new Scan();
5121     // make sure we can set caching up to the number of a scanned values
5122     scanWithClose.setCaching(numRecords);
5123     scanWithClose.setScanMetricsEnabled(true);
5124     ResultScanner scannerWithClose = ht.getScanner(scanWithClose);
5125     for (Result result : scannerWithClose.next(numRecords + 1)) {
5126     }
5127     scannerWithClose.close();
5128     ScanMetrics scanMetricsWithClose = getScanMetrics(scanWithClose);
5129     assertEquals("Did not access all the regions in the table", numOfRegions,
5130         scanMetricsWithClose.countOfRegions.get());
5131   }
5132 
5133   private ScanMetrics getScanMetrics(Scan scan) throws Exception {
5134     byte[] serializedMetrics = scan.getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA);
5135     assertTrue("Serialized metrics were not found.", serializedMetrics != null);
5136 
5137     ScanMetrics scanMetrics = ProtobufUtil.toScanMetrics(serializedMetrics);
5138 
5139     return scanMetrics;
5140   }
5141 
5142   /**
5143    * Tests that cache on write works all the way up from the client-side.
5144    *
5145    * Performs inserts, flushes, and compactions, verifying changes in the block
5146    * cache along the way.
5147    *
5148    * @throws Exception
5149    */
5150   @Test
5151   public void testCacheOnWriteEvictOnClose() throws Exception {
5152     TableName tableName = TableName.valueOf("testCOWEOCfromClient");
5153     byte [] data = Bytes.toBytes("data");
5154     HTable table = TEST_UTIL.createTable(tableName, FAMILY);
5155     // get the block cache and region
5156     String regionName = table.getRegionLocations().firstKey().getEncodedName();
5157     Region region = TEST_UTIL.getRSForFirstRegionInTable(tableName)
5158       .getFromOnlineRegions(regionName);
5159     Store store = region.getStores().iterator().next();
5160     CacheConfig cacheConf = store.getCacheConfig();
5161     cacheConf.setCacheDataOnWrite(true);
5162     cacheConf.setEvictOnClose(true);
5163     BlockCache cache = cacheConf.getBlockCache();
5164 
5165     // establish baseline stats
5166     long startBlockCount = cache.getBlockCount();
5167     long startBlockHits = cache.getStats().getHitCount();
5168     long startBlockMiss = cache.getStats().getMissCount();
5169 
5170     // wait till baseline is stable, (minimal 500 ms)
5171     for (int i = 0; i < 5; i++) {
5172       Thread.sleep(100);
5173       if (startBlockCount != cache.getBlockCount()
5174           || startBlockHits != cache.getStats().getHitCount()
5175           || startBlockMiss != cache.getStats().getMissCount()) {
5176         startBlockCount = cache.getBlockCount();
5177         startBlockHits = cache.getStats().getHitCount();
5178         startBlockMiss = cache.getStats().getMissCount();
5179         i = -1;
5180       }
5181     }
5182 
5183     // insert data
5184     Put put = new Put(ROW);
5185     put.add(FAMILY, QUALIFIER, data);
5186     table.put(put);
5187     assertTrue(Bytes.equals(table.get(new Get(ROW)).value(), data));
5188     // data was in memstore so don't expect any changes
5189     assertEquals(startBlockCount, cache.getBlockCount());
5190     assertEquals(startBlockHits, cache.getStats().getHitCount());
5191     assertEquals(startBlockMiss, cache.getStats().getMissCount());
5192     // flush the data
5193     System.out.println("Flushing cache");
5194     region.flush(true);
5195     // expect one more block in cache, no change in hits/misses
5196     long expectedBlockCount = startBlockCount + 1;
5197     long expectedBlockHits = startBlockHits;
5198     long expectedBlockMiss = startBlockMiss;
5199     assertEquals(expectedBlockCount, cache.getBlockCount());
5200     assertEquals(expectedBlockHits, cache.getStats().getHitCount());
5201     assertEquals(expectedBlockMiss, cache.getStats().getMissCount());
5202     // read the data and expect same blocks, one new hit, no misses
5203     assertTrue(Bytes.equals(table.get(new Get(ROW)).value(), data));
5204     assertEquals(expectedBlockCount, cache.getBlockCount());
5205     assertEquals(++expectedBlockHits, cache.getStats().getHitCount());
5206     assertEquals(expectedBlockMiss, cache.getStats().getMissCount());
5207     // insert a second column, read the row, no new blocks, one new hit
5208     byte [] QUALIFIER2 = Bytes.add(QUALIFIER, QUALIFIER);
5209     byte [] data2 = Bytes.add(data, data);
5210     put = new Put(ROW);
5211     put.add(FAMILY, QUALIFIER2, data2);
5212     table.put(put);
5213     Result r = table.get(new Get(ROW));
5214     assertTrue(Bytes.equals(r.getValue(FAMILY, QUALIFIER), data));
5215     assertTrue(Bytes.equals(r.getValue(FAMILY, QUALIFIER2), data2));
5216     assertEquals(expectedBlockCount, cache.getBlockCount());
5217     assertEquals(++expectedBlockHits, cache.getStats().getHitCount());
5218     assertEquals(expectedBlockMiss, cache.getStats().getMissCount());
5219     // flush, one new block
5220     System.out.println("Flushing cache");
5221     region.flush(true);
5222     assertEquals(++expectedBlockCount, cache.getBlockCount());
5223     assertEquals(expectedBlockHits, cache.getStats().getHitCount());
5224     assertEquals(expectedBlockMiss, cache.getStats().getMissCount());
5225     // compact, net minus two blocks, two hits, no misses
5226     System.out.println("Compacting");
5227     assertEquals(2, store.getStorefilesCount());
5228     store.triggerMajorCompaction();
5229     region.compact(true);
5230     waitForStoreFileCount(store, 1, 10000); // wait 10 seconds max
5231     assertEquals(1, store.getStorefilesCount());
5232     expectedBlockCount -= 2; // evicted two blocks, cached none
5233     assertEquals(expectedBlockCount, cache.getBlockCount());
5234     expectedBlockHits += 2;
5235     assertEquals(expectedBlockMiss, cache.getStats().getMissCount());
5236     assertEquals(expectedBlockHits, cache.getStats().getHitCount());
5237     // read the row, this should be a cache miss because we don't cache data
5238     // blocks on compaction
5239     r = table.get(new Get(ROW));
5240     assertTrue(Bytes.equals(r.getValue(FAMILY, QUALIFIER), data));
5241     assertTrue(Bytes.equals(r.getValue(FAMILY, QUALIFIER2), data2));
5242     expectedBlockCount += 1; // cached one data block
5243     assertEquals(expectedBlockCount, cache.getBlockCount());
5244     assertEquals(expectedBlockHits, cache.getStats().getHitCount());
5245     assertEquals(++expectedBlockMiss, cache.getStats().getMissCount());
5246   }
5247 
5248   private void waitForStoreFileCount(Store store, int count, int timeout)
5249   throws InterruptedException {
5250     long start = System.currentTimeMillis();
5251     while (start + timeout > System.currentTimeMillis() &&
5252         store.getStorefilesCount() != count) {
5253       Thread.sleep(100);
5254     }
5255     System.out.println("start=" + start + ", now=" +
5256         System.currentTimeMillis() + ", cur=" + store.getStorefilesCount());
5257     assertEquals(count, store.getStorefilesCount());
5258   }
5259 
5260   @Test
5261   /**
5262    * Tests the non cached version of getRegionLocator by moving a region.
5263    */
5264   public void testNonCachedGetRegionLocation() throws Exception {
5265     // Test Initialization.
5266     TableName TABLE = TableName.valueOf("testNonCachedGetRegionLocation");
5267     byte [] family1 = Bytes.toBytes("f1");
5268     byte [] family2 = Bytes.toBytes("f2");
5269     try (HTable table = TEST_UTIL.createTable(TABLE, new byte[][] {family1, family2}, 10);
5270         Admin admin = new HBaseAdmin(TEST_UTIL.getConfiguration())) {
5271       Map <HRegionInfo, ServerName> regionsMap = table.getRegionLocations();
5272       assertEquals(1, regionsMap.size());
5273       HRegionInfo regionInfo = regionsMap.keySet().iterator().next();
5274       ServerName addrBefore = regionsMap.get(regionInfo);
5275       // Verify region location before move.
5276       HRegionLocation addrCache = table.getRegionLocation(regionInfo.getStartKey(), false);
5277       HRegionLocation addrNoCache = table.getRegionLocation(regionInfo.getStartKey(),  true);
5278 
5279       assertEquals(addrBefore.getPort(), addrCache.getPort());
5280       assertEquals(addrBefore.getPort(), addrNoCache.getPort());
5281 
5282       ServerName addrAfter = null;
5283       // Now move the region to a different server.
5284       for (int i = 0; i < SLAVES; i++) {
5285         HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(i);
5286         ServerName addr = regionServer.getServerName();
5287         if (addr.getPort() != addrBefore.getPort()) {
5288           admin.move(regionInfo.getEncodedNameAsBytes(),
5289               Bytes.toBytes(addr.toString()));
5290           // Wait for the region to move.
5291           Thread.sleep(5000);
5292           addrAfter = addr;
5293           break;
5294         }
5295       }
5296 
5297       // Verify the region was moved.
5298       addrCache = table.getRegionLocation(regionInfo.getStartKey(), false);
5299       addrNoCache = table.getRegionLocation(regionInfo.getStartKey(), true);
5300       assertNotNull(addrAfter);
5301       assertTrue(addrAfter.getPort() != addrCache.getPort());
5302       assertEquals(addrAfter.getPort(), addrNoCache.getPort());
5303     }
5304   }
5305 
5306   @Test
5307   /**
5308    * Tests getRegionsInRange by creating some regions over which a range of
5309    * keys spans; then changing the key range.
5310    */
5311   public void testGetRegionsInRange() throws Exception {
5312     // Test Initialization.
5313     byte [] startKey = Bytes.toBytes("ddc");
5314     byte [] endKey = Bytes.toBytes("mmm");
5315     TableName TABLE = TableName.valueOf("testGetRegionsInRange");
5316     HTable table = TEST_UTIL.createMultiRegionTable(TABLE, new byte[][] { FAMILY }, 10);
5317     int numOfRegions = -1;
5318     try (RegionLocator r = table.getRegionLocator()) {
5319       numOfRegions = r.getStartKeys().length;
5320     }
5321     assertEquals(26, numOfRegions);
5322 
5323     // Get the regions in this range
5324     List<HRegionLocation> regionsList = table.getRegionsInRange(startKey,
5325       endKey);
5326     assertEquals(10, regionsList.size());
5327 
5328     // Change the start key
5329     startKey = Bytes.toBytes("fff");
5330     regionsList = table.getRegionsInRange(startKey, endKey);
5331     assertEquals(7, regionsList.size());
5332 
5333     // Change the end key
5334     endKey = Bytes.toBytes("nnn");
5335     regionsList = table.getRegionsInRange(startKey, endKey);
5336     assertEquals(8, regionsList.size());
5337 
5338     // Empty start key
5339     regionsList = table.getRegionsInRange(HConstants.EMPTY_START_ROW, endKey);
5340     assertEquals(13, regionsList.size());
5341 
5342     // Empty end key
5343     regionsList = table.getRegionsInRange(startKey, HConstants.EMPTY_END_ROW);
5344     assertEquals(21, regionsList.size());
5345 
5346     // Both start and end keys empty
5347     regionsList = table.getRegionsInRange(HConstants.EMPTY_START_ROW,
5348       HConstants.EMPTY_END_ROW);
5349     assertEquals(26, regionsList.size());
5350 
5351     // Change the end key to somewhere in the last block
5352     endKey = Bytes.toBytes("zzz1");
5353     regionsList = table.getRegionsInRange(startKey, endKey);
5354     assertEquals(21, regionsList.size());
5355 
5356     // Change the start key to somewhere in the first block
5357     startKey = Bytes.toBytes("aac");
5358     regionsList = table.getRegionsInRange(startKey, endKey);
5359     assertEquals(26, regionsList.size());
5360 
5361     // Make start and end key the same
5362     startKey = endKey = Bytes.toBytes("ccc");
5363     regionsList = table.getRegionsInRange(startKey, endKey);
5364     assertEquals(1, regionsList.size());
5365   }
5366 
5367   @Test
5368   public void testJira6912() throws Exception {
5369     TableName TABLE = TableName.valueOf("testJira6912");
5370     Table foo = TEST_UTIL.createTable(TABLE, new byte[][] {FAMILY}, 10);
5371 
5372     List<Put> puts = new ArrayList<Put>();
5373     for (int i=0;i !=100; i++){
5374       Put put = new Put(Bytes.toBytes(i));
5375       put.add(FAMILY, FAMILY, Bytes.toBytes(i));
5376       puts.add(put);
5377     }
5378     foo.put(puts);
5379     // If i comment this out it works
5380     TEST_UTIL.flush();
5381 
5382     Scan scan = new Scan();
5383     scan.setStartRow(Bytes.toBytes(1));
5384     scan.setStopRow(Bytes.toBytes(3));
5385     scan.addColumn(FAMILY, FAMILY);
5386     scan.setFilter(new RowFilter(CompareFilter.CompareOp.NOT_EQUAL, new BinaryComparator(Bytes.toBytes(1))));
5387 
5388     ResultScanner scanner = foo.getScanner(scan);
5389     Result[] bar = scanner.next(100);
5390     assertEquals(1, bar.length);
5391   }
5392 
5393   @Test
5394   public void testScan_NullQualifier() throws IOException {
5395     Table table = TEST_UTIL.createTable(TableName.valueOf("testScan_NullQualifier"), FAMILY);
5396     Put put = new Put(ROW);
5397     put.add(FAMILY, QUALIFIER, VALUE);
5398     table.put(put);
5399 
5400     put = new Put(ROW);
5401     put.add(FAMILY, null, VALUE);
5402     table.put(put);
5403     LOG.info("Row put");
5404 
5405     Scan scan = new Scan();
5406     scan.addColumn(FAMILY, null);
5407 
5408     ResultScanner scanner = table.getScanner(scan);
5409     Result[] bar = scanner.next(100);
5410     assertEquals(1, bar.length);
5411     assertEquals(1, bar[0].size());
5412 
5413     scan = new Scan();
5414     scan.addFamily(FAMILY);
5415 
5416     scanner = table.getScanner(scan);
5417     bar = scanner.next(100);
5418     assertEquals(1, bar.length);
5419     assertEquals(2, bar[0].size());
5420   }
5421 
5422   @Test
5423   public void testNegativeTimestamp() throws IOException {
5424     Table table = TEST_UTIL.createTable(TableName.valueOf("testNegativeTimestamp"), FAMILY);
5425 
5426     try {
5427       Put put = new Put(ROW, -1);
5428       put.add(FAMILY, QUALIFIER, VALUE);
5429       table.put(put);
5430       fail("Negative timestamps should not have been allowed");
5431     } catch (IllegalArgumentException ex) {
5432       assertTrue(ex.getMessage().contains("negative"));
5433     }
5434 
5435     try {
5436       Put put = new Put(ROW);
5437       put.add(FAMILY, QUALIFIER, -1, VALUE);
5438       table.put(put);
5439       fail("Negative timestamps should not have been allowed");
5440     } catch (IllegalArgumentException ex) {
5441       assertTrue(ex.getMessage().contains("negative"));
5442     }
5443 
5444     try {
5445       Delete delete = new Delete(ROW, -1);
5446       table.delete(delete);
5447       fail("Negative timestamps should not have been allowed");
5448     } catch (IllegalArgumentException ex) {
5449       assertTrue(ex.getMessage().contains("negative"));
5450     }
5451 
5452     try {
5453       Delete delete = new Delete(ROW);
5454       delete.deleteFamily(FAMILY, -1);
5455       table.delete(delete);
5456       fail("Negative timestamps should not have been allowed");
5457     } catch (IllegalArgumentException ex) {
5458       assertTrue(ex.getMessage().contains("negative"));
5459     }
5460 
5461     try {
5462       Scan scan = new Scan();
5463       scan.setTimeRange(-1, 1);
5464       table.getScanner(scan);
5465       fail("Negative timestamps should not have been allowed");
5466     } catch (IllegalArgumentException ex) {
5467       assertTrue(ex.getMessage().contains("negative"));
5468     }
5469 
5470     // KeyValue should allow negative timestamps for backwards compat. Otherwise, if the user
5471     // already has negative timestamps in cluster data, HBase won't be able to handle that
5472     try {
5473       new KeyValue(Bytes.toBytes(42), Bytes.toBytes(42), Bytes.toBytes(42), -1, Bytes.toBytes(42));
5474     } catch (IllegalArgumentException ex) {
5475       fail("KeyValue SHOULD allow negative timestamps");
5476     }
5477 
5478     table.close();
5479   }
5480 
5481   @Test
5482   public void testIllegalTableDescriptor() throws Exception {
5483     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("testIllegalTableDescriptor"));
5484     HColumnDescriptor hcd = new HColumnDescriptor(FAMILY);
5485 
5486     // create table with 0 families
5487     checkTableIsIllegal(htd);
5488     htd.addFamily(hcd);
5489     checkTableIsLegal(htd);
5490 
5491     htd.setMaxFileSize(1024); // 1K
5492     checkTableIsIllegal(htd);
5493     htd.setMaxFileSize(0);
5494     checkTableIsIllegal(htd);
5495     htd.setMaxFileSize(1024 * 1024 * 1024); // 1G
5496     checkTableIsLegal(htd);
5497 
5498     htd.setMemStoreFlushSize(1024);
5499     checkTableIsIllegal(htd);
5500     htd.setMemStoreFlushSize(0);
5501     checkTableIsIllegal(htd);
5502     htd.setMemStoreFlushSize(128 * 1024 * 1024); // 128M
5503     checkTableIsLegal(htd);
5504 
5505     htd.setRegionSplitPolicyClassName("nonexisting.foo.class");
5506     checkTableIsIllegal(htd);
5507     htd.setRegionSplitPolicyClassName(null);
5508     checkTableIsLegal(htd);
5509 
5510     hcd.setBlocksize(0);
5511     checkTableIsIllegal(htd);
5512     hcd.setBlocksize(1024 * 1024 * 128); // 128M
5513     checkTableIsIllegal(htd);
5514     hcd.setBlocksize(1024);
5515     checkTableIsLegal(htd);
5516 
5517     hcd.setTimeToLive(0);
5518     checkTableIsIllegal(htd);
5519     hcd.setTimeToLive(-1);
5520     checkTableIsIllegal(htd);
5521     hcd.setTimeToLive(1);
5522     checkTableIsLegal(htd);
5523 
5524     hcd.setMinVersions(-1);
5525     checkTableIsIllegal(htd);
5526     hcd.setMinVersions(3);
5527     try {
5528       hcd.setMaxVersions(2);
5529       fail();
5530     } catch (IllegalArgumentException ex) {
5531       // expected
5532       hcd.setMaxVersions(10);
5533     }
5534     checkTableIsLegal(htd);
5535 
5536     hcd.setScope(-1);
5537     checkTableIsIllegal(htd);
5538     hcd.setScope(0);
5539     checkTableIsLegal(htd);
5540 
5541     // check the conf settings to disable sanity checks
5542     htd.setMemStoreFlushSize(0);
5543 
5544     // Check that logs warn on invalid table but allow it.
5545     ListAppender listAppender = new ListAppender();
5546     Logger log = Logger.getLogger(HMaster.class);
5547     log.addAppender(listAppender);
5548     log.setLevel(Level.WARN);
5549 
5550     htd.setConfiguration("hbase.table.sanity.checks", Boolean.FALSE.toString());
5551     checkTableIsLegal(htd);
5552 
5553     assertFalse(listAppender.getMessages().isEmpty());
5554     assertTrue(listAppender.getMessages().get(0).startsWith("MEMSTORE_FLUSHSIZE for table "
5555         + "descriptor or \"hbase.hregion.memstore.flush.size\" (0) is too small, which might "
5556         + "cause very frequent flushing."));
5557 
5558     log.removeAppender(listAppender);
5559   }
5560 
5561   private static class ListAppender extends AppenderSkeleton {
5562     private final List<String> messages = new ArrayList<String>();
5563 
5564     @Override
5565     protected void append(LoggingEvent event) {
5566       messages.add(event.getMessage().toString());
5567     }
5568 
5569     @Override
5570     public void close() {
5571     }
5572 
5573     @Override
5574     public boolean requiresLayout() {
5575       return false;
5576     }
5577 
5578     public List<String> getMessages() {
5579       return messages;
5580     }
5581   }
5582 
5583   private void checkTableIsLegal(HTableDescriptor htd) throws IOException {
5584     Admin admin = TEST_UTIL.getHBaseAdmin();
5585     admin.createTable(htd);
5586     assertTrue(admin.tableExists(htd.getTableName()));
5587     admin.disableTable(htd.getTableName());
5588     admin.deleteTable(htd.getTableName());
5589   }
5590 
5591   private void checkTableIsIllegal(HTableDescriptor htd) throws IOException {
5592     Admin admin = TEST_UTIL.getHBaseAdmin();
5593     try {
5594       admin.createTable(htd);
5595       fail();
5596     } catch(Exception ex) {
5597       // should throw ex
5598     }
5599     assertFalse(admin.tableExists(htd.getTableName()));
5600   }
5601 
5602   @Test
5603   public void testRawScanRespectsVersions() throws Exception {
5604     TableName TABLE = TableName.valueOf("testRawScan");
5605     Table table = TEST_UTIL.createTable(TABLE, FAMILY);
5606     byte[] row = Bytes.toBytes("row");
5607 
5608     // put the same row 4 times, with different values
5609     Put p = new Put(row);
5610     p.add(FAMILY, QUALIFIER, 10, VALUE);
5611     table.put(p);
5612     p = new Put(row);
5613     p.add(FAMILY, QUALIFIER, 11, ArrayUtils.add(VALUE, (byte) 2));
5614     table.put(p);
5615 
5616     p = new Put(row);
5617     p.add(FAMILY, QUALIFIER, 12, ArrayUtils.add(VALUE, (byte) 3));
5618     table.put(p);
5619 
5620     p = new Put(row);
5621     p.add(FAMILY, QUALIFIER, 13, ArrayUtils.add(VALUE, (byte) 4));
5622     table.put(p);
5623 
5624     int versions = 4;
5625     Scan s = new Scan(row);
5626     // get all the possible versions
5627     s.setMaxVersions();
5628     s.setRaw(true);
5629 
5630     ResultScanner scanner = table.getScanner(s);
5631     int count = 0;
5632     for (Result r : scanner) {
5633       assertEquals("Found an unexpected number of results for the row!", versions, r.listCells().size());
5634       count++;
5635     }
5636     assertEquals("Found more than a single row when raw scanning the table with a single row!", 1,
5637       count);
5638     scanner.close();
5639 
5640     // then if we decrease the number of versions, but keep the scan raw, we should see exactly that
5641     // number of versions
5642     versions = 2;
5643     s.setMaxVersions(versions);
5644     scanner = table.getScanner(s);
5645     count = 0;
5646     for (Result r : scanner) {
5647       assertEquals("Found an unexpected number of results for the row!", versions, r.listCells().size());
5648       count++;
5649     }
5650     assertEquals("Found more than a single row when raw scanning the table with a single row!", 1,
5651       count);
5652     scanner.close();
5653 
5654     // finally, if we turn off raw scanning, but max out the number of versions, we should go back
5655     // to seeing just three
5656     versions = 3;
5657     s.setMaxVersions(versions);
5658     scanner = table.getScanner(s);
5659     count = 0;
5660     for (Result r : scanner) {
5661       assertEquals("Found an unexpected number of results for the row!", versions, r.listCells().size());
5662       count++;
5663     }
5664     assertEquals("Found more than a single row when raw scanning the table with a single row!", 1,
5665       count);
5666     scanner.close();
5667 
5668     table.close();
5669     TEST_UTIL.deleteTable(TABLE);
5670   }
5671 
5672   @Test
5673   public void testSmallScan() throws Exception {
5674     // Test Initialization.
5675     TableName TABLE = TableName.valueOf("testSmallScan");
5676     Table table = TEST_UTIL.createTable(TABLE, FAMILY);
5677 
5678     // Insert one row each region
5679     int insertNum = 10;
5680     for (int i = 0; i < 10; i++) {
5681       Put put = new Put(Bytes.toBytes("row" + String.format("%03d", i)));
5682       put.add(FAMILY, QUALIFIER, VALUE);
5683       table.put(put);
5684     }
5685 
5686     // nomal scan
5687     ResultScanner scanner = table.getScanner(new Scan());
5688     int count = 0;
5689     for (Result r : scanner) {
5690       assertTrue(!r.isEmpty());
5691       count++;
5692     }
5693     assertEquals(insertNum, count);
5694 
5695     // small scan
5696     Scan scan = new Scan(HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
5697     scan.setSmall(true);
5698     scan.setCaching(2);
5699     scanner = table.getScanner(scan);
5700     count = 0;
5701     for (Result r : scanner) {
5702       assertTrue(!r.isEmpty());
5703       count++;
5704     }
5705     assertEquals(insertNum, count);
5706 
5707   }
5708 
5709   @Test
5710   public void testSuperSimpleWithReverseScan() throws Exception {
5711     TableName TABLE = TableName.valueOf("testSuperSimpleWithReverseScan");
5712     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
5713     Put put = new Put(Bytes.toBytes("0-b11111-0000000000000000000"));
5714     put.add(FAMILY, QUALIFIER, VALUE);
5715     ht.put(put);
5716     put = new Put(Bytes.toBytes("0-b11111-0000000000000000002"));
5717     put.add(FAMILY, QUALIFIER, VALUE);
5718     ht.put(put);
5719     put = new Put(Bytes.toBytes("0-b11111-0000000000000000004"));
5720     put.add(FAMILY, QUALIFIER, VALUE);
5721     ht.put(put);
5722     put = new Put(Bytes.toBytes("0-b11111-0000000000000000006"));
5723     put.add(FAMILY, QUALIFIER, VALUE);
5724     ht.put(put);
5725     put = new Put(Bytes.toBytes("0-b11111-0000000000000000008"));
5726     put.add(FAMILY, QUALIFIER, VALUE);
5727     ht.put(put);
5728     put = new Put(Bytes.toBytes("0-b22222-0000000000000000001"));
5729     put.add(FAMILY, QUALIFIER, VALUE);
5730     ht.put(put);
5731     put = new Put(Bytes.toBytes("0-b22222-0000000000000000003"));
5732     put.add(FAMILY, QUALIFIER, VALUE);
5733     ht.put(put);
5734     put = new Put(Bytes.toBytes("0-b22222-0000000000000000005"));
5735     put.add(FAMILY, QUALIFIER, VALUE);
5736     ht.put(put);
5737     put = new Put(Bytes.toBytes("0-b22222-0000000000000000007"));
5738     put.add(FAMILY, QUALIFIER, VALUE);
5739     ht.put(put);
5740     put = new Put(Bytes.toBytes("0-b22222-0000000000000000009"));
5741     put.add(FAMILY, QUALIFIER, VALUE);
5742     ht.put(put);
5743     Scan scan = new Scan(Bytes.toBytes("0-b11111-9223372036854775807"),
5744         Bytes.toBytes("0-b11111-0000000000000000000"));
5745     scan.setReversed(true);
5746     ResultScanner scanner = ht.getScanner(scan);
5747     Result result = scanner.next();
5748     assertTrue(Bytes.equals(result.getRow(),
5749         Bytes.toBytes("0-b11111-0000000000000000008")));
5750     scanner.close();
5751     ht.close();
5752   }
5753 
5754   @Test
5755   public void testFiltersWithReverseScan() throws Exception {
5756     TableName TABLE = TableName.valueOf("testFiltersWithReverseScan");
5757     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
5758     byte[][] ROWS = makeN(ROW, 10);
5759     byte[][] QUALIFIERS = { Bytes.toBytes("col0-<d2v1>-<d3v2>"),
5760         Bytes.toBytes("col1-<d2v1>-<d3v2>"),
5761         Bytes.toBytes("col2-<d2v1>-<d3v2>"),
5762         Bytes.toBytes("col3-<d2v1>-<d3v2>"),
5763         Bytes.toBytes("col4-<d2v1>-<d3v2>"),
5764         Bytes.toBytes("col5-<d2v1>-<d3v2>"),
5765         Bytes.toBytes("col6-<d2v1>-<d3v2>"),
5766         Bytes.toBytes("col7-<d2v1>-<d3v2>"),
5767         Bytes.toBytes("col8-<d2v1>-<d3v2>"),
5768         Bytes.toBytes("col9-<d2v1>-<d3v2>") };
5769     for (int i = 0; i < 10; i++) {
5770       Put put = new Put(ROWS[i]);
5771       put.add(FAMILY, QUALIFIERS[i], VALUE);
5772       ht.put(put);
5773     }
5774     Scan scan = new Scan();
5775     scan.setReversed(true);
5776     scan.addFamily(FAMILY);
5777     Filter filter = new QualifierFilter(CompareOp.EQUAL,
5778         new RegexStringComparator("col[1-5]"));
5779     scan.setFilter(filter);
5780     ResultScanner scanner = ht.getScanner(scan);
5781     int expectedIndex = 5;
5782     for (Result result : scanner) {
5783       assertEquals(result.size(), 1);
5784       assertTrue(Bytes.equals(result.raw()[0].getRow(), ROWS[expectedIndex]));
5785       assertTrue(Bytes.equals(result.raw()[0].getQualifier(),
5786           QUALIFIERS[expectedIndex]));
5787       expectedIndex--;
5788     }
5789     assertEquals(expectedIndex, 0);
5790     scanner.close();
5791     ht.close();
5792   }
5793 
5794   @Test
5795   public void testKeyOnlyFilterWithReverseScan() throws Exception {
5796     TableName TABLE = TableName.valueOf("testKeyOnlyFilterWithReverseScan");
5797     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
5798     byte[][] ROWS = makeN(ROW, 10);
5799     byte[][] QUALIFIERS = { Bytes.toBytes("col0-<d2v1>-<d3v2>"),
5800         Bytes.toBytes("col1-<d2v1>-<d3v2>"),
5801         Bytes.toBytes("col2-<d2v1>-<d3v2>"),
5802         Bytes.toBytes("col3-<d2v1>-<d3v2>"),
5803         Bytes.toBytes("col4-<d2v1>-<d3v2>"),
5804         Bytes.toBytes("col5-<d2v1>-<d3v2>"),
5805         Bytes.toBytes("col6-<d2v1>-<d3v2>"),
5806         Bytes.toBytes("col7-<d2v1>-<d3v2>"),
5807         Bytes.toBytes("col8-<d2v1>-<d3v2>"),
5808         Bytes.toBytes("col9-<d2v1>-<d3v2>") };
5809     for (int i = 0; i < 10; i++) {
5810       Put put = new Put(ROWS[i]);
5811       put.add(FAMILY, QUALIFIERS[i], VALUE);
5812       ht.put(put);
5813     }
5814     Scan scan = new Scan();
5815     scan.setReversed(true);
5816     scan.addFamily(FAMILY);
5817     Filter filter = new KeyOnlyFilter(true);
5818     scan.setFilter(filter);
5819     ResultScanner scanner = ht.getScanner(scan);
5820     int count = 0;
5821     for (Result result : ht.getScanner(scan)) {
5822       assertEquals(result.size(), 1);
5823       assertEquals(result.raw()[0].getValueLength(), Bytes.SIZEOF_INT);
5824       assertEquals(Bytes.toInt(result.raw()[0].getValue()), VALUE.length);
5825       count++;
5826     }
5827     assertEquals(count, 10);
5828     scanner.close();
5829     ht.close();
5830   }
5831 
5832   /**
5833    * Test simple table and non-existent row cases.
5834    */
5835   @Test
5836   public void testSimpleMissingWithReverseScan() throws Exception {
5837     TableName TABLE = TableName.valueOf("testSimpleMissingWithReverseScan");
5838     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
5839     byte[][] ROWS = makeN(ROW, 4);
5840 
5841     // Try to get a row on an empty table
5842     Scan scan = new Scan();
5843     scan.setReversed(true);
5844     Result result = getSingleScanResult(ht, scan);
5845     assertNullResult(result);
5846 
5847     scan = new Scan(ROWS[0]);
5848     scan.setReversed(true);
5849     result = getSingleScanResult(ht, scan);
5850     assertNullResult(result);
5851 
5852     scan = new Scan(ROWS[0], ROWS[1]);
5853     scan.setReversed(true);
5854     result = getSingleScanResult(ht, scan);
5855     assertNullResult(result);
5856 
5857     scan = new Scan();
5858     scan.setReversed(true);
5859     scan.addFamily(FAMILY);
5860     result = getSingleScanResult(ht, scan);
5861     assertNullResult(result);
5862 
5863     scan = new Scan();
5864     scan.setReversed(true);
5865     scan.addColumn(FAMILY, QUALIFIER);
5866     result = getSingleScanResult(ht, scan);
5867     assertNullResult(result);
5868 
5869     // Insert a row
5870 
5871     Put put = new Put(ROWS[2]);
5872     put.add(FAMILY, QUALIFIER, VALUE);
5873     ht.put(put);
5874 
5875     // Make sure we can scan the row
5876     scan = new Scan();
5877     scan.setReversed(true);
5878     result = getSingleScanResult(ht, scan);
5879     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
5880 
5881     scan = new Scan(ROWS[3], ROWS[0]);
5882     scan.setReversed(true);
5883     result = getSingleScanResult(ht, scan);
5884     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
5885 
5886     scan = new Scan(ROWS[2], ROWS[1]);
5887     scan.setReversed(true);
5888     result = getSingleScanResult(ht, scan);
5889     assertSingleResult(result, ROWS[2], FAMILY, QUALIFIER, VALUE);
5890 
5891     // Try to scan empty rows around it
5892     // Introduced MemStore#shouldSeekForReverseScan to fix the following
5893     scan = new Scan(ROWS[1]);
5894     scan.setReversed(true);
5895     result = getSingleScanResult(ht, scan);
5896     assertNullResult(result);
5897     ht.close();
5898   }
5899 
5900   @Test
5901   public void testNullWithReverseScan() throws Exception {
5902     TableName TABLE = TableName.valueOf("testNullWithReverseScan");
5903     Table ht = TEST_UTIL.createTable(TABLE, FAMILY);
5904     // Null qualifier (should work)
5905     Put put = new Put(ROW);
5906     put.add(FAMILY, null, VALUE);
5907     ht.put(put);
5908     scanTestNull(ht, ROW, FAMILY, VALUE, true);
5909     Delete delete = new Delete(ROW);
5910     delete.deleteColumns(FAMILY, null);
5911     ht.delete(delete);
5912     // Use a new table
5913     byte[] TABLE2 = Bytes.toBytes("testNull2WithReverseScan");
5914     ht = TEST_UTIL.createTable(TableName.valueOf(TABLE2), FAMILY);
5915     // Empty qualifier, byte[0] instead of null (should work)
5916     put = new Put(ROW);
5917     put.add(FAMILY, HConstants.EMPTY_BYTE_ARRAY, VALUE);
5918     ht.put(put);
5919     scanTestNull(ht, ROW, FAMILY, VALUE, true);
5920     TEST_UTIL.flush();
5921     scanTestNull(ht, ROW, FAMILY, VALUE, true);
5922     delete = new Delete(ROW);
5923     delete.deleteColumns(FAMILY, HConstants.EMPTY_BYTE_ARRAY);
5924     ht.delete(delete);
5925     // Null value
5926     put = new Put(ROW);
5927     put.add(FAMILY, QUALIFIER, null);
5928     ht.put(put);
5929     Scan scan = new Scan();
5930     scan.setReversed(true);
5931     scan.addColumn(FAMILY, QUALIFIER);
5932     Result result = getSingleScanResult(ht, scan);
5933     assertSingleResult(result, ROW, FAMILY, QUALIFIER, null);
5934     ht.close();
5935   }
5936 
5937   @Test
5938   public void testDeletesWithReverseScan() throws Exception {
5939     TableName TABLE = TableName.valueOf("testDeletesWithReverseScan");
5940     byte[][] ROWS = makeNAscii(ROW, 6);
5941     byte[][] FAMILIES = makeNAscii(FAMILY, 3);
5942     byte[][] VALUES = makeN(VALUE, 5);
5943     long[] ts = { 1000, 2000, 3000, 4000, 5000 };
5944     Table ht = TEST_UTIL.createTable(TABLE, FAMILIES, TEST_UTIL.getConfiguration(), 3);
5945 
5946     Put put = new Put(ROW);
5947     put.add(FAMILIES[0], QUALIFIER, ts[0], VALUES[0]);
5948     put.add(FAMILIES[0], QUALIFIER, ts[1], VALUES[1]);
5949     ht.put(put);
5950 
5951     Delete delete = new Delete(ROW);
5952     delete.deleteFamily(FAMILIES[0], ts[0]);
5953     ht.delete(delete);
5954 
5955     Scan scan = new Scan(ROW);
5956     scan.setReversed(true);
5957     scan.addFamily(FAMILIES[0]);
5958     scan.setMaxVersions(Integer.MAX_VALUE);
5959     Result result = getSingleScanResult(ht, scan);
5960     assertNResult(result, ROW, FAMILIES[0], QUALIFIER, new long[] { ts[1] },
5961         new byte[][] { VALUES[1] }, 0, 0);
5962 
5963     // Test delete latest version
5964     put = new Put(ROW);
5965     put.add(FAMILIES[0], QUALIFIER, ts[4], VALUES[4]);
5966     put.add(FAMILIES[0], QUALIFIER, ts[2], VALUES[2]);
5967     put.add(FAMILIES[0], QUALIFIER, ts[3], VALUES[3]);
5968     put.add(FAMILIES[0], null, ts[4], VALUES[4]);
5969     put.add(FAMILIES[0], null, ts[2], VALUES[2]);
5970     put.add(FAMILIES[0], null, ts[3], VALUES[3]);
5971     ht.put(put);
5972 
5973     delete = new Delete(ROW);
5974     delete.deleteColumn(FAMILIES[0], QUALIFIER); // ts[4]
5975     ht.delete(delete);
5976 
5977     scan = new Scan(ROW);
5978     scan.setReversed(true);
5979     scan.addColumn(FAMILIES[0], QUALIFIER);
5980     scan.setMaxVersions(Integer.MAX_VALUE);
5981     result = getSingleScanResult(ht, scan);
5982     assertNResult(result, ROW, FAMILIES[0], QUALIFIER, new long[] { ts[1],
5983         ts[2], ts[3] }, new byte[][] { VALUES[1], VALUES[2], VALUES[3] }, 0, 2);
5984 
5985     // Test for HBASE-1847
5986     delete = new Delete(ROW);
5987     delete.deleteColumn(FAMILIES[0], null);
5988     ht.delete(delete);
5989 
5990     // Cleanup null qualifier
5991     delete = new Delete(ROW);
5992     delete.deleteColumns(FAMILIES[0], null);
5993     ht.delete(delete);
5994 
5995     // Expected client behavior might be that you can re-put deleted values
5996     // But alas, this is not to be. We can't put them back in either case.
5997 
5998     put = new Put(ROW);
5999     put.add(FAMILIES[0], QUALIFIER, ts[0], VALUES[0]); // 1000
6000     put.add(FAMILIES[0], QUALIFIER, ts[4], VALUES[4]); // 5000
6001     ht.put(put);
6002 
6003     // The Scanner returns the previous values, the expected-naive-unexpected
6004     // behavior
6005 
6006     scan = new Scan(ROW);
6007     scan.setReversed(true);
6008     scan.addFamily(FAMILIES[0]);
6009     scan.setMaxVersions(Integer.MAX_VALUE);
6010     result = getSingleScanResult(ht, scan);
6011     assertNResult(result, ROW, FAMILIES[0], QUALIFIER, new long[] { ts[1],
6012         ts[2], ts[3] }, new byte[][] { VALUES[1], VALUES[2], VALUES[3] }, 0, 2);
6013 
6014     // Test deleting an entire family from one row but not the other various
6015     // ways
6016 
6017     put = new Put(ROWS[0]);
6018     put.add(FAMILIES[1], QUALIFIER, ts[0], VALUES[0]);
6019     put.add(FAMILIES[1], QUALIFIER, ts[1], VALUES[1]);
6020     put.add(FAMILIES[2], QUALIFIER, ts[2], VALUES[2]);
6021     put.add(FAMILIES[2], QUALIFIER, ts[3], VALUES[3]);
6022     ht.put(put);
6023 
6024     put = new Put(ROWS[1]);
6025     put.add(FAMILIES[1], QUALIFIER, ts[0], VALUES[0]);
6026     put.add(FAMILIES[1], QUALIFIER, ts[1], VALUES[1]);
6027     put.add(FAMILIES[2], QUALIFIER, ts[2], VALUES[2]);
6028     put.add(FAMILIES[2], QUALIFIER, ts[3], VALUES[3]);
6029     ht.put(put);
6030 
6031     put = new Put(ROWS[2]);
6032     put.add(FAMILIES[1], QUALIFIER, ts[0], VALUES[0]);
6033     put.add(FAMILIES[1], QUALIFIER, ts[1], VALUES[1]);
6034     put.add(FAMILIES[2], QUALIFIER, ts[2], VALUES[2]);
6035     put.add(FAMILIES[2], QUALIFIER, ts[3], VALUES[3]);
6036     ht.put(put);
6037 
6038     delete = new Delete(ROWS[0]);
6039     delete.deleteFamily(FAMILIES[2]);
6040     ht.delete(delete);
6041 
6042     delete = new Delete(ROWS[1]);
6043     delete.deleteColumns(FAMILIES[1], QUALIFIER);
6044     ht.delete(delete);
6045 
6046     delete = new Delete(ROWS[2]);
6047     delete.deleteColumn(FAMILIES[1], QUALIFIER);
6048     delete.deleteColumn(FAMILIES[1], QUALIFIER);
6049     delete.deleteColumn(FAMILIES[2], QUALIFIER);
6050     ht.delete(delete);
6051 
6052     scan = new Scan(ROWS[0]);
6053     scan.setReversed(true);
6054     scan.addFamily(FAMILIES[1]);
6055     scan.addFamily(FAMILIES[2]);
6056     scan.setMaxVersions(Integer.MAX_VALUE);
6057     result = getSingleScanResult(ht, scan);
6058     assertTrue("Expected 2 keys but received " + result.size(),
6059         result.size() == 2);
6060     assertNResult(result, ROWS[0], FAMILIES[1], QUALIFIER, new long[] { ts[0],
6061         ts[1] }, new byte[][] { VALUES[0], VALUES[1] }, 0, 1);
6062 
6063     scan = new Scan(ROWS[1]);
6064     scan.setReversed(true);
6065     scan.addFamily(FAMILIES[1]);
6066     scan.addFamily(FAMILIES[2]);
6067     scan.setMaxVersions(Integer.MAX_VALUE);
6068     result = getSingleScanResult(ht, scan);
6069     assertTrue("Expected 2 keys but received " + result.size(),
6070         result.size() == 2);
6071 
6072     scan = new Scan(ROWS[2]);
6073     scan.setReversed(true);
6074     scan.addFamily(FAMILIES[1]);
6075     scan.addFamily(FAMILIES[2]);
6076     scan.setMaxVersions(Integer.MAX_VALUE);
6077     result = getSingleScanResult(ht, scan);
6078     assertEquals(1, result.size());
6079     assertNResult(result, ROWS[2], FAMILIES[2], QUALIFIER,
6080         new long[] { ts[2] }, new byte[][] { VALUES[2] }, 0, 0);
6081 
6082     // Test if we delete the family first in one row (HBASE-1541)
6083 
6084     delete = new Delete(ROWS[3]);
6085     delete.deleteFamily(FAMILIES[1]);
6086     ht.delete(delete);
6087 
6088     put = new Put(ROWS[3]);
6089     put.add(FAMILIES[2], QUALIFIER, VALUES[0]);
6090     ht.put(put);
6091 
6092     put = new Put(ROWS[4]);
6093     put.add(FAMILIES[1], QUALIFIER, VALUES[1]);
6094     put.add(FAMILIES[2], QUALIFIER, VALUES[2]);
6095     ht.put(put);
6096 
6097     scan = new Scan(ROWS[4]);
6098     scan.setReversed(true);
6099     scan.addFamily(FAMILIES[1]);
6100     scan.addFamily(FAMILIES[2]);
6101     scan.setMaxVersions(Integer.MAX_VALUE);
6102     ResultScanner scanner = ht.getScanner(scan);
6103     result = scanner.next();
6104     assertTrue("Expected 2 keys but received " + result.size(),
6105         result.size() == 2);
6106     assertTrue(Bytes.equals(result.raw()[0].getRow(), ROWS[4]));
6107     assertTrue(Bytes.equals(result.raw()[1].getRow(), ROWS[4]));
6108     assertTrue(Bytes.equals(result.raw()[0].getValue(), VALUES[1]));
6109     assertTrue(Bytes.equals(result.raw()[1].getValue(), VALUES[2]));
6110     result = scanner.next();
6111     assertTrue("Expected 1 key but received " + result.size(),
6112         result.size() == 1);
6113     assertTrue(Bytes.equals(result.raw()[0].getRow(), ROWS[3]));
6114     assertTrue(Bytes.equals(result.raw()[0].getValue(), VALUES[0]));
6115     scanner.close();
6116     ht.close();
6117   }
6118 
6119   /**
6120    * Tests reversed scan under multi regions
6121    */
6122   @Test
6123   public void testReversedScanUnderMultiRegions() throws Exception {
6124     // Test Initialization.
6125     TableName TABLE = TableName.valueOf("testReversedScanUnderMultiRegions");
6126     byte[] maxByteArray = ReversedClientScanner.MAX_BYTE_ARRAY;
6127     byte[][] splitRows = new byte[][] { Bytes.toBytes("005"),
6128         Bytes.add(Bytes.toBytes("005"), Bytes.multiple(maxByteArray, 16)),
6129         Bytes.toBytes("006"),
6130         Bytes.add(Bytes.toBytes("006"), Bytes.multiple(maxByteArray, 8)),
6131         Bytes.toBytes("007"),
6132         Bytes.add(Bytes.toBytes("007"), Bytes.multiple(maxByteArray, 4)),
6133         Bytes.toBytes("008"), Bytes.multiple(maxByteArray, 2) };
6134     HTable table = TEST_UTIL.createTable(TABLE, FAMILY, splitRows);
6135     TEST_UTIL.waitUntilAllRegionsAssigned(table.getName());
6136 
6137     assertEquals(splitRows.length + 1, table.getRegionLocations().size());
6138     // Insert one row each region
6139     int insertNum = splitRows.length;
6140     for (int i = 0; i < insertNum; i++) {
6141       Put put = new Put(splitRows[i]);
6142       put.add(FAMILY, QUALIFIER, VALUE);
6143       table.put(put);
6144     }
6145 
6146     // scan forward
6147     ResultScanner scanner = table.getScanner(new Scan());
6148     int count = 0;
6149     for (Result r : scanner) {
6150       assertTrue(!r.isEmpty());
6151       count++;
6152     }
6153     assertEquals(insertNum, count);
6154 
6155     // scan backward
6156     Scan scan = new Scan();
6157     scan.setReversed(true);
6158     scanner = table.getScanner(scan);
6159     count = 0;
6160     byte[] lastRow = null;
6161     for (Result r : scanner) {
6162       assertTrue(!r.isEmpty());
6163       count++;
6164       byte[] thisRow = r.getRow();
6165       if (lastRow != null) {
6166         assertTrue("Error scan order, last row= " + Bytes.toString(lastRow)
6167             + ",this row=" + Bytes.toString(thisRow),
6168             Bytes.compareTo(thisRow, lastRow) < 0);
6169       }
6170       lastRow = thisRow;
6171     }
6172     assertEquals(insertNum, count);
6173     table.close();
6174   }
6175 
6176   /**
6177    * Tests reversed scan under multi regions
6178    */
6179   @Test
6180   public void testSmallReversedScanUnderMultiRegions() throws Exception {
6181     // Test Initialization.
6182     TableName TABLE = TableName.valueOf("testSmallReversedScanUnderMultiRegions");
6183     byte[][] splitRows = new byte[][]{
6184         Bytes.toBytes("000"), Bytes.toBytes("002"), Bytes.toBytes("004"),
6185         Bytes.toBytes("006"), Bytes.toBytes("008"), Bytes.toBytes("010")};
6186     HTable table = TEST_UTIL.createTable(TABLE, FAMILY, splitRows);
6187     TEST_UTIL.waitUntilAllRegionsAssigned(table.getName());
6188 
6189     assertEquals(splitRows.length + 1, table.getRegionLocations().size());
6190     for (byte[] splitRow : splitRows) {
6191       Put put = new Put(splitRow);
6192       put.add(FAMILY, QUALIFIER, VALUE);
6193       table.put(put);
6194 
6195       byte[] nextRow = Bytes.copy(splitRow);
6196       nextRow[nextRow.length - 1]++;
6197 
6198       put = new Put(nextRow);
6199       put.add(FAMILY, QUALIFIER, VALUE);
6200       table.put(put);
6201     }
6202 
6203     // scan forward
6204     ResultScanner scanner = table.getScanner(new Scan());
6205     int count = 0;
6206     for (Result r : scanner) {
6207       assertTrue(!r.isEmpty());
6208       count++;
6209     }
6210     assertEquals(12, count);
6211 
6212     reverseScanTest(table, false);
6213     reverseScanTest(table, true);
6214 
6215     table.close();
6216   }
6217 
6218   private void reverseScanTest(Table table, boolean small) throws IOException {
6219     // scan backward
6220     Scan scan = new Scan();
6221     scan.setReversed(true);
6222     ResultScanner scanner = table.getScanner(scan);
6223     int count = 0;
6224     byte[] lastRow = null;
6225     for (Result r : scanner) {
6226       assertTrue(!r.isEmpty());
6227       count++;
6228       byte[] thisRow = r.getRow();
6229       if (lastRow != null) {
6230         assertTrue("Error scan order, last row= " + Bytes.toString(lastRow)
6231             + ",this row=" + Bytes.toString(thisRow),
6232             Bytes.compareTo(thisRow, lastRow) < 0);
6233       }
6234       lastRow = thisRow;
6235     }
6236     assertEquals(12, count);
6237 
6238     scan = new Scan();
6239     scan.setSmall(small);
6240     scan.setReversed(true);
6241     scan.setStartRow(Bytes.toBytes("002"));
6242     scanner = table.getScanner(scan);
6243     count = 0;
6244     lastRow = null;
6245     for (Result r : scanner) {
6246       assertTrue(!r.isEmpty());
6247       count++;
6248       byte[] thisRow = r.getRow();
6249       if (lastRow != null) {
6250         assertTrue("Error scan order, last row= " + Bytes.toString(lastRow)
6251             + ",this row=" + Bytes.toString(thisRow),
6252             Bytes.compareTo(thisRow, lastRow) < 0);
6253       }
6254       lastRow = thisRow;
6255     }
6256     assertEquals(3, count); // 000 001 002
6257 
6258     scan = new Scan();
6259     scan.setSmall(small);
6260     scan.setReversed(true);
6261     scan.setStartRow(Bytes.toBytes("002"));
6262     scan.setStopRow(Bytes.toBytes("000"));
6263     scanner = table.getScanner(scan);
6264     count = 0;
6265     lastRow = null;
6266     for (Result r : scanner) {
6267       assertTrue(!r.isEmpty());
6268       count++;
6269       byte[] thisRow = r.getRow();
6270       if (lastRow != null) {
6271         assertTrue("Error scan order, last row= " + Bytes.toString(lastRow)
6272             + ",this row=" + Bytes.toString(thisRow),
6273             Bytes.compareTo(thisRow, lastRow) < 0);
6274       }
6275       lastRow = thisRow;
6276     }
6277     assertEquals(2, count); // 001 002
6278 
6279     scan = new Scan();
6280     scan.setSmall(small);
6281     scan.setReversed(true);
6282     scan.setStartRow(Bytes.toBytes("001"));
6283     scanner = table.getScanner(scan);
6284     count = 0;
6285     lastRow = null;
6286     for (Result r : scanner) {
6287       assertTrue(!r.isEmpty());
6288       count++;
6289       byte[] thisRow = r.getRow();
6290       if (lastRow != null) {
6291         assertTrue("Error scan order, last row= " + Bytes.toString(lastRow)
6292             + ",this row=" + Bytes.toString(thisRow),
6293             Bytes.compareTo(thisRow, lastRow) < 0);
6294       }
6295       lastRow = thisRow;
6296     }
6297     assertEquals(2, count); // 000 001
6298 
6299     scan = new Scan();
6300     scan.setSmall(small);
6301     scan.setReversed(true);
6302     scan.setStartRow(Bytes.toBytes("000"));
6303     scanner = table.getScanner(scan);
6304     count = 0;
6305     lastRow = null;
6306     for (Result r : scanner) {
6307       assertTrue(!r.isEmpty());
6308       count++;
6309       byte[] thisRow = r.getRow();
6310       if (lastRow != null) {
6311         assertTrue("Error scan order, last row= " + Bytes.toString(lastRow)
6312             + ",this row=" + Bytes.toString(thisRow),
6313             Bytes.compareTo(thisRow, lastRow) < 0);
6314       }
6315       lastRow = thisRow;
6316     }
6317     assertEquals(1, count); // 000
6318 
6319     scan = new Scan();
6320     scan.setSmall(small);
6321     scan.setReversed(true);
6322     scan.setStartRow(Bytes.toBytes("006"));
6323     scan.setStopRow(Bytes.toBytes("002"));
6324     scanner = table.getScanner(scan);
6325     count = 0;
6326     lastRow = null;
6327     for (Result r : scanner) {
6328       assertTrue(!r.isEmpty());
6329       count++;
6330       byte[] thisRow = r.getRow();
6331       if (lastRow != null) {
6332         assertTrue("Error scan order, last row= " + Bytes.toString(lastRow)
6333             + ",this row=" + Bytes.toString(thisRow),
6334             Bytes.compareTo(thisRow, lastRow) < 0);
6335       }
6336       lastRow = thisRow;
6337     }
6338     assertEquals(4, count); // 003 004 005 006
6339   }
6340 
6341   @Test
6342   public void testGetStartEndKeysWithRegionReplicas() throws IOException {
6343     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("testGetStartEndKeys"));
6344     HColumnDescriptor fam = new HColumnDescriptor(FAMILY);
6345     htd.addFamily(fam);
6346     byte[][] KEYS = HBaseTestingUtility.KEYS_FOR_HBA_CREATE_TABLE;
6347     HBaseAdmin admin = TEST_UTIL.getHBaseAdmin();
6348     admin.createTable(htd, KEYS);
6349     List<HRegionInfo> regions = admin.getTableRegions(htd.getTableName());
6350 
6351     HRegionLocator locator =
6352         (HRegionLocator) admin.getConnection().getRegionLocator(htd.getTableName());
6353     for (int regionReplication = 1; regionReplication < 4; regionReplication++) {
6354       List<RegionLocations> regionLocations = new ArrayList<RegionLocations>();
6355 
6356       // mock region locations coming from meta with multiple replicas
6357       for (HRegionInfo region : regions) {
6358         HRegionLocation[] arr = new HRegionLocation[regionReplication];
6359         for (int i = 0; i < arr.length; i++) {
6360           arr[i] = new HRegionLocation(RegionReplicaUtil.getRegionInfoForReplica(region, i), null);
6361         }
6362         regionLocations.add(new RegionLocations(arr));
6363       }
6364 
6365       Pair<byte[][], byte[][]> startEndKeys = locator.getStartEndKeys(regionLocations);
6366 
6367       assertEquals(KEYS.length + 1, startEndKeys.getFirst().length);
6368 
6369       for (int i = 0; i < KEYS.length + 1; i++) {
6370         byte[] startKey = i == 0 ? HConstants.EMPTY_START_ROW : KEYS[i - 1];
6371         byte[] endKey = i == KEYS.length ? HConstants.EMPTY_END_ROW : KEYS[i];
6372         assertArrayEquals(startKey, startEndKeys.getFirst()[i]);
6373         assertArrayEquals(endKey, startEndKeys.getSecond()[i]);
6374       }
6375     }
6376   }
6377 }