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