SQOOP-3309: Implement HiveServer2 client
[sqoop.git] / src / java / org / apache / sqoop / hive / HiveServer2ConnectionFactoryInitializer.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.hive;
20
21
22 import org.apache.hadoop.security.UserGroupInformation;
23 import org.apache.sqoop.SqoopOptions;
24 import org.apache.sqoop.authentication.KerberosAuthenticator;
25 import org.apache.sqoop.db.JdbcConnectionFactory;
26 import org.apache.sqoop.db.decorator.KerberizedConnectionFactoryDecorator;
27
28 import java.io.IOException;
29
30 import static org.apache.commons.lang3.StringUtils.isBlank;
31 import static org.apache.commons.lang3.StringUtils.isEmpty;
32
33 public class HiveServer2ConnectionFactoryInitializer {
34
35 public JdbcConnectionFactory createJdbcConnectionFactory(SqoopOptions sqoopOptions) {
36 String connectionUsername = determineConnectionUsername(sqoopOptions);
37 JdbcConnectionFactory connectionFactory = new HiveServer2ConnectionFactory(sqoopOptions.getHs2Url(), connectionUsername);
38 if (useKerberizedConnection(sqoopOptions)) {
39 KerberosAuthenticator authenticator = createKerberosAuthenticator(sqoopOptions);
40 connectionFactory = new KerberizedConnectionFactoryDecorator(connectionFactory, authenticator);
41 }
42 return connectionFactory;
43 }
44
45 private String determineConnectionUsername(SqoopOptions sqoopOptions) {
46 if (!isEmpty(sqoopOptions.getHs2User())) {
47 return sqoopOptions.getHs2User();
48 }
49 try {
50 return UserGroupInformation.getLoginUser().getUserName();
51 } catch (IOException e) {
52 throw new RuntimeException("Unable to determine login user.", e);
53 }
54 }
55
56 private KerberosAuthenticator createKerberosAuthenticator(SqoopOptions sqoopOptions) {
57 return new KerberosAuthenticator(sqoopOptions.getConf(), sqoopOptions.getHs2User(), sqoopOptions.getHs2Keytab());
58 }
59
60 private boolean useKerberizedConnection(SqoopOptions sqoopOptions) {
61 return !isBlank(sqoopOptions.getHs2Keytab());
62 }
63
64 }