1   /*
2    * Copyright 2010 The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  
21  package org.apache.hadoop.hbase.rest;
22  
23  import java.io.ByteArrayInputStream;
24  import java.io.IOException;
25  import java.io.StringWriter;
26  import java.util.Iterator;
27  import java.util.Random;
28  
29  import javax.xml.bind.JAXBContext;
30  import javax.xml.bind.JAXBException;
31  import javax.xml.bind.Marshaller;
32  import javax.xml.bind.Unmarshaller;
33  
34  import org.apache.commons.httpclient.Header;
35  import org.apache.hadoop.conf.Configuration;
36  import org.apache.hadoop.hbase.HBaseTestingUtility;
37  import org.apache.hadoop.hbase.HColumnDescriptor;
38  import org.apache.hadoop.hbase.HTableDescriptor;
39  import org.apache.hadoop.hbase.KeyValue;
40  import org.apache.hadoop.hbase.client.HBaseAdmin;
41  import org.apache.hadoop.hbase.client.HTable;
42  import org.apache.hadoop.hbase.client.Put;
43  import org.apache.hadoop.hbase.rest.client.Client;
44  import org.apache.hadoop.hbase.rest.client.Cluster;
45  import org.apache.hadoop.hbase.rest.client.Response;
46  import org.apache.hadoop.hbase.rest.model.CellModel;
47  import org.apache.hadoop.hbase.rest.model.CellSetModel;
48  import org.apache.hadoop.hbase.rest.model.RowModel;
49  import org.apache.hadoop.hbase.rest.model.ScannerModel;
50  import org.apache.hadoop.hbase.util.Bytes;
51  
52  import static org.junit.Assert.*;
53  import org.junit.AfterClass;
54  import org.junit.BeforeClass;
55  import org.junit.Test;
56  
57  public class TestScannerResource {
58    private static final String TABLE = "TestScannerResource";
59    private static final String NONEXISTENT_TABLE = "ThisTableDoesNotExist";
60    private static final String CFA = "a";
61    private static final String CFB = "b";
62    private static final String COLUMN_1 = CFA + ":1";
63    private static final String COLUMN_2 = CFB + ":2";
64  
65    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
66    private static final HBaseRESTTestingUtility REST_TEST_UTIL = 
67      new HBaseRESTTestingUtility();
68    private static Client client;
69    private static JAXBContext context;
70    private static Marshaller marshaller;
71    private static Unmarshaller unmarshaller;
72    private static int expectedRows1;
73    private static int expectedRows2;
74    private static Configuration conf;
75  
76    private static int insertData(String tableName, String column, double prob)
77        throws IOException {
78      Random rng = new Random();
79      int count = 0;
80      HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName);
81      byte[] k = new byte[3];
82      byte [][] famAndQf = KeyValue.parseColumn(Bytes.toBytes(column));
83      for (byte b1 = 'a'; b1 < 'z'; b1++) {
84        for (byte b2 = 'a'; b2 < 'z'; b2++) {
85          for (byte b3 = 'a'; b3 < 'z'; b3++) {
86            if (rng.nextDouble() < prob) {
87              k[0] = b1;
88              k[1] = b2;
89              k[2] = b3;
90              Put put = new Put(k);
91              put.setWriteToWAL(false);
92              put.add(famAndQf[0], famAndQf[1], k);
93              table.put(put);
94              count++;
95            }
96          }
97        }
98      }
99      table.flushCommits();
100     return count;
101   }
102 
103   private static int countCellSet(CellSetModel model) {
104     int count = 0;
105     Iterator<RowModel> rows = model.getRows().iterator();
106     while (rows.hasNext()) {
107       RowModel row = rows.next();
108       Iterator<CellModel> cells = row.getCells().iterator();
109       while (cells.hasNext()) {
110         cells.next();
111         count++;
112       }
113     }
114     return count;
115   }
116 
117   private static int fullTableScan(ScannerModel model) throws IOException {
118     model.setBatch(100);
119     Response response = client.put("/" + TABLE + "/scanner",
120       Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
121     assertEquals(response.getCode(), 201);
122     String scannerURI = response.getLocation();
123     assertNotNull(scannerURI);
124     int count = 0;
125     while (true) {
126       response = client.get(scannerURI, Constants.MIMETYPE_PROTOBUF);
127       assertTrue(response.getCode() == 200 || response.getCode() == 204);
128       if (response.getCode() == 200) {
129         CellSetModel cellSet = new CellSetModel();
130         cellSet.getObjectFromMessage(response.getBody());
131         Iterator<RowModel> rows = cellSet.getRows().iterator();
132         while (rows.hasNext()) {
133           RowModel row = rows.next();
134           Iterator<CellModel> cells = row.getCells().iterator();
135           while (cells.hasNext()) {
136             cells.next();
137             count++;
138           }
139         }
140       } else {
141         break;
142       }
143     }
144     // delete the scanner
145     response = client.delete(scannerURI);
146     assertEquals(response.getCode(), 200);
147     return count;
148   }
149 
150   @BeforeClass
151   public static void setUpBeforeClass() throws Exception {
152     conf = TEST_UTIL.getConfiguration();
153     TEST_UTIL.startMiniCluster();
154     REST_TEST_UTIL.startServletContainer(conf);
155     client = new Client(new Cluster().add("localhost",
156       REST_TEST_UTIL.getServletPort()));
157     context = JAXBContext.newInstance(
158       CellModel.class,
159       CellSetModel.class,
160       RowModel.class,
161       ScannerModel.class);
162     marshaller = context.createMarshaller();
163     unmarshaller = context.createUnmarshaller();
164     HBaseAdmin admin = TEST_UTIL.getHBaseAdmin();
165     if (admin.tableExists(TABLE)) {
166       return;
167     }
168     HTableDescriptor htd = new HTableDescriptor(TABLE);
169     htd.addFamily(new HColumnDescriptor(CFA));
170     htd.addFamily(new HColumnDescriptor(CFB));
171     admin.createTable(htd);
172     expectedRows1 = insertData(TABLE, COLUMN_1, 1.0);
173     expectedRows2 = insertData(TABLE, COLUMN_2, 0.5);
174   }
175 
176   @AfterClass
177   public static void tearDownAfterClass() throws Exception {
178     REST_TEST_UTIL.shutdownServletContainer();
179     TEST_UTIL.shutdownMiniCluster();
180   }
181 
182   @Test
183   public void testSimpleScannerXML() throws IOException, JAXBException {
184     final int BATCH_SIZE = 5;
185     // new scanner
186     ScannerModel model = new ScannerModel();
187     model.setBatch(BATCH_SIZE);
188     model.addColumn(Bytes.toBytes(COLUMN_1));
189     StringWriter writer = new StringWriter();
190     marshaller.marshal(model, writer);
191     byte[] body = Bytes.toBytes(writer.toString());
192 
193     // test put operation is forbidden in read-only mode
194     conf.set("hbase.rest.readonly", "true");
195     Response response = client.put("/" + TABLE + "/scanner",
196       Constants.MIMETYPE_XML, body);
197     assertEquals(response.getCode(), 403);
198     String scannerURI = response.getLocation();
199     assertNull(scannerURI);
200 
201     // recall previous put operation with read-only off
202     conf.set("hbase.rest.readonly", "false");
203     response = client.put("/" + TABLE + "/scanner", Constants.MIMETYPE_XML,
204       body);
205     assertEquals(response.getCode(), 201);
206     scannerURI = response.getLocation();
207     assertNotNull(scannerURI);
208 
209     // get a cell set
210     response = client.get(scannerURI, Constants.MIMETYPE_XML);
211     assertEquals(response.getCode(), 200);
212     CellSetModel cellSet = (CellSetModel)
213       unmarshaller.unmarshal(new ByteArrayInputStream(response.getBody()));
214     // confirm batch size conformance
215     assertEquals(countCellSet(cellSet), BATCH_SIZE);
216 
217     // test delete scanner operation is forbidden in read-only mode
218     conf.set("hbase.rest.readonly", "true");
219     response = client.delete(scannerURI);
220     assertEquals(response.getCode(), 403);
221 
222     // recall previous delete scanner operation with read-only off
223     conf.set("hbase.rest.readonly", "false");
224     response = client.delete(scannerURI);
225     assertEquals(response.getCode(), 200);
226   }
227 
228   @Test
229   public void testSimpleScannerPB() throws IOException {
230     final int BATCH_SIZE = 10;
231     // new scanner
232     ScannerModel model = new ScannerModel();
233     model.setBatch(BATCH_SIZE);
234     model.addColumn(Bytes.toBytes(COLUMN_1));
235 
236     // test put operation is forbidden in read-only mode
237     conf.set("hbase.rest.readonly", "true");
238     Response response = client.put("/" + TABLE + "/scanner",
239       Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
240     assertEquals(response.getCode(), 403);
241     String scannerURI = response.getLocation();
242     assertNull(scannerURI);
243 
244     // recall previous put operation with read-only off
245     conf.set("hbase.rest.readonly", "false");
246     response = client.put("/" + TABLE + "/scanner",
247       Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
248     assertEquals(response.getCode(), 201);
249     scannerURI = response.getLocation();
250     assertNotNull(scannerURI);
251 
252     // get a cell set
253     response = client.get(scannerURI, Constants.MIMETYPE_PROTOBUF);
254     assertEquals(response.getCode(), 200);
255     CellSetModel cellSet = new CellSetModel();
256     cellSet.getObjectFromMessage(response.getBody());
257     // confirm batch size conformance
258     assertEquals(countCellSet(cellSet), BATCH_SIZE);
259 
260     // test delete scanner operation is forbidden in read-only mode
261     conf.set("hbase.rest.readonly", "true");
262     response = client.delete(scannerURI);
263     assertEquals(response.getCode(), 403);
264 
265     // recall previous delete scanner operation with read-only off
266     conf.set("hbase.rest.readonly", "false");
267     response = client.delete(scannerURI);
268     assertEquals(response.getCode(), 200);
269   }
270 
271   @Test
272   public void testSimpleScannerBinary() throws IOException {
273     // new scanner
274     ScannerModel model = new ScannerModel();
275     model.setBatch(1);
276     model.addColumn(Bytes.toBytes(COLUMN_1));
277 
278     // test put operation is forbidden in read-only mode
279     conf.set("hbase.rest.readonly", "true");
280     Response response = client.put("/" + TABLE + "/scanner",
281       Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
282     assertEquals(response.getCode(), 403);
283     String scannerURI = response.getLocation();
284     assertNull(scannerURI);
285 
286     // recall previous put operation with read-only off
287     conf.set("hbase.rest.readonly", "false");
288     response = client.put("/" + TABLE + "/scanner",
289       Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
290     assertEquals(response.getCode(), 201);
291     scannerURI = response.getLocation();
292     assertNotNull(scannerURI);
293 
294     // get a cell
295     response = client.get(scannerURI, Constants.MIMETYPE_BINARY);
296     assertEquals(response.getCode(), 200);
297     // verify that data was returned
298     assertTrue(response.getBody().length > 0);
299     // verify that the expected X-headers are present
300     boolean foundRowHeader = false, foundColumnHeader = false,
301       foundTimestampHeader = false;
302     for (Header header: response.getHeaders()) {
303       if (header.getName().equals("X-Row")) {
304         foundRowHeader = true;
305       } else if (header.getName().equals("X-Column")) {
306         foundColumnHeader = true;
307       } else if (header.getName().equals("X-Timestamp")) {
308         foundTimestampHeader = true;
309       }
310     }
311     assertTrue(foundRowHeader);
312     assertTrue(foundColumnHeader);
313     assertTrue(foundTimestampHeader);
314 
315     // test delete scanner operation is forbidden in read-only mode
316     conf.set("hbase.rest.readonly", "true");
317     response = client.delete(scannerURI);
318     assertEquals(response.getCode(), 403);
319 
320     // recall previous delete scanner operation with read-only off
321     conf.set("hbase.rest.readonly", "false");
322     response = client.delete(scannerURI);
323     assertEquals(response.getCode(), 200);
324   }
325 
326   @Test
327   public void testFullTableScan() throws IOException {
328     ScannerModel model = new ScannerModel();
329     model.addColumn(Bytes.toBytes(COLUMN_1));
330     assertEquals(fullTableScan(model), expectedRows1);
331 
332     model = new ScannerModel();
333     model.addColumn(Bytes.toBytes(COLUMN_2));
334     assertEquals(fullTableScan(model), expectedRows2);
335   }
336 
337   @Test
338   public void testTableDoesNotExist() throws IOException, JAXBException {
339     ScannerModel model = new ScannerModel();
340     StringWriter writer = new StringWriter();
341     marshaller.marshal(model, writer);
342     byte[] body = Bytes.toBytes(writer.toString());
343     Response response = client.put("/" + NONEXISTENT_TABLE +
344       "/scanner", Constants.MIMETYPE_XML, body);
345     assertEquals(response.getCode(), 404);
346   }
347 }