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