SQOOP-3309: Implement HiveServer2 client
[sqoop.git] / src / test / org / apache / sqoop / testutil / HiveServer2TestUtil.java
1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 * <p>
10 * http://www.apache.org/licenses/LICENSE-2.0
11 * <p>
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package org.apache.sqoop.testutil;
20
21 import org.apache.sqoop.hive.HiveServer2ConnectionFactory;
22
23 import java.sql.Connection;
24 import java.sql.PreparedStatement;
25 import java.sql.ResultSet;
26 import java.sql.ResultSetMetaData;
27 import java.sql.SQLException;
28 import java.util.ArrayList;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31
32 public class HiveServer2TestUtil {
33
34 private static final String SELECT_TABLE_QUERY = "SELECT * FROM %s";
35
36 private HiveServer2ConnectionFactory hs2ConnectionFactory;
37
38 public HiveServer2TestUtil(String url) {
39 this(url, null, null);
40 }
41
42 public HiveServer2TestUtil(String url, String username, String password) {
43 hs2ConnectionFactory = new HiveServer2ConnectionFactory(url, username, password);
44 }
45
46 public List<LinkedHashMap<String, Object>> loadRowsFromTable(String tableName) {
47 List<LinkedHashMap<String, Object>> result = new ArrayList<>();
48 try(Connection connection = hs2ConnectionFactory.createConnection();
49 PreparedStatement query = connection.prepareStatement(String.format(SELECT_TABLE_QUERY, tableName))) {
50
51 ResultSet resultSet = query.executeQuery();
52 ResultSetMetaData metaData = resultSet.getMetaData();
53
54 while (resultSet.next()) {
55 LinkedHashMap<String, Object> row = new LinkedHashMap<>();
56 for (int i = 1; i <= metaData.getColumnCount(); i++) {
57 row.put(metaData.getColumnName(i), resultSet.getObject(i));
58 }
59 result.add(row);
60 }
61 } catch (SQLException e) {
62 throw new RuntimeException(e);
63 }
64 return result;
65 }
66
67 public List<List<Object>> loadRawRowsFromTable(String tableName) {
68 List<List<Object>> result = new ArrayList<>();
69 List<LinkedHashMap<String, Object>> rowsWithColumnNames = loadRowsFromTable(tableName);
70
71 for (LinkedHashMap<String, Object> rowWithColumnNames : rowsWithColumnNames) {
72 result.add(new ArrayList<>(rowWithColumnNames.values()));
73 }
74
75 return result;
76 }
77
78 }