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