1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.client;
20
21 import org.apache.hadoop.hbase.HBaseTestingUtility;
22 import org.apache.hadoop.hbase.MediumTests;
23 import org.apache.hadoop.hbase.TableName;
24 import org.apache.hadoop.hbase.filter.CompareFilter;
25 import org.apache.hadoop.hbase.util.Bytes;
26 import org.junit.AfterClass;
27 import org.junit.BeforeClass;
28 import org.junit.Test;
29 import org.junit.experimental.categories.Category;
30
31 import static org.junit.Assert.assertTrue;
32
33 @Category(MediumTests.class)
34 public class TestCheckAndMutate {
35 private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
36
37
38
39
40 @BeforeClass
41 public static void setUpBeforeClass() throws Exception {
42 TEST_UTIL.startMiniCluster();
43 }
44
45
46
47
48 @AfterClass
49 public static void tearDownAfterClass() throws Exception {
50 TEST_UTIL.shutdownMiniCluster();
51 }
52
53 @Test
54 public void testCheckAndMutate() throws Exception {
55 final TableName tableName = TableName.valueOf("TestPutWithDelete");
56 final byte[] rowKey = Bytes.toBytes("12345");
57 final byte[] family = Bytes.toBytes("cf");
58 HTable table = TEST_UTIL.createTable(tableName, family);
59 TEST_UTIL.waitTableAvailable(tableName.getName(), 5000);
60 try {
61
62 Put put = new Put(rowKey);
63 put.add(family, Bytes.toBytes("A"), Bytes.toBytes("a"));
64 put.add(family, Bytes.toBytes("B"), Bytes.toBytes("b"));
65 put.add(family, Bytes.toBytes("C"), Bytes.toBytes("c"));
66 table.put(put);
67
68 Get get = new Get(rowKey);
69 Result result = table.get(get);
70 assertTrue("Column A value should be a",
71 Bytes.toString(result.getValue(family, Bytes.toBytes("A"))).equals("a"));
72 assertTrue("Column B value should be b",
73 Bytes.toString(result.getValue(family, Bytes.toBytes("B"))).equals("b"));
74 assertTrue("Column C value should be c",
75 Bytes.toString(result.getValue(family, Bytes.toBytes("C"))).equals("c"));
76
77
78 RowMutations rm = new RowMutations(rowKey);
79 put = new Put(rowKey);
80 put.add(family, Bytes.toBytes("A"), Bytes.toBytes("a"));
81 put.add(family, Bytes.toBytes("B"), Bytes.toBytes("b"));
82 rm.add(put);
83 Delete del = new Delete(rowKey);
84 del.deleteColumn(family, Bytes.toBytes("C"));
85 rm.add(del);
86 boolean res = table.checkAndMutate(rowKey, family, Bytes.toBytes("A"), CompareFilter.CompareOp.EQUAL,
87 Bytes.toBytes("a"), rm);
88 assertTrue(res);
89
90
91 get = new Get(rowKey);
92 result = table.get(get);
93 assertTrue("Column A value should be a",
94 Bytes.toString(result.getValue(family, Bytes.toBytes("A"))).equals("a"));
95 assertTrue("Column B value should be b",
96 Bytes.toString(result.getValue(family, Bytes.toBytes("B"))).equals("b"));
97 assertTrue("Column C should not exist",
98 result.getValue(family, Bytes.toBytes("C")) == null);
99 } finally {
100 table.close();
101 }
102 }
103 }