├── .github ├── CODEOWNERS └── workflows │ ├── main.yml │ └── release.yml ├── logo.png ├── NOTICE ├── .travis.yml ├── .gitignore ├── src ├── main │ └── java │ │ └── com │ │ └── hotels │ │ └── beeju │ │ ├── ThriftHiveMetaStoreApp.java │ │ ├── hiveserver2 │ │ ├── RelaxedSQLStdHiveAccessController.java │ │ ├── RelaxedSQLStdHiveAccessControllerWrapper.java │ │ └── RelaxedSQLStdHiveAuthorizerFactory.java │ │ ├── core │ │ ├── HiveMetaStoreCore.java │ │ ├── HiveServer2Core.java │ │ ├── ThriftHiveMetaStoreCore.java │ │ └── BeejuCore.java │ │ ├── extensions │ │ ├── HiveMetaStoreJUnitExtension.java │ │ ├── HiveServer2JUnitExtension.java │ │ ├── ThriftHiveMetaStoreJUnitExtension.java │ │ └── BeejuJUnitExtension.java │ │ ├── BeejuJUnitRule.java │ │ ├── HiveServer2JUnitRule.java │ │ ├── HiveMetaStoreJUnitRule.java │ │ └── ThriftHiveMetaStoreJUnitRule.java └── test │ ├── java │ └── com │ │ └── hotels │ │ └── beeju │ │ ├── core │ │ ├── HiveMetaStoreCoreTest.java │ │ ├── ThriftHiveMetaStoreCoreTest.java │ │ ├── BeejuCoreTest.java │ │ └── HiveServer2CoreTest.java │ │ ├── HiveServer2JUnitRuleTest.java │ │ ├── extensions │ │ ├── HiveServer2JUnitExtensionTest.java │ │ ├── HiveMetaStoreJUnitExtensionTest.java │ │ └── ThriftHiveMetaStoreJUnitExtensionTest.java │ │ ├── HiveMetaStoreJUnitRuleTest.java │ │ └── ThriftHiveMetaStoreJUnitRuleTest.java │ └── resources │ └── log4j.xml ├── CONTRIBUTING.md ├── CODE-OF-CONDUCT.md ├── CHANGELOG.md ├── pom.xml ├── README.md └── LICENSE.txt /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @HotelsDotCom/apiary-committers 2 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ExpediaGroup/beeju/HEAD/logo.png -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Expedia Inc. 2 | Copyright (C) 2015-2020 Expedia, Inc. 3 | 4 | This product includes software developed by Expedia, Inc. licensed under the Apache License, Version 2.0. 5 | 6 | This product includes software developed by The Apache Software Foundation (http://www.apache.org/) licensed under the Apache License, Version 2.0. 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk8 4 | os: 5 | - linux 6 | cache: 7 | directories: 8 | - ~/.m2/repository 9 | install: 10 | - mvn install -DskipTests=true -Dmaven.javadoc.skip=true --quiet --batch-mode --show-version 11 | script: 12 | - mvn package jacoco:report --batch-mode -Dtest.arguments='-Xmx512m -XX:MaxPermSize=256m' 13 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | name: Package and run all tests 8 | runs-on: ubuntu-24.04 9 | steps: 10 | - uses: actions/checkout@v2 11 | with: 12 | fetch-depth: 0 13 | - name: Set up JDK 14 | uses: actions/setup-java@v2 15 | with: 16 | distribution: 'adopt' 17 | java-version: '8' 18 | java-package: jdk 19 | - name: Run Maven Targets 20 | run: mvn package jacoco:report --batch-mode --show-version 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Eclipse 2 | .classpath 3 | .project 4 | .metadata 5 | .settings/ 6 | 7 | # Checkstyle and findbugs eclipse plugins 8 | */.checkstyle 9 | */.fbExcludeFilterFile 10 | 11 | # Intellij 12 | .idea/ 13 | *.iml 14 | *.iws 15 | 16 | # Mac 17 | .DS_Store 18 | 19 | # Maven 20 | log/ 21 | target/ 22 | 23 | # Java 24 | *.class 25 | *.jar 26 | *.war 27 | *.ear 28 | 29 | # Python 30 | *.py[cod] 31 | *.egg 32 | *.egg-info 33 | dist 34 | build 35 | eggs 36 | parts 37 | sdist 38 | develop-eggs 39 | .installed.cfg 40 | lib 41 | lib64 42 | MANIFEST 43 | 44 | # *Nix text editor backup files 45 | *~ 46 | # Emacs backup files 47 | .\#* 48 | \#* 49 | 50 | # Ignore GPG files 51 | **/*.gpg 52 | **/*.key 53 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/ThriftHiveMetaStoreApp.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju; 17 | 18 | import java.util.concurrent.CountDownLatch; 19 | 20 | public class ThriftHiveMetaStoreApp { 21 | 22 | public static void main(String[] args) throws Throwable { 23 | ThriftHiveMetaStoreJUnitRule rule = new ThriftHiveMetaStoreJUnitRule(); 24 | rule.setThriftPort(22334); 25 | rule.starting(null); 26 | System.out.println("BeeJU Thrift Hive Metastore listening on: " + rule.getThriftConnectionUri()); 27 | CountDownLatch latch = new CountDownLatch(1); 28 | latch.await(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/core/HiveMetaStoreCoreTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.core; 17 | 18 | import static org.junit.jupiter.api.Assertions.assertNotNull; 19 | 20 | import java.util.concurrent.ExecutionException; 21 | 22 | import org.junit.jupiter.api.AfterEach; 23 | import org.junit.jupiter.api.Test; 24 | 25 | public class HiveMetaStoreCoreTest { 26 | 27 | private final BeejuCore core = new BeejuCore(); 28 | private final HiveMetaStoreCore hiveMetaStoreCore = new HiveMetaStoreCore(core); 29 | 30 | @Test 31 | public void clientStarted() throws ExecutionException, InterruptedException { 32 | hiveMetaStoreCore.initialise(); 33 | assertNotNull(hiveMetaStoreCore.client()); 34 | } 35 | 36 | @AfterEach 37 | public void cleanUp() { 38 | core.cleanUp(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How To Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are just a few guidelines you need to follow which are described in detail below. 4 | 5 | ## 1. Fork this repo 6 | 7 | You should create a fork of this project in your account and work from there. You can create a fork by clicking the fork button in GitHub. 8 | 9 | ## 2. One feature, one branch 10 | 11 | Work for each new feature/issue should occur in its own branch. To create a new branch from the command line: 12 | ```shell 13 | git checkout -b my-new-feature 14 | ``` 15 | where "my-new-feature" describes what you're working on. 16 | 17 | ## 3. Add unit tests 18 | If your contribution modifies existing or adds new code please add corresponding unit tests for this. 19 | 20 | ## 4. Ensure that the build passes 21 | 22 | Run 23 | ```shell 24 | mvn package 25 | ``` 26 | and check that there are no errors. 27 | 28 | ## 5. Add documentation for new or updated functionality 29 | 30 | Please review all of the .md files in this project to see if they are impacted by your change and update them accordingly. 31 | 32 | ## 6. Add to CHANGELOG.md 33 | 34 | Any notable changes should be recorded in the CHANGELOG.md following the [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) conventions. 35 | 36 | ## 7. Submit a pull request and describe the change 37 | 38 | Push your changes to your branch and open a pull request against the parent repo on GitHub. The project administrators will review your pull request and respond with feedback. 39 | 40 | # How your contribution gets merged 41 | 42 | Upon pull request submission, your code will be reviewed by the maintainers. They will confirm at least the following: 43 | 44 | - Tests run successfully (unit, coverage, integration, style). 45 | - Contribution policy has been followed. 46 | 47 | Two (human) reviewers will need to sign off on your pull request before it can be merged. 48 | -------------------------------------------------------------------------------- /src/test/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release to Maven Central 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | branch: 6 | description: "The branch to use to release from." 7 | required: true 8 | default: "main" 9 | jobs: 10 | release: 11 | name: Release to Maven Central 12 | runs-on: ubuntu-24.04 13 | 14 | steps: 15 | - name: Checkout source code 16 | uses: actions/checkout@v2 17 | with: 18 | fetch-depth: 0 19 | ref: ${{ github.event.inputs.branch }} 20 | # We need a personal access token to be able to push to a protected branch 21 | token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }} 22 | 23 | - name: Set up JDK 24 | uses: actions/setup-java@v2 25 | with: 26 | distribution: 'adopt' 27 | java-version: '8' 28 | java-package: jdk 29 | server-id: central # Value of the distributionManagement/repository/id field of the pom.xml 30 | server-username: SONATYPE_USERNAME # env variable for username in deploy 31 | server-password: SONATYPE_PASSWORD # env variable for token in deploy 32 | # only signed artifacts will be released to maven central. this sets up things for the maven-gpg-plugin 33 | gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} # Value of the GPG private key to import 34 | gpg-passphrase: GPG_PASSPHRASE # env variable for GPG private key passphrase 35 | # this creates a settings.xml with the following server 36 | settings-path: ${{ github.workspace }} 37 | 38 | - name: Configure Git User 39 | run: | 40 | git config user.email "oss@expediagroup.com" 41 | git config user.name "eg-oss-ci" 42 | 43 | - name: Run Maven Targets 44 | # we are skipping the tests for releases, run a build step first. 45 | run: mvn release:prepare release:perform --settings $GITHUB_WORKSPACE/settings.xml -DskipTests -Darguments=-DskipTests --activate-profiles sonatype-oss-release-github-actions --batch-mode --show-version --no-transfer-progress 46 | env: 47 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 48 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 49 | GPG_PASSPHRASE: ${{secrets.GPG_PRIVATE_KEY_PASSPHRASE}} 50 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/HiveServer2JUnitRuleTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.junit.Assert.assertThat; 20 | 21 | import java.util.Collections; 22 | import java.util.Map; 23 | 24 | import org.apache.hadoop.hive.conf.HiveConf; 25 | import org.junit.Before; 26 | import org.junit.Rule; 27 | import org.junit.Test; 28 | 29 | public class HiveServer2JUnitRuleTest { 30 | 31 | private static final String DATABASE = "my_test_db"; 32 | 33 | public @Rule HiveServer2JUnitRule defaultDbRule = new HiveServer2JUnitRule(); 34 | public @Rule HiveServer2JUnitRule customDbRule = new HiveServer2JUnitRule(DATABASE); 35 | public @Rule HiveServer2JUnitRule customPropertiesRule = new HiveServer2JUnitRule("custom_props_database", customConfProperties()); 36 | 37 | private Map customConfProperties() { 38 | return Collections.singletonMap("my.custom.key", "my.custom.value"); 39 | } 40 | 41 | @Before 42 | public void init() throws Exception { 43 | Class.forName(customDbRule.driverClassName()); 44 | } 45 | 46 | @Test 47 | public void defaultDatabaseName() { 48 | String defaultDbName = defaultDbRule.databaseName(); 49 | assertThat(defaultDbName, is("test_database")); 50 | } 51 | 52 | @Test 53 | public void customProperties() { 54 | HiveConf hiveConf = customPropertiesRule.conf(); 55 | assertThat(hiveConf.get("my.custom.key"), is("my.custom.value")); 56 | } 57 | 58 | @Test 59 | public void databaseName() { 60 | assertThat(customDbRule.databaseName(), is(DATABASE)); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/extensions/HiveServer2JUnitExtensionTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.extensions; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.hamcrest.MatcherAssert.assertThat; 20 | 21 | import java.util.Collections; 22 | import java.util.Map; 23 | 24 | import org.apache.hadoop.hive.conf.HiveConf; 25 | import org.junit.jupiter.api.Test; 26 | import org.junit.jupiter.api.extension.RegisterExtension; 27 | 28 | public class HiveServer2JUnitExtensionTest { 29 | 30 | private static final String DATABASE = "my_test_db"; 31 | 32 | @RegisterExtension 33 | HiveServer2JUnitExtension defaultDbExtension = new HiveServer2JUnitExtension(); 34 | 35 | @RegisterExtension 36 | HiveServer2JUnitExtension customDbExtension = new HiveServer2JUnitExtension(DATABASE); 37 | 38 | @RegisterExtension 39 | HiveServer2JUnitExtension customPropertiesExtension = new HiveServer2JUnitExtension("custom_props_database", 40 | customConfProperties()); 41 | 42 | private Map customConfProperties() { 43 | Map conf = Collections.singletonMap("my.custom.key", "my.custom.value"); 44 | return conf; 45 | } 46 | 47 | @Test 48 | public void databaseName() { 49 | assertThat(customDbExtension.databaseName(), is(DATABASE)); 50 | } 51 | 52 | @Test 53 | public void defaultDatabaseName() throws Exception { 54 | String defaultDbName = defaultDbExtension.databaseName(); 55 | assertThat(defaultDbName, is("test_database")); 56 | } 57 | 58 | @Test 59 | public void customProperties() throws Exception { 60 | HiveConf hiveConf = customPropertiesExtension.conf(); 61 | assertThat(hiveConf.get("my.custom.key"), is("my.custom.value")); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/hiveserver2/RelaxedSQLStdHiveAccessController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.hiveserver2; 17 | 18 | import org.apache.hadoop.hive.conf.HiveConf; 19 | import org.apache.hadoop.hive.conf.HiveConf.ConfVars; 20 | import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider; 21 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException; 22 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext; 23 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory; 24 | import org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAccessController; 25 | 26 | /** 27 | * This class unsets the owner privileges to avoid issues with the the persistence manager. 28 | *

29 | * By default SELECT, INSERT, UPDATE and DELETE rights are granted to the owner and in our set up this caused the 30 | * persistence manager to hang. We don't need these rights because this service is just for testing so we remove them 31 | * here. 32 | *

33 | */ 34 | public class RelaxedSQLStdHiveAccessController extends SQLStdHiveAccessController { 35 | 36 | public RelaxedSQLStdHiveAccessController( 37 | HiveMetastoreClientFactory metastoreClientFactory, 38 | HiveConf conf, 39 | HiveAuthenticationProvider authenticator, 40 | HiveAuthzSessionContext ctx) throws HiveAuthzPluginException { 41 | super(metastoreClientFactory, conf, authenticator, ctx); 42 | } 43 | 44 | @Override 45 | public void applyAuthorizationConfigPolicy(HiveConf hiveConf) throws HiveAuthzPluginException { 46 | super.applyAuthorizationConfigPolicy(hiveConf); 47 | hiveConf.setVar(ConfVars.HIVE_AUTHORIZATION_TABLE_OWNER_GRANTS, ""); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/core/HiveMetaStoreCore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.core; 17 | 18 | import java.util.concurrent.Callable; 19 | import java.util.concurrent.ExecutionException; 20 | import java.util.concurrent.ExecutorService; 21 | import java.util.concurrent.Executors; 22 | 23 | import org.apache.hadoop.hive.conf.HiveConf; 24 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 25 | 26 | public class HiveMetaStoreCore { 27 | 28 | private HiveMetaStoreClient client; 29 | private final BeejuCore beejuCore; 30 | 31 | public HiveMetaStoreCore(BeejuCore beejuCore) { 32 | this.beejuCore = beejuCore; 33 | } 34 | 35 | public void initialise() throws InterruptedException, ExecutionException { 36 | HiveConf hiveConf = new HiveConf(beejuCore.conf(), HiveMetaStoreClient.class); 37 | ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); 38 | try { 39 | client = singleThreadExecutor.submit(new CallableHiveClient(hiveConf)).get(); 40 | } finally { 41 | singleThreadExecutor.shutdown(); 42 | } 43 | } 44 | 45 | public void shutdown() { 46 | if (client != null) { 47 | client.close(); 48 | } 49 | } 50 | 51 | /** 52 | * @return the {@link HiveMetaStoreClient} backed by an HSQLDB in-memory database. 53 | */ 54 | public HiveMetaStoreClient client() { 55 | return client; 56 | } 57 | 58 | public static class CallableHiveClient implements Callable { 59 | 60 | private final HiveConf hiveConf; 61 | 62 | CallableHiveClient(HiveConf hiveConf) { 63 | this.hiveConf = hiveConf; 64 | } 65 | 66 | @Override 67 | public HiveMetaStoreClient call() throws Exception { 68 | return new HiveMetaStoreClient(hiveConf); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/core/ThriftHiveMetaStoreCoreTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.core; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.hamcrest.MatcherAssert.assertThat; 20 | import static org.junit.jupiter.api.Assertions.assertThrows; 21 | 22 | import java.util.List; 23 | 24 | import org.apache.hadoop.hive.conf.HiveConf; 25 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 26 | import org.junit.jupiter.api.AfterEach; 27 | import org.junit.jupiter.api.Test; 28 | 29 | public class ThriftHiveMetaStoreCoreTest { 30 | 31 | private final BeejuCore core = new BeejuCore(); 32 | private final ThriftHiveMetaStoreCore thriftHiveMetaStoreCore = new ThriftHiveMetaStoreCore(core); 33 | 34 | @AfterEach 35 | public void cleanUp() { 36 | core.cleanUp(); 37 | } 38 | 39 | @Test 40 | public void before() throws Exception { 41 | thriftHiveMetaStoreCore.initialise(); 42 | assertThat(core.conf().getVar(HiveConf.ConfVars.METASTOREURIS), 43 | is(thriftHiveMetaStoreCore.getThriftConnectionUri())); 44 | 45 | HiveConf conf = new HiveConf(this.getClass()); 46 | conf.setVar(HiveConf.ConfVars.METASTOREURIS, thriftHiveMetaStoreCore.getThriftConnectionUri()); 47 | HiveMetaStoreClient client = new HiveMetaStoreClient(conf); 48 | List databases = client.getAllDatabases(); 49 | assertThat(databases.size(), is(1)); 50 | assertThat(databases.get(0), is("default")); 51 | } 52 | 53 | @Test 54 | public void validThriftPort() throws Exception { 55 | int thriftPort = 3333; 56 | thriftHiveMetaStoreCore.setThriftPort(3333); 57 | assertThat(thriftHiveMetaStoreCore.getThriftPort(), is(thriftPort)); 58 | thriftHiveMetaStoreCore.initialise(); 59 | assertThat(thriftHiveMetaStoreCore.getThriftPort(), is(thriftPort)); 60 | } 61 | 62 | @Test 63 | public void invalidThriftPort() { 64 | assertThrows(IllegalArgumentException.class, () -> thriftHiveMetaStoreCore.setThriftPort(-1)); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/hiveserver2/RelaxedSQLStdHiveAccessControllerWrapper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.hiveserver2; 17 | 18 | import java.lang.reflect.Field; 19 | 20 | import org.apache.hadoop.hive.conf.HiveConf; 21 | import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider; 22 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException; 23 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext; 24 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory; 25 | import org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAccessControllerWrapper; 26 | 27 | /** 28 | * This class overrides the {@code hiveAccessController} attribute in the parent class with our own implementation. 29 | */ 30 | public class RelaxedSQLStdHiveAccessControllerWrapper extends SQLStdHiveAccessControllerWrapper { 31 | 32 | public RelaxedSQLStdHiveAccessControllerWrapper( 33 | HiveMetastoreClientFactory metastoreClientFactory, 34 | HiveConf conf, 35 | HiveAuthenticationProvider authenticator, 36 | HiveAuthzSessionContext ctx) throws HiveAuthzPluginException { 37 | super(metastoreClientFactory, conf, authenticator, ctx); 38 | overrideHiveAccessController( 39 | new RelaxedSQLStdHiveAccessController(metastoreClientFactory, conf, authenticator, ctx)); 40 | } 41 | 42 | private void overrideHiveAccessController(RelaxedSQLStdHiveAccessController hackedSQLStdHiveAccessController) { 43 | try { 44 | Field hiveAccessControllerField = SQLStdHiveAccessControllerWrapper.class 45 | .getDeclaredField("hiveAccessController"); 46 | hiveAccessControllerField.setAccessible(true); 47 | hiveAccessControllerField.set(this, hackedSQLStdHiveAccessController); 48 | hiveAccessControllerField.setAccessible(false); 49 | } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { 50 | throw new RuntimeException("Unable to override field 'hiveAccessController' in class " 51 | + SQLStdHiveAccessControllerWrapper.class.getName(), e); 52 | } 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/core/HiveServer2Core.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.core; 17 | 18 | import java.io.IOException; 19 | import java.net.ServerSocket; 20 | 21 | import org.apache.hadoop.hive.conf.HiveConf; 22 | import org.apache.hive.service.Service; 23 | import org.apache.hive.service.server.HiveServer2; 24 | 25 | import com.hotels.beeju.hiveserver2.RelaxedSQLStdHiveAuthorizerFactory; 26 | 27 | public class HiveServer2Core { 28 | 29 | private final BeejuCore beejuCore; 30 | private String jdbcConnectionUrl; 31 | private HiveServer2 hiveServer2; 32 | private int port; 33 | 34 | public HiveServer2Core(BeejuCore beejuCore) { 35 | this.beejuCore = beejuCore; 36 | } 37 | 38 | public void initialise() throws InterruptedException { 39 | beejuCore.setHiveVar(HiveConf.ConfVars.HIVE_AUTHORIZATION_MANAGER, 40 | RelaxedSQLStdHiveAuthorizerFactory.class.getName()); 41 | hiveServer2 = new HiveServer2(); 42 | hiveServer2.init(beejuCore.conf()); 43 | hiveServer2.start(); 44 | waitForHiveServer2StartUp(); 45 | 46 | jdbcConnectionUrl = "jdbc:hive2://localhost:" + port + "/" + beejuCore.databaseName(); 47 | } 48 | 49 | public void shutdown() { 50 | if (hiveServer2 != null) { 51 | hiveServer2.stop(); 52 | } 53 | } 54 | 55 | private void waitForHiveServer2StartUp() throws InterruptedException { 56 | int retries = 0; 57 | int maxRetries = 5; 58 | while (hiveServer2.getServiceState() != Service.STATE.STARTED && retries < maxRetries) { 59 | Thread.sleep(1000); 60 | retries++; 61 | } 62 | if (retries >= maxRetries) { 63 | throw new RuntimeException("HiveServer2 did not start in a reasonable time"); 64 | } 65 | } 66 | 67 | public void startServerSocket() throws IOException { 68 | try (ServerSocket socket = new ServerSocket(0)) { 69 | port = socket.getLocalPort(); 70 | } 71 | beejuCore.setHiveIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT, port); 72 | } 73 | 74 | public String getJdbcConnectionUrl() { 75 | return jdbcConnectionUrl; 76 | } 77 | 78 | public int getPort() { 79 | return port; 80 | } 81 | 82 | public HiveServer2 getHiveServer2() { 83 | return hiveServer2; 84 | } 85 | 86 | public BeejuCore getCore() { 87 | return beejuCore; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/extensions/HiveMetaStoreJUnitExtension.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.extensions; 17 | 18 | import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.CONNECT_URL_KEY; 19 | 20 | import java.util.Map; 21 | 22 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 23 | import org.junit.jupiter.api.extension.ExtensionContext; 24 | 25 | import com.hotels.beeju.core.HiveMetaStoreCore; 26 | 27 | /** 28 | * A JUnit Extension that creates a Hive Metastore backed by an in-memory database. 29 | *

30 | * A fresh database instance will be created for each test method. 31 | *

32 | */ 33 | public class HiveMetaStoreJUnitExtension extends BeejuJUnitExtension { 34 | 35 | private final HiveMetaStoreCore hiveMetaStoreCore; 36 | 37 | /** 38 | * Create a Hive Metastore with a pre-created database "test_database". 39 | */ 40 | public HiveMetaStoreJUnitExtension() { 41 | this("test_database"); 42 | } 43 | 44 | /** 45 | * Create a Hive Metastore with a pre-created database using the provided name. 46 | * 47 | * @param databaseName Database name. 48 | */ 49 | public HiveMetaStoreJUnitExtension(String databaseName) { 50 | this(databaseName, null); 51 | } 52 | 53 | /** 54 | * Create a Hive Metastore with a pre-created database using the provided name and configuration. 55 | * 56 | * @param databaseName Database name. 57 | * @param configuration Hive configuration properties. 58 | */ 59 | public HiveMetaStoreJUnitExtension(String databaseName, Map configuration) { 60 | super(databaseName, configuration); 61 | hiveMetaStoreCore = new HiveMetaStoreCore(core); 62 | } 63 | 64 | @Override 65 | public void beforeEach(ExtensionContext context) throws Exception { 66 | System.clearProperty(CONNECT_URL_KEY.getVarname()); 67 | super.beforeEach(context); 68 | hiveMetaStoreCore.initialise(); 69 | } 70 | 71 | @Override 72 | public void afterEach(ExtensionContext context) throws Exception { 73 | hiveMetaStoreCore.shutdown(); 74 | super.afterEach(context); 75 | } 76 | 77 | /** 78 | * @return {@link com.hotels.beeju.core.HiveMetaStoreCore#client()}. 79 | */ 80 | public HiveMetaStoreClient client() { 81 | return hiveMetaStoreCore.client(); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/extensions/HiveServer2JUnitExtension.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.extensions; 17 | 18 | import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.CONNECT_URL_KEY; 19 | 20 | import java.util.Map; 21 | 22 | import org.apache.hive.jdbc.HiveDriver; 23 | import org.junit.jupiter.api.extension.ExtensionContext; 24 | 25 | import com.hotels.beeju.core.HiveServer2Core; 26 | 27 | public class HiveServer2JUnitExtension extends BeejuJUnitExtension { 28 | 29 | private final HiveServer2Core hiveServer2Core; 30 | 31 | /** 32 | * Create a HiveServer2 service with a pre-created database "test_database". 33 | */ 34 | public HiveServer2JUnitExtension() { 35 | this("test_database"); 36 | } 37 | 38 | /** 39 | * Create a HiveServer2 service with a pre-created database using the provided name. 40 | * 41 | * @param databaseName Database name. 42 | */ 43 | public HiveServer2JUnitExtension(String databaseName) { 44 | this(databaseName, null); 45 | } 46 | 47 | /** 48 | * Create a HiveServer2 service with a pre-created database using the provided name and configuration. 49 | * 50 | * @param databaseName Database name. 51 | * @param configuration Hive configuration properties. 52 | */ 53 | public HiveServer2JUnitExtension(String databaseName, Map configuration) { 54 | super(databaseName, configuration); 55 | hiveServer2Core = new HiveServer2Core(core); 56 | } 57 | 58 | @Override 59 | public void beforeEach(ExtensionContext context) throws Exception { 60 | System.clearProperty(CONNECT_URL_KEY.getVarname()); 61 | hiveServer2Core.startServerSocket(); 62 | super.beforeEach(context); 63 | hiveServer2Core.initialise(); 64 | } 65 | 66 | @Override 67 | public void afterEach(ExtensionContext context) throws Exception { 68 | hiveServer2Core.shutdown(); 69 | super.afterEach(context); 70 | } 71 | 72 | /** 73 | * @return the name of the Hive JDBC driver class used to access the database. 74 | */ 75 | @Override 76 | public String driverClassName() { 77 | return HiveDriver.class.getName(); 78 | } 79 | 80 | /** 81 | * @return {@link com.hotels.beeju.core.HiveServer2Core#getJdbcConnectionUrl()}. 82 | */ 83 | @Override 84 | public String connectionURL() { 85 | return hiveServer2Core.getJdbcConnectionUrl(); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/hiveserver2/RelaxedSQLStdHiveAuthorizerFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2017 The Apache Software Foundation and Expedia Inc. 3 | * This code is based on Hive's HiveMetaStore: 4 | * 5 | * https://github.com/apache/hive/blob/release-2.1.0-rc3/ql/src/java/org/apache/hadoop/hive/ql/ 6 | * security/authorization/plugin/sqlstd/SQLStdHiveAuthorizerFactory.java 7 | * 8 | * Licensed to the Apache Software Foundation (ASF) under one 9 | * or more contributor license agreements. See the NOTICE file 10 | * distributed with this work for additional information 11 | * regarding copyright ownership. The ASF licenses this file 12 | * to you under the Apache License, Version 2.0 (the 13 | * "License"); you may not use this file except in compliance 14 | * with the License. You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | package com.hotels.beeju.hiveserver2; 25 | 26 | import org.apache.hadoop.hive.conf.HiveConf; 27 | import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider; 28 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizer; 29 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizerFactory; 30 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizerImpl; 31 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException; 32 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext; 33 | import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory; 34 | import org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAuthorizationValidator; 35 | 36 | /** 37 | * Based on {@code org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAccessControllerWrapper} in 38 | * {@code hive-exec-1.2.1} 39 | *

40 | * This class creates a {@code HiveAuthorizer} that ignores the default owner privileges on the tables. 41 | *

42 | */ 43 | public class RelaxedSQLStdHiveAuthorizerFactory implements HiveAuthorizerFactory { 44 | @Override 45 | public HiveAuthorizer createHiveAuthorizer( 46 | HiveMetastoreClientFactory metastoreClientFactory, 47 | HiveConf conf, 48 | HiveAuthenticationProvider authenticator, 49 | HiveAuthzSessionContext ctx) 50 | throws HiveAuthzPluginException { 51 | RelaxedSQLStdHiveAccessControllerWrapper privilegeManager = new RelaxedSQLStdHiveAccessControllerWrapper( 52 | metastoreClientFactory, conf, authenticator, ctx); 53 | return new HiveAuthorizerImpl(privilegeManager, 54 | new SQLStdHiveAuthorizationValidator(metastoreClientFactory, conf, authenticator, privilegeManager, ctx)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/extensions/HiveMetaStoreJUnitExtensionTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.extensions; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.hamcrest.MatcherAssert.assertThat; 20 | import static org.junit.jupiter.api.Assertions.assertThrows; 21 | 22 | import java.io.File; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | import org.apache.hadoop.hive.metastore.api.AlreadyExistsException; 27 | import org.apache.hadoop.hive.metastore.api.Database; 28 | import org.junit.jupiter.api.Test; 29 | import org.junit.jupiter.api.extension.RegisterExtension; 30 | 31 | public class HiveMetaStoreJUnitExtensionTest { 32 | 33 | @RegisterExtension 34 | HiveMetaStoreJUnitExtension defaultDbExtension = new HiveMetaStoreJUnitExtension(); 35 | 36 | @RegisterExtension 37 | HiveMetaStoreJUnitExtension customDbExtension = new HiveMetaStoreJUnitExtension("my_test_database"); 38 | 39 | @RegisterExtension 40 | HiveMetaStoreJUnitExtension customPropertiesExtension = new HiveMetaStoreJUnitExtension("custom_props_database", 41 | customConfProperties()); 42 | 43 | private void assertExtensionInitialised(HiveMetaStoreJUnitExtension hive) throws Exception { 44 | String databaseName = hive.databaseName(); 45 | Database database = hive.client().getDatabase(databaseName); 46 | 47 | assertThat(database.getName(), is(databaseName)); 48 | File databaseFolder = new File(hive.getWarehouseDirectory(), databaseName); 49 | assertThat(new File(database.getLocationUri()) + "/", is(databaseFolder.toURI().toString())); 50 | } 51 | 52 | private Map customConfProperties() { 53 | Map conf = new HashMap<>(); 54 | conf.put("my.custom.key", "my.custom.value"); 55 | return conf; 56 | } 57 | 58 | @Test 59 | public void defaultDbNameInitialised() throws Exception { 60 | assertExtensionInitialised(defaultDbExtension); 61 | } 62 | 63 | @Test 64 | public void customDbNameInitialised() throws Exception { 65 | assertExtensionInitialised(customDbExtension); 66 | } 67 | 68 | @Test 69 | public void customDbNameAndConfInitialised() throws Exception { 70 | assertExtensionInitialised(customPropertiesExtension); 71 | } 72 | 73 | @Test 74 | public void createExistingDatabase() { 75 | assertThrows(AlreadyExistsException.class, 76 | () -> defaultDbExtension.createDatabase(defaultDbExtension.databaseName())); 77 | } 78 | 79 | @Test 80 | public void createDatabaseNullName() { 81 | assertThrows(NullPointerException.class, () -> defaultDbExtension.createDatabase(null)); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /CODE-OF-CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behaviour that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behaviour by participants include: 24 | 25 | * The use of sexualised language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behaviour and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behaviour. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviours that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behaviour may be 58 | reported by contacting [a member of the project team](https://github.com/orgs/ExpediaGroup/teams/apiary-committers/members). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/extensions/ThriftHiveMetaStoreJUnitExtension.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.extensions; 17 | 18 | import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.CONNECT_URL_KEY; 19 | 20 | import java.util.Map; 21 | 22 | import org.junit.jupiter.api.extension.ExtensionContext; 23 | 24 | import com.hotels.beeju.core.ThriftHiveMetaStoreCore; 25 | 26 | /** 27 | * A JUnit Extension that creates a Hive Metastore Thrift service backed by a Hive Metastore using an in-memory 28 | * database. 29 | *

30 | * A fresh database instance will be created for each test method. 31 | *

32 | */ 33 | public class ThriftHiveMetaStoreJUnitExtension extends HiveMetaStoreJUnitExtension { 34 | 35 | private final ThriftHiveMetaStoreCore thriftHiveMetaStoreCore; 36 | 37 | /** 38 | * Create a Thrift Hive Metastore service with a pre-created database "test_database". 39 | */ 40 | public ThriftHiveMetaStoreJUnitExtension() { 41 | this("test_database"); 42 | } 43 | 44 | /** 45 | * Create a Thrift Hive Metastore service with a pre-created database using the provided name. 46 | * 47 | * @param databaseName Database name. 48 | */ 49 | public ThriftHiveMetaStoreJUnitExtension(String databaseName) { 50 | this(databaseName, null); 51 | } 52 | 53 | /** 54 | * Create a Thrift Hive Metastore service with a pre-created database using the provided name and configuration. 55 | * 56 | * @param databaseName Database name. 57 | * @param configuration Hive configuration properties. 58 | */ 59 | public ThriftHiveMetaStoreJUnitExtension(String databaseName, Map configuration) { 60 | super(databaseName, configuration); 61 | thriftHiveMetaStoreCore = new ThriftHiveMetaStoreCore(core); 62 | } 63 | 64 | @Override 65 | public void beforeEach(ExtensionContext context) throws Exception { 66 | System.clearProperty(CONNECT_URL_KEY.getVarname()); 67 | thriftHiveMetaStoreCore.initialise(); 68 | super.beforeEach(context); 69 | } 70 | 71 | @Override 72 | public void afterEach(ExtensionContext context) throws Exception { 73 | thriftHiveMetaStoreCore.shutdown(); 74 | super.afterEach(context); 75 | } 76 | 77 | /** 78 | * @return {@link com.hotels.beeju.core.ThriftHiveMetaStoreCore#getThriftConnectionUri()}. 79 | */ 80 | public String getThriftConnectionUri() { 81 | return thriftHiveMetaStoreCore.getThriftConnectionUri(); 82 | } 83 | 84 | /** 85 | * @return {@link com.hotels.beeju.core.ThriftHiveMetaStoreCore#getThriftPort()} 86 | */ 87 | public int getThriftPort() { 88 | return thriftHiveMetaStoreCore.getThriftPort(); 89 | } 90 | 91 | /** 92 | * @param thriftPort The Port to use for the Thrift Hive metastore, if not set then a port number will automatically be allocated. 93 | */ 94 | public void setThriftPort(int thriftPort) { 95 | thriftHiveMetaStoreCore.setThriftPort(thriftPort); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/extensions/BeejuJUnitExtension.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.extensions; 17 | 18 | import java.io.File; 19 | import java.util.Map; 20 | 21 | import org.apache.hadoop.hive.conf.HiveConf; 22 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 23 | import org.apache.thrift.TException; 24 | import org.junit.jupiter.api.extension.AfterEachCallback; 25 | import org.junit.jupiter.api.extension.BeforeEachCallback; 26 | import org.junit.jupiter.api.extension.ExtensionContext; 27 | 28 | import com.hotels.beeju.core.BeejuCore; 29 | 30 | /** 31 | * Base class for BeeJU JUnit Extensions that require a Hive Metastore database configuration pre-set. 32 | */ 33 | public abstract class BeejuJUnitExtension implements BeforeEachCallback, AfterEachCallback { 34 | 35 | protected BeejuCore core; 36 | 37 | public BeejuJUnitExtension(String databaseName, Map configuration) { 38 | core = new BeejuCore(databaseName, configuration); 39 | } 40 | 41 | @Override 42 | public void beforeEach(ExtensionContext context) throws Exception { 43 | createDatabase(databaseName()); 44 | } 45 | 46 | @Override 47 | public void afterEach(ExtensionContext context) throws Exception { 48 | core.cleanUp(); 49 | } 50 | 51 | /** 52 | * @return {@link com.hotels.beeju.core.BeejuCore#driverClassName()}. 53 | */ 54 | public String driverClassName() { 55 | return core.driverClassName(); 56 | } 57 | 58 | /** 59 | * @return {@link com.hotels.beeju.core.BeejuCore#databaseName()}. 60 | */ 61 | public String databaseName() { 62 | return core.databaseName(); 63 | } 64 | 65 | /** 66 | * @return {@link com.hotels.beeju.core.BeejuCore#connectionURL()} 67 | */ 68 | public String connectionURL() { 69 | return core.connectionURL(); 70 | } 71 | 72 | /** 73 | * @return {@link com.hotels.beeju.core.BeejuCore#conf()}. 74 | */ 75 | public HiveConf conf() { 76 | return core.conf(); 77 | } 78 | 79 | /** 80 | * @return {@link com.hotels.beeju.core.BeejuCore#newClient()}. 81 | */ 82 | public HiveMetaStoreClient newClient() { 83 | return core.newClient(); 84 | } 85 | 86 | /** 87 | * See {@link com.hotels.beeju.core.BeejuCore#createDatabase(String)} 88 | * 89 | * @param databaseName Database name. 90 | * @throws TException If an error occurs creating the database. 91 | */ 92 | public void createDatabase(String databaseName) throws TException { 93 | core.createDatabase(databaseName); 94 | } 95 | 96 | /** 97 | * @return Root temporary directory as a file. 98 | */ 99 | public File getTempDirectory() { 100 | return core.tempDir().toFile(); 101 | } 102 | 103 | /** 104 | * @return Root warehouse directory as a file. 105 | */ 106 | public File getWarehouseDirectory() { 107 | return core.warehouseDir().toFile(); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/BeejuJUnitRule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju; 17 | 18 | import java.io.File; 19 | import java.util.Map; 20 | 21 | import org.apache.hadoop.hive.conf.HiveConf; 22 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 23 | import org.apache.thrift.TException; 24 | import org.junit.rules.TestWatcher; 25 | import org.junit.runner.Description; 26 | 27 | import com.hotels.beeju.core.BeejuCore; 28 | 29 | /** 30 | * Base class for BeeJU JUnit Rules that require a Hive Metastore database configuration pre-set. 31 | */ 32 | abstract class BeejuJUnitRule extends TestWatcher { 33 | 34 | protected BeejuCore core; 35 | 36 | BeejuJUnitRule(String databaseName, Map preConfiguration) { 37 | core = new BeejuCore(databaseName, preConfiguration); 38 | } 39 | 40 | public BeejuJUnitRule( 41 | String databaseName, 42 | Map preConfiguration, 43 | Map postConfiguration) { 44 | core = new BeejuCore(databaseName, preConfiguration, postConfiguration); 45 | } 46 | 47 | @Override 48 | public void starting(Description description) { 49 | try { 50 | createDatabase(databaseName()); 51 | } catch (TException e) { 52 | throw new RuntimeException("Error starting rule", e); 53 | } 54 | } 55 | 56 | @Override 57 | public void finished(Description description) { 58 | core.cleanUp(); 59 | } 60 | 61 | /** 62 | * @return {@link com.hotels.beeju.core.BeejuCore#driverClassName()}. 63 | */ 64 | public String driverClassName() { 65 | return core.driverClassName(); 66 | } 67 | 68 | /** 69 | * @return {@link com.hotels.beeju.core.BeejuCore#databaseName()}. 70 | */ 71 | public String databaseName() { 72 | return core.databaseName(); 73 | } 74 | 75 | /** 76 | * @return {@link com.hotels.beeju.core.BeejuCore#connectionURL()}. 77 | */ 78 | public String connectionURL() { 79 | return core.connectionURL(); 80 | } 81 | 82 | /** 83 | * @return {@link com.hotels.beeju.core.BeejuCore#conf()}. 84 | */ 85 | public HiveConf conf() { 86 | return core.conf(); 87 | } 88 | 89 | /** 90 | * @return {@link com.hotels.beeju.core.BeejuCore#newClient()}. 91 | */ 92 | public HiveMetaStoreClient newClient() { 93 | return core.newClient(); 94 | } 95 | 96 | /** 97 | * @return Root of temporary directory 98 | */ 99 | File tempDir() { 100 | return core.tempDir().toFile(); 101 | } 102 | 103 | /** 104 | * @return Root of warehouse directory 105 | */ 106 | File warehouseDir() { 107 | return core.warehouseDir().toFile(); 108 | } 109 | 110 | /** 111 | * Create a new database with the specified name. 112 | * 113 | * @param databaseName Database name. 114 | * @throws TException If an error occurs creating the database. 115 | */ 116 | public void createDatabase(String databaseName) throws TException { 117 | core.createDatabase(databaseName); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/HiveMetaStoreJUnitRuleTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.junit.Assert.assertFalse; 20 | import static org.junit.Assert.assertThat; 21 | import static org.junit.Assert.assertTrue; 22 | 23 | import java.io.File; 24 | import java.util.Collections; 25 | import java.util.Map; 26 | 27 | import org.apache.hadoop.hive.conf.HiveConf; 28 | import org.apache.hadoop.hive.metastore.api.AlreadyExistsException; 29 | import org.apache.hadoop.hive.metastore.api.Database; 30 | import org.apache.hadoop.hive.metastore.api.InvalidObjectException; 31 | import org.apache.thrift.TException; 32 | import org.junit.AfterClass; 33 | import org.junit.Before; 34 | import org.junit.Rule; 35 | import org.junit.Test; 36 | 37 | public class HiveMetaStoreJUnitRuleTest { 38 | 39 | private static File tempRoot; 40 | public @Rule HiveMetaStoreJUnitRule defaultDbRule = new HiveMetaStoreJUnitRule(); 41 | public @Rule HiveMetaStoreJUnitRule customDbRule = new HiveMetaStoreJUnitRule("my_test_database"); 42 | public @Rule HiveMetaStoreJUnitRule customPropertiesRule = new HiveMetaStoreJUnitRule("custom_props_database", customConfProperties()); 43 | 44 | private Map customConfProperties() { 45 | return Collections.singletonMap("my.custom.key", "my.custom.value"); 46 | } 47 | 48 | @Before 49 | public void before() { 50 | tempRoot = defaultDbRule.tempDir(); 51 | assertTrue(tempRoot.exists()); 52 | } 53 | 54 | @Test 55 | public void hiveDefaultName() throws Exception { 56 | assertRuleInitialised(defaultDbRule); 57 | } 58 | 59 | @Test 60 | public void hiveCustomName() throws Exception { 61 | assertRuleInitialised(customDbRule); 62 | } 63 | 64 | private static void assertRuleInitialised(HiveMetaStoreJUnitRule hive) throws Exception { 65 | String databaseName = hive.databaseName(); 66 | Database database = hive.client().getDatabase(databaseName); 67 | 68 | assertThat(database.getName(), is(databaseName)); 69 | File databaseFolder = new File(hive.warehouseDir(), databaseName); 70 | assertThat(new File(database.getLocationUri()) + "/", is(databaseFolder.toURI().toString())); 71 | } 72 | 73 | @Test 74 | public void customProperties() { 75 | HiveConf hiveConf = customPropertiesRule.conf(); 76 | assertThat(hiveConf.get("my.custom.key"), is("my.custom.value")); 77 | } 78 | 79 | @Test(expected = AlreadyExistsException.class) 80 | public void createExistingDatabase() throws TException { 81 | defaultDbRule.createDatabase(defaultDbRule.databaseName()); 82 | } 83 | 84 | @Test(expected = NullPointerException.class) 85 | public void createDatabaseNullName() throws TException { 86 | defaultDbRule.createDatabase(null); 87 | } 88 | 89 | @Test(expected = InvalidObjectException.class) 90 | public void createDatabaseInvalidName() throws TException { 91 | defaultDbRule.createDatabase(""); 92 | } 93 | 94 | @AfterClass 95 | public static void afterClass() { 96 | assertFalse("Found folder at " + tempRoot, tempRoot.exists()); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/HiveServer2JUnitRule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju; 17 | 18 | import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.CONNECT_URL_KEY; 19 | 20 | import java.io.IOException; 21 | import java.io.UncheckedIOException; 22 | import java.util.Map; 23 | 24 | import org.apache.hive.jdbc.HiveDriver; 25 | import org.junit.runner.Description; 26 | 27 | import com.hotels.beeju.core.HiveServer2Core; 28 | 29 | /** 30 | * A JUnit Rule that creates a HiveServer2 service and Thrift Metastore service backed by a Hive Metastore using an 31 | * HSQLDB in-memory database. 32 | *

33 | * A fresh database instance will be created for each test method. 34 | *

35 | *

36 | * Note that this class is meant to be used for DDL operations only. Any attempt to run DML operations may result in 37 | * errors. 38 | *

39 | */ 40 | public class HiveServer2JUnitRule extends BeejuJUnitRule { 41 | 42 | private HiveServer2Core hiveServer2Core = new HiveServer2Core(core); 43 | 44 | /** 45 | * Create a HiveServer2 service with a pre-created database "test_database". 46 | */ 47 | public HiveServer2JUnitRule() { 48 | this("test_database"); 49 | } 50 | 51 | /** 52 | * Create a HiveServer2 service with a pre-created database using the provided name. 53 | * 54 | * @param databaseName Database name. 55 | */ 56 | public HiveServer2JUnitRule(String databaseName) { 57 | this(databaseName, null); 58 | } 59 | 60 | /** 61 | * Create a HiveServer2 service with a pre-created database using the provided name and configuration. 62 | * 63 | * @param databaseName Database name. 64 | * @param configuration Hive configuration properties. 65 | */ 66 | public HiveServer2JUnitRule(String databaseName, Map configuration) { 67 | super(databaseName, configuration); 68 | } 69 | 70 | @Override 71 | public void starting(Description description) { 72 | System.clearProperty(CONNECT_URL_KEY.getVarname()); 73 | try { 74 | hiveServer2Core.startServerSocket(); 75 | } catch (IOException e) { 76 | throw new UncheckedIOException("Error starting HiveServer2 server socket", e); 77 | } 78 | super.starting(description); 79 | try { 80 | hiveServer2Core.initialise(); 81 | } catch (InterruptedException e) { 82 | throw new RuntimeException("Error initialising HiveServer2 core", e); 83 | } 84 | } 85 | 86 | @Override 87 | public void finished(Description description) { 88 | try { 89 | hiveServer2Core.shutdown(); 90 | } finally { 91 | super.finished(description); 92 | } 93 | } 94 | 95 | /** 96 | * @return the name of the Hive JDBC driver class used to access the database. 97 | */ 98 | @Override 99 | public String driverClassName() { 100 | return HiveDriver.class.getName(); 101 | } 102 | 103 | /** 104 | * @return {@link com.hotels.beeju.core.HiveServer2Core#getJdbcConnectionUrl()}. 105 | */ 106 | @Override 107 | public String connectionURL() { 108 | return hiveServer2Core.getJdbcConnectionUrl(); 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/HiveMetaStoreJUnitRule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju; 17 | 18 | import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.CONNECT_URL_KEY; 19 | 20 | import java.util.Map; 21 | import java.util.concurrent.ExecutionException; 22 | 23 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 24 | import org.junit.runner.Description; 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | import com.hotels.beeju.core.HiveMetaStoreCore; 29 | 30 | /** 31 | * A JUnit {@link org.junit.Rule} that creates a Hive Metastore backed by an in-memory database. 32 | *

33 | * A fresh database instance will be created for each test method. 34 | */ 35 | public class HiveMetaStoreJUnitRule extends BeejuJUnitRule { 36 | 37 | private static final Logger log = LoggerFactory.getLogger(HiveMetaStoreJUnitRule.class); 38 | 39 | private final HiveMetaStoreCore hiveMetaStoreCore = new HiveMetaStoreCore(core); 40 | 41 | /** 42 | * Create a Hive Metastore with a pre-created database "test_database". 43 | */ 44 | public HiveMetaStoreJUnitRule() { 45 | this("test_database"); 46 | } 47 | 48 | /** 49 | * Create a Hive Metastore with a pre-created database using the provided name. 50 | * 51 | * @param databaseName Database name. 52 | */ 53 | public HiveMetaStoreJUnitRule(String databaseName) { 54 | this(databaseName, null); 55 | } 56 | 57 | /** 58 | * Create a Hive Metastore with a pre-created database using the provided name and configuration. 59 | * 60 | * @param databaseName Database name. 61 | * @param preConfiguration Hive configuration properties that will be set prior to BeeJU potentially overriding these 62 | * with its defaults. 63 | */ 64 | public HiveMetaStoreJUnitRule(String databaseName, Map preConfiguration) { 65 | super(databaseName, preConfiguration); 66 | } 67 | 68 | /** 69 | * Create a Hive Metastore with a pre-created database using the provided name and configuration. 70 | * 71 | * @param databaseName Database name. 72 | * @param preConfiguration Hive configuration properties that will be set prior to BeeJU potentially overriding these 73 | * with its defaults. 74 | * @param postConfiguration Hive configuration properties that will be set to override BeeJU's defaults. 75 | */ 76 | public HiveMetaStoreJUnitRule( 77 | String databaseName, 78 | Map preConfiguration, 79 | Map postConfiguration) { 80 | super(databaseName, preConfiguration, postConfiguration); 81 | } 82 | 83 | @Override 84 | public void starting(Description description) { 85 | System.clearProperty(CONNECT_URL_KEY.getVarname()); 86 | super.starting(description); 87 | try { 88 | hiveMetaStoreCore.initialise(); 89 | } catch (InterruptedException | ExecutionException e) { 90 | throw new RuntimeException("Error initialising metastore core", e); 91 | } 92 | } 93 | 94 | @Override 95 | public void finished(Description description) { 96 | try { 97 | hiveMetaStoreCore.shutdown(); 98 | } catch (Throwable t) { 99 | log.warn("Error shutting down metastore core", t); 100 | } 101 | super.finished(description); 102 | } 103 | 104 | /** 105 | * @return the {@link com.hotels.beeju.core.HiveMetaStoreCore#client()}. 106 | */ 107 | public HiveMetaStoreClient client() { 108 | return hiveMetaStoreCore.client(); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/core/ThriftHiveMetaStoreCore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.core; 17 | 18 | import java.net.ServerSocket; 19 | import java.util.concurrent.ExecutorService; 20 | import java.util.concurrent.Executors; 21 | import java.util.concurrent.TimeUnit; 22 | import java.util.concurrent.atomic.AtomicBoolean; 23 | import java.util.concurrent.locks.Condition; 24 | import java.util.concurrent.locks.Lock; 25 | import java.util.concurrent.locks.ReentrantLock; 26 | 27 | import org.apache.hadoop.hive.conf.HiveConf; 28 | import org.apache.hadoop.hive.metastore.HiveMetaStore; 29 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 30 | import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge; 31 | import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge23; 32 | import org.slf4j.Logger; 33 | import org.slf4j.LoggerFactory; 34 | 35 | public class ThriftHiveMetaStoreCore { 36 | 37 | private static final Logger LOG = LoggerFactory.getLogger(ThriftHiveMetaStoreCore.class); 38 | private final ExecutorService thriftServer; 39 | private final BeejuCore beejuCore; 40 | private int thriftPort = -1; 41 | 42 | public ThriftHiveMetaStoreCore(BeejuCore beejuCore) { 43 | this.beejuCore = beejuCore; 44 | thriftServer = Executors.newSingleThreadExecutor(); 45 | } 46 | 47 | public void initialise() throws Exception { 48 | final Lock startLock = new ReentrantLock(); 49 | final Condition startCondition = startLock.newCondition(); 50 | final AtomicBoolean startedServing = new AtomicBoolean(); 51 | int socketPort = 0; 52 | if (thriftPort > 0) { 53 | socketPort = thriftPort; 54 | } 55 | try (ServerSocket socket = new ServerSocket(socketPort)) { 56 | thriftPort = socket.getLocalPort(); 57 | } 58 | beejuCore.setHiveVar(HiveConf.ConfVars.METASTOREURIS, getThriftConnectionUri()); 59 | final HiveConf hiveConf = new HiveConf(beejuCore.conf(), HiveMetaStoreClient.class); 60 | thriftServer.execute(() -> { 61 | try { 62 | HadoopThriftAuthBridge bridge = HadoopThriftAuthBridge23.getBridge(); 63 | HiveMetaStore.startMetaStore(thriftPort, bridge, hiveConf, startLock, startCondition, startedServing); 64 | } catch (Throwable e) { 65 | LOG.error("Unable to start a Thrift server for Hive Metastore", e); 66 | } 67 | }); 68 | int i = 0; 69 | while (i++ < 3) { 70 | startLock.lock(); 71 | try { 72 | if (startCondition.await(1, TimeUnit.MINUTES)) { 73 | break; 74 | } 75 | } finally { 76 | startLock.unlock(); 77 | } 78 | if (i == 3) { 79 | throw new RuntimeException("Maximum number of tries reached whilst waiting for Thrift server to be ready"); 80 | } 81 | } 82 | } 83 | 84 | public void shutdown() { 85 | thriftServer.shutdown(); 86 | } 87 | 88 | /** 89 | * @return The Thrift connection string for the Metastore service. 90 | */ 91 | public String getThriftConnectionUri() { 92 | return "thrift://localhost:" + thriftPort; 93 | } 94 | 95 | /** 96 | * @return The port used for the Thrift Metastore service. 97 | */ 98 | public int getThriftPort() { 99 | return thriftPort; 100 | } 101 | 102 | /** 103 | * @param thriftPort The Port to use for the Thrift Hive metastore, if not set then a port number will automatically be allocated. 104 | */ 105 | public void setThriftPort(int thriftPort) { 106 | if (thriftPort < 0) { 107 | throw new IllegalArgumentException("Thrift port must be >=0, not " + thriftPort); 108 | } 109 | this.thriftPort = thriftPort; 110 | } 111 | 112 | public String getDatabaseName(){ 113 | return beejuCore.databaseName(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/ThriftHiveMetaStoreJUnitRule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju; 17 | 18 | import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.CONNECT_URL_KEY; 19 | 20 | import java.util.Map; 21 | 22 | import org.junit.runner.Description; 23 | 24 | import com.hotels.beeju.core.ThriftHiveMetaStoreCore; 25 | 26 | /** 27 | * A JUnit Rule that creates a Hive Metastore Thrift service backed by a Hive Metastore using an HSQLDB in-memory 28 | * database. 29 | *

30 | * A fresh database instance will be created for each test method. 31 | *

32 | */ 33 | public class ThriftHiveMetaStoreJUnitRule extends HiveMetaStoreJUnitRule { 34 | 35 | private ThriftHiveMetaStoreCore thriftHiveMetaStoreCore = new ThriftHiveMetaStoreCore(core); 36 | 37 | /** 38 | * Create a Thrift Hive Metastore service with a pre-created database "test_database". 39 | */ 40 | public ThriftHiveMetaStoreJUnitRule() { 41 | this("test_database"); 42 | } 43 | 44 | /** 45 | * Create a Thrift Hive Metastore service with a pre-created database using the provided name. 46 | * 47 | * @param databaseName Database name. 48 | */ 49 | public ThriftHiveMetaStoreJUnitRule(String databaseName) { 50 | this(databaseName, null); 51 | } 52 | 53 | /** 54 | * Create a Thrift Hive Metastore service with a pre-created database using the provided name and configuration. 55 | * 56 | * @param databaseName Database name. 57 | * @param preConfiguration Hive configuration properties that will be set prior to BeeJU potentially overriding these 58 | * with its defaults. 59 | */ 60 | public ThriftHiveMetaStoreJUnitRule(String databaseName, Map preConfiguration) { 61 | super(databaseName, preConfiguration); 62 | } 63 | 64 | /** 65 | * Create a Thrift Hive Metastore service with a pre-created database using the provided name and configuration. 66 | * 67 | * @param databaseName Database name. 68 | * @param preConfiguration Hive configuration properties that will be set prior to BeeJU potentially overriding these 69 | * with its defaults. 70 | * @param postConfiguration Hive configuration properties that will be set to override BeeJU's defaults. 71 | */ 72 | public ThriftHiveMetaStoreJUnitRule( 73 | String databaseName, 74 | Map preConfiguration, 75 | Map postConfiguration) { 76 | super(databaseName, preConfiguration, postConfiguration); 77 | } 78 | 79 | @Override 80 | public void starting(Description description) { 81 | System.clearProperty(CONNECT_URL_KEY.getVarname()); 82 | try { 83 | thriftHiveMetaStoreCore.initialise(); 84 | } catch (Exception e) { 85 | throw new RuntimeException(e); 86 | } 87 | super.starting(description); 88 | } 89 | 90 | @Override 91 | public void finished(Description description) { 92 | try { 93 | thriftHiveMetaStoreCore.shutdown(); 94 | } finally { 95 | super.finished(description); 96 | } 97 | } 98 | 99 | /** 100 | * @return {@link com.hotels.beeju.core.ThriftHiveMetaStoreCore#getThriftConnectionUri()}. 101 | */ 102 | public String getThriftConnectionUri() { 103 | return thriftHiveMetaStoreCore.getThriftConnectionUri(); 104 | } 105 | 106 | /** 107 | * @return {@link com.hotels.beeju.core.ThriftHiveMetaStoreCore#getThriftPort()} 108 | */ 109 | public int getThriftPort() { 110 | return thriftHiveMetaStoreCore.getThriftPort(); 111 | } 112 | 113 | /** 114 | * @param thriftPort The Port to use for the Thrift Hive metastore, if not set then a port number will automatically 115 | * be allocated. 116 | */ 117 | public void setThriftPort(int thriftPort) { 118 | thriftHiveMetaStoreCore.setThriftPort(thriftPort); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/extensions/ThriftHiveMetaStoreJUnitExtensionTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.extensions; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.hamcrest.MatcherAssert.assertThat; 20 | import static org.junit.jupiter.api.Assertions.assertThrows; 21 | 22 | import java.io.File; 23 | import java.util.Collections; 24 | import java.util.List; 25 | import java.util.Map; 26 | 27 | import org.apache.hadoop.hive.conf.HiveConf; 28 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 29 | import org.apache.hadoop.hive.metastore.api.AlreadyExistsException; 30 | import org.apache.hadoop.hive.metastore.api.Database; 31 | import org.apache.hadoop.hive.metastore.api.InvalidObjectException; 32 | import org.junit.jupiter.api.Test; 33 | import org.junit.jupiter.api.extension.RegisterExtension; 34 | 35 | public class ThriftHiveMetaStoreJUnitExtensionTest { 36 | 37 | @RegisterExtension 38 | ThriftHiveMetaStoreJUnitExtension defaultDbExtension = new ThriftHiveMetaStoreJUnitExtension(); 39 | 40 | @RegisterExtension 41 | ThriftHiveMetaStoreJUnitExtension customDbExtension = new ThriftHiveMetaStoreJUnitExtension("my_test_database"); 42 | 43 | @RegisterExtension 44 | ThriftHiveMetaStoreJUnitExtension customPropertiesExtension = new ThriftHiveMetaStoreJUnitExtension( 45 | "custom_props_database", customConfProperties()); 46 | 47 | private void assertExtensionInitialised(ThriftHiveMetaStoreJUnitExtension hive) throws Exception { 48 | String databaseName = hive.databaseName(); 49 | 50 | Database database = hive.client().getDatabase(databaseName); 51 | 52 | assertThat(database.getName(), is(databaseName)); 53 | File databaseFolder = new File(hive.getWarehouseDirectory(), databaseName); 54 | assertThat(new File(database.getLocationUri()) + "/", is(databaseFolder.toURI().toString())); 55 | 56 | assertThat(hive.getThriftConnectionUri(), is("thrift://localhost:" + hive.getThriftPort())); 57 | HiveConf conf = new HiveConf(hive.conf()); 58 | conf.setVar(HiveConf.ConfVars.METASTOREURIS, hive.getThriftConnectionUri()); 59 | HiveMetaStoreClient client = new HiveMetaStoreClient(conf); 60 | try { 61 | List databases = client.getAllDatabases(); 62 | assertThat(databases.size(), is(2)); 63 | assertThat(databases.get(0), is("default")); 64 | assertThat(databases.get(1), is(databaseName)); 65 | } finally { 66 | client.close(); 67 | } 68 | } 69 | 70 | private Map customConfProperties() { 71 | return Collections.singletonMap("my.custom.key", "my.custom.value"); 72 | } 73 | 74 | @Test 75 | public void hiveDefaultName() throws Exception { 76 | assertExtensionInitialised(defaultDbExtension); 77 | } 78 | 79 | @Test 80 | public void hiveCustomName() throws Exception { 81 | assertExtensionInitialised(customDbExtension); 82 | } 83 | 84 | @Test 85 | public void customProperties() { 86 | HiveConf hiveConf = customPropertiesExtension.conf(); 87 | assertThat(hiveConf.get("my.custom.key"), is("my.custom.value")); 88 | } 89 | 90 | @Test 91 | public void createExistingDatabase() { 92 | assertThrows(AlreadyExistsException.class, 93 | () -> defaultDbExtension.createDatabase(defaultDbExtension.databaseName())); 94 | } 95 | 96 | @Test 97 | public void createDatabaseNullName() { 98 | assertThrows(NullPointerException.class, () -> defaultDbExtension.createDatabase(null)); 99 | } 100 | 101 | @Test 102 | public void createDatabaseInvalidName() { 103 | assertThrows(InvalidObjectException.class, () -> defaultDbExtension.createDatabase("")); 104 | } 105 | 106 | @Test 107 | public void thriftPort() { 108 | int thriftPort = 3333; 109 | defaultDbExtension.setThriftPort(thriftPort); 110 | assertThat(defaultDbExtension.getThriftPort(), is(thriftPort)); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/ThriftHiveMetaStoreJUnitRuleTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.junit.Assert.assertFalse; 20 | import static org.junit.Assert.assertThat; 21 | import static org.junit.Assert.assertTrue; 22 | 23 | import java.io.File; 24 | import java.util.Collections; 25 | import java.util.HashMap; 26 | import java.util.List; 27 | import java.util.Map; 28 | 29 | import org.apache.hadoop.hive.conf.HiveConf; 30 | import org.apache.hadoop.hive.conf.HiveConf.ConfVars; 31 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 32 | import org.apache.hadoop.hive.metastore.api.AlreadyExistsException; 33 | import org.apache.hadoop.hive.metastore.api.Database; 34 | import org.apache.hadoop.hive.metastore.api.InvalidObjectException; 35 | import org.apache.thrift.TException; 36 | import org.junit.AfterClass; 37 | import org.junit.Before; 38 | import org.junit.Rule; 39 | import org.junit.Test; 40 | 41 | public class ThriftHiveMetaStoreJUnitRuleTest { 42 | 43 | public @Rule ThriftHiveMetaStoreJUnitRule defaultDbRule = new ThriftHiveMetaStoreJUnitRule(); 44 | public @Rule ThriftHiveMetaStoreJUnitRule customDbRule = new ThriftHiveMetaStoreJUnitRule("my_test_database"); 45 | public @Rule ThriftHiveMetaStoreJUnitRule customPropertiesRule = new ThriftHiveMetaStoreJUnitRule("custom_props_database", customConfProperties()); 46 | 47 | private static File defaultTempRoot; 48 | private static File customTempRoot; 49 | 50 | private Map customConfProperties() { 51 | return Collections.singletonMap("my.custom.key", "my.custom.value"); 52 | } 53 | 54 | @Before 55 | public void before() { 56 | defaultTempRoot = defaultDbRule.tempDir(); 57 | assertTrue(defaultTempRoot.exists()); 58 | customTempRoot = customDbRule.tempDir(); 59 | assertTrue(customTempRoot.exists()); 60 | } 61 | 62 | @Test 63 | public void hiveDefaultName() throws Exception { 64 | assertRuleInitialised(defaultDbRule); 65 | } 66 | 67 | @Test 68 | public void hiveCustomName() throws Exception { 69 | assertRuleInitialised(customDbRule); 70 | } 71 | 72 | private void assertRuleInitialised(ThriftHiveMetaStoreJUnitRule hive) throws Exception { 73 | String databaseName = hive.databaseName(); 74 | 75 | Database database = hive.client().getDatabase(databaseName); 76 | 77 | assertThat(database.getName(), is(databaseName)); 78 | File databaseFolder = new File(hive.warehouseDir(), databaseName); 79 | assertThat(new File(database.getLocationUri()) + "/", is(databaseFolder.toURI().toString())); 80 | 81 | assertThat(hive.getThriftConnectionUri(), is("thrift://localhost:" + hive.getThriftPort())); 82 | HiveConf conf = new HiveConf(hive.conf()); 83 | conf.setVar(ConfVars.METASTOREURIS, hive.getThriftConnectionUri()); 84 | HiveMetaStoreClient client = new HiveMetaStoreClient(conf); 85 | try { 86 | List databases = client.getAllDatabases(); 87 | assertThat(databases.size(), is(2)); 88 | assertThat(databases.get(0), is("default")); 89 | assertThat(databases.get(1), is(databaseName)); 90 | } finally { 91 | client.close(); 92 | } 93 | } 94 | 95 | @Test 96 | public void customProperties() { 97 | Map conf = new HashMap<>(); 98 | conf.put("my.custom.key", "my.custom.value"); 99 | HiveConf hiveConf = customPropertiesRule.conf(); 100 | assertThat(hiveConf.get("my.custom.key"), is("my.custom.value")); 101 | } 102 | 103 | @Test(expected = AlreadyExistsException.class) 104 | public void createExistingDatabase() throws TException { 105 | defaultDbRule.createDatabase(defaultDbRule.databaseName()); 106 | } 107 | 108 | @Test(expected = NullPointerException.class) 109 | public void createDatabaseNullName() throws TException { 110 | defaultDbRule.createDatabase(null); 111 | } 112 | 113 | @Test(expected = InvalidObjectException.class) 114 | public void createDatabaseInvalidName() throws TException { 115 | defaultDbRule.createDatabase(""); 116 | } 117 | 118 | @Test 119 | public void thriftPort() { 120 | int thriftPort = 3333; 121 | defaultDbRule.setThriftPort(thriftPort); 122 | assertThat(defaultDbRule.getThriftPort(), is(thriftPort)); 123 | } 124 | 125 | @AfterClass 126 | public static void afterClass() { 127 | assertFalse(defaultTempRoot.exists()); 128 | assertFalse(customTempRoot.exists()); 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | ## [5.0.3] - 2025-07-21 3 | ### Changed 4 | - Switched to groupId `com.expediagroup` 5 | 6 | ## [5.0.1] - 2024-10-03 7 | ### Changed 8 | - Nothing changed, please ignore. 9 | 10 | ## [5.0.0] - 2021-03-01 11 | ### Changed 12 | - Hive version updated to `3.1.2` (was `2.3.7`) and Hadoop version updated to `3.1.0` (was `2.7.2`). 13 | 14 | ## [4.0.0] - 2021-02-09 15 | ### Fixed 16 | - Intermediate temporary folders now cleaned up as part of test lifecycle. 17 | - `HiveMetaStoreCore` performs a null check before attempting to close its metastore client. 18 | 19 | ### Changed 20 | - Hive version updated to `2.3.8` (was `2.3.7`). 21 | - `hive-exec` dependency changed to use `core` classifier to allow source code retrieval for easier debugging. 22 | - Hive's `METASTORE_CONNECTION_POOLING_TYPE` is now set to `"NONE"`. 23 | - Hive's `HIVESTATSAUTOGATHER` is now set to `false`. 24 | - Hive's `HIVE_SERVER2_LOGGING_OPERATION_ENABLED` is now set to `false`. 25 | - Various Derby, scratch and similar folders now configured to use a base temporary folder. 26 | - JUnit4 Rules now extend `TestWatcher` instead of `ExternalResource` to allow cleanup of temporary folders on test failures. 27 | - `BeejuCore` `tempDir()` returns base temporary test folder instead of temporary Hive warehouse dir. 28 | - `BeejuCore` returns temporary Hive warehouse dir via `warehouseDir()`. 29 | - JUnit5 Extensions `getTempDirectory()` returns base temporary test folder instead of temporary Hive warehouse dir. 30 | - JUnit5 Extensions return temporary Hive warehouse dir via `getWarehouseDirectory()`. 31 | - JUnit4 Rules `tempDir()` returns base temporary test folder instead of temporary Hive warehouse dir. 32 | - JUnit4 rules return temporary Hive warehouse dir via `warehouseDir()`. 33 | - `hotels-oss-parent` version updated to `6.1.0` (was `5.0.0`) to enable building with Java 11. 34 | 35 | ## [3.3.0] - 2020-10-23 36 | ### Changed 37 | - Allow passing in of "pre" and "post" configuration values so that BeeJU's defaults can be overridden. 38 | - JUnit version updated to `5.7.0` (was `5.5.2`). 39 | - `hotels-oss-parent` version updated to `5.0.0` (was `4.2.0`). 40 | 41 | ## [3.2.0] - 2020-10-14 42 | ### Added 43 | - Support for setting Thrift Hive Metastore port in tests. 44 | - A `ThriftHiveMetaStoreApp` which can be used to run the the Thrift Hive Metastore service locally. 45 | 46 | ### Changed 47 | - Changed visibility of `createDatabase()` method in `BeejuJUnitRule` from default to public (for external usage). 48 | 49 | ## [3.1.0] - 2020-05-13 50 | ### Changed 51 | - JUnit version updated to `5.5.2` (was `5.5.1`). 52 | - Depend on `junit-jupiter` (was `junit-jupiter-api`). 53 | - `hotels-oss-parent` version updated to `4.2.0` (was `4.1.0`). 54 | - Upgraded version of `hive.version` to `2.3.7` (was `2.3.4`). Allows BeeJU to be used on JDK>=9. 55 | 56 | ### Added 57 | - Support for setting Hive conf using arbitrary string as conf key. 58 | 59 | ## [3.0.1] - 2019-09-27 60 | ### Changed 61 | - `HiveMetaStoreJUnitExtension` and `HiveServer2JUnitExtension` constructors made public to allow access to classes outside of the extensions package. 62 | 63 | ## [3.0.0] - 2019-09-06 64 | ### Changed 65 | - JDK version upgrade to 1.8 (was 1.7). 66 | 67 | ### Added 68 | - JUnit5 extension class equivalents for all BeeJU Rules. 69 | 70 | ## [2.0.0] - 2019-09-02 71 | ### Added 72 | - Support for JUnit5 using `migration-support` dependency. NOTE - the transitive dependency for JUnit4 from Beeju has been removed so you must depend on it in your own POM. 73 | 74 | ### Changed 75 | - Excluded `org.pentaho.pentaho-aggdesigner-algorithm` dependency as it's not available in Maven Central. 76 | - `hotels-oss-parent` version updated to 4.1.0 (was 4.0.1). 77 | 78 | ## [1.3.2] - 2019-07-10 79 | ### Changed 80 | - Release process now uses HTTPS (was SSH) from build slaves to GitHub, no changes to code or functionality. 81 | 82 | ## [1.3.1] - 2019-04-11 83 | ### Changed 84 | - `hotels-oss-parent` version updated to 4.0.1 (was 2.3.5). 85 | - Refactored project to remove checkstyle and findbugs warnings, which does not impact functionality. 86 | 87 | ## [1.3.0] - 2018-12-18 88 | ### Changed 89 | - `log4j-slf4j-impl` transitive dependency excluded. See [#17](https://github.com/ExpediaGroup/beeju/issues/17). 90 | - Hive version upgraded to 2.3.4 (was 2.3.0) and transitive dependencies on HBase which in turn depended on JDK tools 1.7 excluded. See [#19](https://github.com/ExpediaGroup/beeju/issues/19). 91 | - `hotels-oss` parent pom upgraded to 2.3.3 (was 2.0.6). See [#19](https://github.com/ExpediaGroup/beeju/issues/19). 92 | 93 | ## [1.2.1] - 2017-11-09 94 | ### Changed 95 | - Change `ConfVars` added in Hive 2.x to their equivalent string. 96 | 97 | ## [1.2.0] - 2017-10-03 98 | ### Changed 99 | - Upgrade to Hive-2.3.0. 100 | - Upgrade parent POM to 2.0.3. 101 | 102 | ### Added 103 | - The rules now accept Hive configuration properties at construction time. 104 | 105 | ## [1.1.3] - 2017-09-25 106 | ### Changed 107 | - Depend on latest parent with test.arguments build parameter. 108 | 109 | ## [1.1.0] - 2017-08-18 110 | ### Changed 111 | - Upgrade to Hive-2.1.1, required a switch from HsqlDB to Derby (Hive no longer seems to support HsqlDB). 112 | 113 | ## [1.0.2] 114 | ### Changed 115 | - Upgrade parent POM to 1.1.1. 116 | 117 | ## [1.0.1] 118 | ### Added 119 | - Addition of `HiveServer2JUnitRule` rule to test against Hive Metastore using the JDBC API. 120 | 121 | ## [1.0.0] 122 | ### Added 123 | - First release: `HiveMetaStoreJUnitRule` and `ThriftHiveMetaStoreJUnitRule` rules to test a Hive Metastore connecting directly to the database and the Thrift API respectively. 124 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/core/BeejuCoreTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.core; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.hamcrest.CoreMatchers.notNullValue; 20 | import static org.hamcrest.MatcherAssert.assertThat; 21 | import static org.junit.jupiter.api.Assertions.assertFalse; 22 | 23 | import java.io.IOException; 24 | import java.nio.file.Files; 25 | import java.util.HashMap; 26 | import java.util.Map; 27 | 28 | import org.apache.derby.jdbc.EmbeddedDriver; 29 | import org.apache.hadoop.hive.conf.HiveConf; 30 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 31 | import org.apache.hadoop.hive.metastore.api.Database; 32 | import org.junit.jupiter.api.AfterEach; 33 | import org.junit.jupiter.api.Test; 34 | 35 | public class BeejuCoreTest { 36 | 37 | private String preKey = "my.custom.pre.key"; 38 | private String preValue = "my.custom.pre.value"; 39 | private String postKey = "my.custom.post.key"; 40 | private String postValue = "my.custom.post.value"; 41 | private String coreOverrideValue = "user-that-core-will-override"; 42 | private String confOverrideValue = "password-that-will-override-core"; 43 | 44 | private final BeejuCore defaultCore = new BeejuCore(); 45 | private final BeejuCore dbNameCore = new BeejuCore("test_db"); 46 | private final BeejuCore dbNameAndMapConfCore = new BeejuCore("test_db_2", createPreConfigurationMap(), 47 | createPostConfigurationMap()); 48 | private final BeejuCore dbNameAndHiveConfCore = new BeejuCore("test_db_2", createPreHiveConf(), createPostHiveConf()); 49 | 50 | private Map createPreConfigurationMap() { 51 | Map conf = new HashMap<>(); 52 | conf.put(preKey, preValue); 53 | conf.put(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME.toString(), coreOverrideValue); 54 | return conf; 55 | } 56 | 57 | private Map createPostConfigurationMap() { 58 | Map conf = new HashMap<>(); 59 | conf.put(postKey, postValue); 60 | conf.put(HiveConf.ConfVars.METASTOREPWD.toString(), confOverrideValue); 61 | return conf; 62 | } 63 | 64 | private HiveConf createPreHiveConf() { 65 | HiveConf conf = new HiveConf(); 66 | conf.clear(); 67 | conf.set(preKey, preValue); 68 | conf.setVar(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME, coreOverrideValue); 69 | return conf; 70 | } 71 | 72 | private HiveConf createPostHiveConf() { 73 | HiveConf conf = new HiveConf(); 74 | conf.clear(); 75 | conf.set(postKey, postValue); 76 | conf.setVar(HiveConf.ConfVars.METASTOREPWD, confOverrideValue); 77 | return conf; 78 | } 79 | 80 | @AfterEach 81 | public void cleanUp() { 82 | defaultCore.cleanUp(); 83 | dbNameCore.cleanUp(); 84 | dbNameAndMapConfCore.cleanUp(); 85 | dbNameAndHiveConfCore.cleanUp(); 86 | } 87 | 88 | @Test 89 | public void initialisedDefaultConstructor() { 90 | assertThat(defaultCore.databaseName(), is("test_database")); 91 | } 92 | 93 | @Test 94 | public void initialisedDbNameConstructor() { 95 | assertThat(dbNameCore.databaseName(), is("test_db")); 96 | } 97 | 98 | @Test 99 | public void initialisedDbNameAndMapConfConstructor() { 100 | assertThat(dbNameAndMapConfCore.databaseName(), is("test_db_2")); 101 | assertThat(dbNameAndMapConfCore.conf().get(preKey), is(preValue)); 102 | assertThat(dbNameAndMapConfCore.conf().get(postKey), is(postValue)); 103 | // below still set to BeeJU default as pre-config not overridden 104 | assertThat(dbNameAndMapConfCore.conf().getVar(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME), is("db_user")); 105 | // below overridden by post-config 106 | assertThat(dbNameAndMapConfCore.conf().getVar(HiveConf.ConfVars.METASTOREPWD), is(confOverrideValue)); 107 | } 108 | 109 | @Test 110 | public void initialisedDbNameAndHiveConfConstructor() { 111 | assertThat(dbNameAndHiveConfCore.databaseName(), is("test_db_2")); 112 | assertThat(dbNameAndHiveConfCore.conf().get(preKey), is(preValue)); 113 | assertThat(dbNameAndHiveConfCore.conf().get(postKey), is(postValue)); 114 | // below still set to BeeJU default as pre-config not overridden 115 | assertThat(dbNameAndHiveConfCore.conf().getVar(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME), is("db_user")); 116 | // below overridden by post-config 117 | assertThat(dbNameAndHiveConfCore.conf().getVar(HiveConf.ConfVars.METASTOREPWD), is(confOverrideValue)); 118 | } 119 | 120 | @Test 121 | public void createDirectory() { 122 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTOREWAREHOUSE), is(defaultCore.warehouseDir().toString())); 123 | } 124 | 125 | @Test 126 | public void deleteDirectory() throws IOException { 127 | BeejuCore testCore = new BeejuCore(); 128 | testCore.cleanUp(); 129 | assertFalse(Files.exists(testCore.warehouseDir())); 130 | assertFalse(Files.exists(testCore.tempDir())); 131 | } 132 | 133 | @Test 134 | public void setHiveVar() { 135 | defaultCore.setHiveVar(HiveConf.ConfVars.METASTORECONNECTURLKEY, "test"); 136 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTORECONNECTURLKEY), is("test")); 137 | } 138 | 139 | @Test 140 | public void setHiveConf() { 141 | defaultCore.setHiveConf("my.custom.key", "test"); 142 | assertThat(defaultCore.conf().get("my.custom.key"), is("test")); 143 | } 144 | 145 | @Test 146 | public void setHiveIntVar() { 147 | defaultCore.setHiveIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT, 00000); 148 | assertThat(defaultCore.conf().getIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT), is(00000)); 149 | } 150 | 151 | @Test 152 | public void checkConfig() { 153 | assertThat(defaultCore.driverClassName(), is(EmbeddedDriver.class.getName())); 154 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTORECONNECTURLKEY), is(defaultCore.connectionURL())); 155 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTORE_CONNECTION_DRIVER), 156 | is(defaultCore.driverClassName())); 157 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME), is("db_user")); 158 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTOREPWD), is("db_password")); 159 | assertThat(defaultCore.conf().getBoolVar(HiveConf.ConfVars.HMSHANDLERFORCERELOADCONF), is(true)); 160 | assertThat(defaultCore.conf().get("datanucleus.schema.autoCreateAll"), is("true")); 161 | assertThat(defaultCore.conf().get("hive.metastore.schema.verification"), is("false")); 162 | assertThat(defaultCore.conf().get("hcatalog.hive.client.cache.disabled"), is("true")); 163 | } 164 | 165 | @Test 166 | public void createDatabase() throws Exception { 167 | String databaseName = "Another_DB"; 168 | 169 | defaultCore.createDatabase(databaseName); 170 | HiveMetaStoreClient client = defaultCore.newClient(); 171 | Database db = client.getDatabase(databaseName); 172 | client.close(); 173 | 174 | assertThat(db, is(notNullValue())); 175 | assertThat(db.getName(), is(databaseName.toLowerCase())); 176 | assertThat(db.getLocationUri(), is(String.format("file:%s/%s", defaultCore.warehouseDir(), databaseName))); 177 | } 178 | 179 | } 180 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | com.expediagroup 7 | eg-oss-parent 8 | 3.0.1 9 | 10 | 11 | com.expediagroup 12 | beeju 13 | beeju 14 | jar 15 | 5.0.4-SNAPSHOT 16 | 2015 17 | 18 | 19 | scm:git:https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ExpediaGroup/beeju.git 20 | scm:git:https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ExpediaGroup/beeju.git 21 | https://github.com/ExpediaGroup/beeju 22 | HEAD 23 | 24 | 25 | 26 | 3.1.0 27 | 3.1.2 28 | 0.9.1 29 | 1.8 30 | 5.7.0 31 | 1.3.2 32 | 2.5.3 33 | 34 | 35 | 36 | 37 | 38 | com.esotericsoftware 39 | kryo-shaded 40 | 3.0.3 41 | 42 | 43 | org.apache.hadoop 44 | hadoop-common 45 | ${hadoop.version} 46 | 47 | 48 | org.apache.hadoop 49 | hadoop-mapreduce-client-core 50 | ${hadoop.version} 51 | 52 | 53 | org.apache.hive 54 | hive-common 55 | ${hive.version} 56 | 57 | 58 | org.apache.logging.log4j 59 | log4j-slf4j-impl 60 | 61 | 62 | 63 | 64 | org.apache.hive 65 | hive-exec 66 | ${hive.version} 67 | core 68 | 69 | 70 | org.apache.logging.log4j 71 | log4j-slf4j-impl 72 | 73 | 74 | org.pentaho 75 | pentaho-aggdesigner-algorithm 76 | 77 | 78 | 79 | 80 | org.apache.hive 81 | hive-metastore 82 | ${hive.version} 83 | 84 | 85 | org.apache.hbase 86 | hbase-client 87 | 88 | 89 | 90 | 91 | org.apache.hive 92 | hive-service 93 | ${hive.version} 94 | 95 | 96 | org.apache.hbase 97 | * 98 | 99 | 100 | org.pentaho 101 | pentaho-aggdesigner-algorithm 102 | 103 | 104 | 105 | 106 | org.apache.hive 107 | hive-jdbc 108 | ${hive.version} 109 | 110 | 111 | org.apache.tez 112 | tez-common 113 | ${tez.version} 114 | 115 | 116 | org.apache.tez 117 | tez-dag 118 | ${tez.version} 119 | 120 | 121 | org.hamcrest 122 | hamcrest 123 | 2.2 124 | provided 125 | 126 | 127 | junit 128 | junit 129 | 4.13.1 130 | provided 131 | 132 | 133 | org.hamcrest 134 | hamcrest-core 135 | 136 | 137 | 138 | 139 | org.junit.jupiter 140 | junit-jupiter 141 | ${junit.jupiter.version} 142 | provided 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | com.mycila 151 | license-maven-plugin 152 | ${license.maven.plugin.version} 153 | 154 | 155 | 156 | src/main/java/com/hotels/beeju/core/BeejuCore.java 157 | src/main/java/com/hotels/beeju/hiveserver2/RelaxedSQLStdHiveAuthorizerFactory.java 158 | 159 | 160 | 161 | 162 | org.sonatype.plugins 163 | nexus-staging-maven-plugin 164 | ${nexus.staging.maven.plugin.version} 165 | true 166 | 167 | sonatype-nexus-staging 168 | https://oss.sonatype.org/ 169 | true 170 | 30 171 | 172 | 173 | 174 | org.apache.maven.plugins 175 | maven-release-plugin 176 | ${maven.release.plugin.version} 177 | 178 | 179 | 180 | 181 | 182 | 193 | 194 | org.apache.maven.plugins 195 | maven-surefire-plugin 196 | 2.22.2 197 | 198 | 199 | 200 | org.junit.platform 201 | junit-platform-surefire-provider 202 | ${junit.platform.version} 203 | 204 | 205 | 206 | org.junit.vintage 207 | junit-vintage-engine 208 | ${junit.jupiter.version} 209 | 210 | 211 | 212 | org.junit.jupiter 213 | junit-jupiter-engine 214 | ${junit.jupiter.version} 215 | 216 | 217 | 218 | 219 | org.jacoco 220 | jacoco-maven-plugin 221 | 222 | 223 | 224 | org/apache/hadoop/hive/ql/parse/HiveParser 225 | 226 | 227 | 228 | 229 | 230 | 231 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BeeJU 2 | ![Hive Bee JUnit.](logo.png "Project logo of a beeju bee.") 3 | 4 | # Start using 5 | You can obtain BeeJU from Maven Central: 6 | 7 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.expediagroup/beeju/badge.svg?subject=com.ls:beeju)](https://maven-badges.herokuapp.com/maven-central/com.expediagroup/beeju) ![build](https://github.com/ExpediaGroup/beeju/workflows/build/badge.svg?event=push) [![Coverage Status](https://coveralls.io/repos/github/ExpediaGroup/beeju/badge.svg?branch=main)](https://coveralls.io/github/ExpediaGroup/beeju) ![GitHub license](https://img.shields.io/github/license/ExpediaGroup/beeju.svg) 8 | 9 | # Overview 10 | BeeJU provides [JUnit5 Extensions](https://junit.org/junit5/docs/current/user-guide/#extensions) that can be used to write test code that tests [Hive](https://hive.apache.org/). The JUnit lifecycle extension points are a means to provide resources in a test and automatically tear them down when the life cycle of a test ends. 11 | This project is currently built with and tested against Hive 2.3.x (and minor versions back to Hive 1.2.1) but is most likely compatible with older and newer versions of Hive. The available JUnit extensions are explained in more detail below. 12 | 13 | BeeJU also provides [JUnit4 Rules](http://junit.org/junit4/javadoc/4.12/org/junit/Rule.html) that can be used in the same manner as the JUnit5 extensions. Examples of how to use both options can be found below. 14 | # Usage 15 | The BeeJU JUnit rules and extensions provide a way to run tests that have an underlying requirement to use the Hive Metastore API but don't have the ability to mock the [Hive Metastore Client](https://hive.apache.org/javadocs/r2.3.6/api/index.html). The rules and extensions spin up and tear down an in-memory Metastore which may add a few seconds to the test life cycle so if you require tests to run in the sub-second range this is not for you. 16 | 17 | ## Maven Dependencies 18 | Depend on BeeJU using: 19 | 20 | ```xml 21 | 22 | com.expediagroup 23 | beeju 24 | .... 25 | test 26 | 27 | ``` 28 | 29 | ## Hive version compatibility 30 | 31 | This version of BeeJU is intended for use with Hive 3.1.2. For Hive 2.x support, please use BeeJU 4.0.0. 32 | 33 | ## JUnit5 34 | ### ThriftHiveMetaStoreJUnitExtension 35 | This extension creates an in-memory Hive database and a Thrift Hive Metastore service on top of this. This can then be used to perform Hive Thrift API calls in a test. The extension exposes a Thrift URI that can be injected into the class under test and a Hive Metastore Client which can be used for data setup and assertions. 36 | 37 | Example usage: Class under test creates a table via the Hive Metastore Thrift API. 38 | 39 | @RegisterExtension 40 | public ThriftHiveMetaStoreJUnitExtension hive = new ThriftHiveMetaStoreJUnitExtension("foo_db"); 41 | 42 | @Test 43 | public void example() throws Exception { 44 | ClassUnderTest classUnderTest = new ClassUnderTest(hive.getThriftConnectionUri()); 45 | classUnderTest.createTable("foo_db", "bar_table"); 46 | 47 | assertTrue(hive.client().tableExists("foo_db", "bar_table")); 48 | } 49 | 50 | ### HiveMetaStoreJUnitExtension 51 | This extension creates an in-memory Hive database without a Thrift Hive Metastore service. This can then be used to perform Hive API calls directly (i.e. without going via Hive's Metastore Thrift service) in a test. 52 | 53 | Example usage: Class under test creates a partition using an injected Hive Metastore Client. 54 | 55 | @RegisterExtension 56 | public HiveMetaStoreJUnitExtension hive = new HiveMetaStoreJUnitExtension("foo_db"); 57 | 58 | @Test 59 | public void example() throws Exception { 60 | HiveMetaStoreClient client = hive.client(); 61 | ClassUnderTest classUnderTest = new ClassUnderTest(client); 62 | Table table = new Table(); 63 | table.setDbName("foo_db"); 64 | table.setTableName("bar_table"); 65 | hive.createTable(table); 66 | 67 | classUnderTest.createPartition(client, table); 68 | 69 | assertEquals(1, client.listPartitions("foo_db", "bar_table", (short) 100)); 70 | } 71 | 72 | ### HiveServer2JUnitExtension 73 | This extension creates an in-memory Hive database, a Thrift Hive Metastore service on top of this and a HiveServer2 service. This can then be used to perform Hive JDBC calls in a test. The extension exposes a JDBC URI that can be injected into the class under test and a Hive Metastore Client which can be used for data setup and assertions. 74 | 75 | Example usage: Class under test drops a table via Hive JDBC. 76 | 77 | @RegisterExtension 78 | public HiveServer2JUnitExtension hive = new HiveServer2JUnitExtension("foo_db"); 79 | 80 | @Test 81 | public void example() { 82 | Class.forName(hive.driverClassName()); 83 | try (Connection connection = DriverManager.getConnection(hive.connectionURL()); 84 | Statement statement = connection.createStatement()) { 85 | String createHql = new StringBuilder(256) 86 | .append("CREATE TABLE `foo_db.bar_table`(`id` int, `name` string) ") 87 | .append("ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' ") 88 | .append("STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' ") 89 | .append("OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'") 90 | .toString(); 91 | statement.execute(createHql); 92 | } 93 | 94 | ClassUnderTest classUnderTest = new ClassUnderTest(hive.connectionURL()); 95 | classUnderTest.dropTable("foo_db", "bar_table"); 96 | 97 | HiveMetaStoreClient client = hive.newClient(); 98 | try { 99 | assertFalse(client.tableExists("foo_db", "bar_table")); 100 | } finally { 101 | client.close(); 102 | } 103 | } 104 | 105 | ## JUnit4 106 | For JUnit4, ensure you have the [JUnit4](https://github.com/junit-team/junit4) dependency in your POM, as BeeJU no longer supplies it as a transitive dependency. 107 | 108 | ### ThriftHiveMetaStoreJUnitRule 109 | This rule creates an in-memory Hive database and a Thrift Hive Metastore service on top of this. This can then be used to perform Hive Thrift API calls in a test. The rule exposes a Thrift URI that can be injected into the class under test and a Hive Metastore Client which can be used for data setup and assertions. 110 | 111 | Example `@Rule` usage: Class under test creates a table via the Hive Metastore Thrift API. 112 | 113 | @Rule 114 | public ThriftHiveMetaStoreJUnitRule hive = new ThriftHiveMetaStoreJUnitRule("foo_db"); 115 | 116 | @Test 117 | public void example() throws Exception { 118 | ClassUnderTest classUnderTest = new ClassUnderTest(hive.getThriftConnectionUri()); 119 | classUnderTest.createTable("foo_db", "bar_table"); 120 | 121 | assertTrue(hive.client().tableExists("foo_db", "bar_table")); 122 | } 123 | 124 | ### HiveMetaStoreJUnitRule 125 | This rule creates an in-memory Hive database without a Thrift Hive Metastore service. This can then be used to perform Hive API calls directly (i.e. without going via Hive's Metastore Thrift service) in a test. 126 | 127 | Example `@Rule` usage: Class under test creates a partition using an injected Hive Metastore Client. 128 | 129 | @Rule 130 | public HiveMetaStoreJUnitRule hive = new HiveMetaStoreJUnitRule("foo_db"); 131 | 132 | @Test 133 | public void example() throws Exception { 134 | HiveMetaStoreClient client = hive.client(); 135 | ClassUnderTest classUnderTest = new ClassUnderTest(client); 136 | Table table = new Table(); 137 | table.setDbName("foo_db"); 138 | table.setTableName("bar_table"); 139 | hive.createTable(table); 140 | 141 | classUnderTest.createPartition(client, table); 142 | 143 | assertEquals(1, client.listPartitions("foo_db", "bar_table", (short) 100)); 144 | } 145 | 146 | ### HiveServer2JUnitRule 147 | This rule creates an in-memory Hive database, a Thrift Hive Metastore service on top of this and a HiveServer2 service. This can then be used to perform Hive JDBC calls in a test. The rule exposes a JDBC URI that can be injected into the class under test and a Hive Metastore Client which can be used for data setup and assertions. 148 | 149 | Example `@Rule` usage: Class under test drops a table via Hive JDBC. 150 | 151 | @Rule 152 | public HiveServer2JUnitRule hive = new HiveServer2JUnitRule("foo_db"); 153 | 154 | @Test 155 | public void example() { 156 | Class.forName(hive.driverClassName()); 157 | try (Connection connection = DriverManager.getConnection(hive.connectionURL()); 158 | Statement statement = connection.createStatement()) { 159 | String createHql = new StringBuilder(256) 160 | .append("CREATE TABLE `foo_db.bar_table`(`id` int, `name` string) ") 161 | .append("ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' ") 162 | .append("STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' ") 163 | .append("OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'") 164 | .toString(); 165 | statement.execute(createHql); 166 | } 167 | 168 | ClassUnderTest classUnderTest = new ClassUnderTest(hive.connectionURL()); 169 | classUnderTest.dropTable("foo_db", "bar_table"); 170 | 171 | HiveMetaStoreClient client = hive.newClient(); 172 | try { 173 | assertFalse(client.tableExists("foo_db", "bar_table")); 174 | } finally { 175 | client.close(); 176 | } 177 | } 178 | 179 | ## JUnit5 Rule Migration 180 | Support is available to enable you to migrate your JUnit4 tests that currently use BeeJU rules without changing them to use extensions. To use JUnit5, ensure you have the following dependency in your POM: 181 | 182 | ```xml 183 | 184 | org.junit.jupiter 185 | junit-jupiter-migrationsupport 186 | ${junit.jupiter.version} 187 | test 188 | 189 | ``` 190 | 191 | For any test classes using the BeeJU rules, add the class annotation `@EnableRuleMigrationSupport`. No further changes are needed to move your JUnit4 tests to JUnit5. 192 | 193 | # Legal 194 | This project is available under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0.html). 195 | 196 | Copyright 2016-2021 Expedia, Inc. 197 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/main/java/com/hotels/beeju/core/BeejuCore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. and Klarna AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.core; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import java.io.File; 21 | import java.io.IOException; 22 | import java.io.UncheckedIOException; 23 | import java.net.ServerSocket; 24 | import java.nio.file.Files; 25 | import java.nio.file.Path; 26 | import java.util.Collections; 27 | import java.util.HashMap; 28 | import java.util.Iterator; 29 | import java.util.Map; 30 | import java.util.Map.Entry; 31 | import java.util.UUID; 32 | import java.util.concurrent.TimeUnit; 33 | 34 | import org.apache.commons.io.FileUtils; 35 | import org.apache.derby.jdbc.EmbeddedDriver; 36 | import org.apache.hadoop.fs.FileUtil; 37 | import org.apache.hadoop.fs.permission.FsPermission; 38 | import org.apache.hadoop.hive.conf.HiveConf; 39 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 40 | import org.apache.hadoop.hive.metastore.api.Database; 41 | import org.apache.hadoop.hive.metastore.api.MetaException; 42 | import org.apache.hadoop.hive.metastore.conf.MetastoreConf; 43 | import org.apache.thrift.TException; 44 | import org.slf4j.Logger; 45 | import org.slf4j.LoggerFactory; 46 | 47 | // This class contains some code sourced from and inspired by HiveRunner, specifically 48 | // https://github.com/klarna/HiveRunner/blob/fb00a98f37abdb779547c1c98ef6fbe54d373e0c/src/main/java/com/klarna/hiverunner/StandaloneHiveServerContext.java 49 | public class BeejuCore { 50 | 51 | private static final Logger log = LoggerFactory.getLogger(BeejuCore.class); 52 | 53 | // "user" conflicts with USER db and the metastore_db can't be created. 54 | private static final String METASTORE_DB_USER = "db_user"; 55 | private static final String METASTORE_DB_PASSWORD = "db_password"; 56 | 57 | protected final HiveConf conf = new HiveConf(); 58 | private final String databaseName; 59 | private String connectionURL; 60 | private String driverClassName; 61 | private Path warehouseDir; 62 | private Path derbyHome; 63 | private Path baseDir; 64 | 65 | private static Map convertToMap(HiveConf hiveConf) { 66 | Map converted = new HashMap(); 67 | Iterator> iterator = hiveConf.iterator(); 68 | while (iterator.hasNext()) { 69 | Entry next = iterator.next(); 70 | converted.put(next.getKey(), next.getValue()); 71 | } 72 | return converted; 73 | } 74 | 75 | public BeejuCore() { 76 | this("test_database"); 77 | } 78 | 79 | public BeejuCore(String databaseName) { 80 | this(databaseName, Collections.emptyMap()); 81 | } 82 | 83 | public BeejuCore(String databaseName, HiveConf preConfiguration, HiveConf postConfiguration) { 84 | this(databaseName, convertToMap(preConfiguration), convertToMap(postConfiguration)); 85 | } 86 | 87 | public BeejuCore(String databaseName, Map preConfiguration) { 88 | this(databaseName, preConfiguration, Collections.emptyMap()); 89 | } 90 | 91 | public BeejuCore(String databaseName, Map preConfiguration, Map postConfiguration) { 92 | checkNotNull(databaseName, "databaseName is required"); 93 | this.databaseName = databaseName; 94 | configure(preConfiguration); 95 | 96 | configureFolders(); 97 | 98 | configureMetastore(); 99 | 100 | configureMisc(); 101 | 102 | configure(postConfiguration); 103 | } 104 | 105 | private void configureMisc() { 106 | int webUIPort = getWebUIPort(); 107 | 108 | // override default port as some of our test environments claim it is in use. 109 | conf.setIntVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_PORT, webUIPort); 110 | 111 | conf.setBoolVar(HiveConf.ConfVars.HIVESTATSAUTOGATHER, false); 112 | 113 | // Disable to get rid of clean up exception when stopping the Session. 114 | conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_LOGGING_OPERATION_ENABLED, false); 115 | 116 | // Used to prevent "Not authorized to make the get_current_notificationEventId call" errors 117 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.EVENT_DB_NOTIFICATION_API_AUTH, "false"); 118 | 119 | // Used to prevent "Error polling for notification events" error 120 | conf.setTimeVar(HiveConf.ConfVars.HIVE_NOTFICATION_EVENT_POLL_INTERVAL, 0, TimeUnit.MILLISECONDS); 121 | 122 | // Has to be added to exclude failures related to the HiveMaterializedViewsRegistry 123 | conf.set(HiveConf.ConfVars.HIVE_SERVER2_MATERIALIZED_VIEWS_REGISTRY_IMPL.varname, "DUMMY"); 124 | System.setProperty(HiveConf.ConfVars.HIVE_SERVER2_MATERIALIZED_VIEWS_REGISTRY_IMPL.varname, "DUMMY"); 125 | } 126 | 127 | private void setMetastoreAndSystemProperty(MetastoreConf.ConfVars key, String value) { 128 | conf.set(key.getVarname(), value); 129 | conf.set(key.getHiveName(), value); 130 | 131 | System.setProperty(key.getVarname(), value); 132 | System.setProperty(key.getHiveName(), value); 133 | } 134 | 135 | private int getWebUIPort() { 136 | // Try to find a free port, if impossible return the default port 0 which disables the WebUI altogether 137 | int defaultPort = 0; 138 | 139 | try (ServerSocket socket = new ServerSocket(0)) { 140 | return socket.getLocalPort(); 141 | } catch (IOException e) { 142 | log.info( 143 | "No free port available for the Web UI. Setting the port to " + defaultPort + ", which disables the WebUI.", 144 | e); 145 | return defaultPort; 146 | } 147 | } 148 | 149 | private void configureFolders() { 150 | try { 151 | baseDir = Files.createTempDirectory("beeju-basedir-"); 152 | createAndSetFolderProperty(HiveConf.ConfVars.SCRATCHDIR, "scratchdir"); 153 | createAndSetFolderProperty(HiveConf.ConfVars.LOCALSCRATCHDIR, "localscratchdir"); 154 | createAndSetFolderProperty(HiveConf.ConfVars.HIVEHISTORYFILELOC, "hive-history"); 155 | 156 | createDerbyPaths(); 157 | createWarehousePath(); 158 | } catch (IOException e) { 159 | throw new UncheckedIOException("Error creating temporary folders", e); 160 | } 161 | } 162 | 163 | private void configureMetastore() { 164 | driverClassName = EmbeddedDriver.class.getName(); 165 | conf.setBoolean("hcatalog.hive.client.cache.disabled", true); 166 | connectionURL = "jdbc:derby:memory:" + UUID.randomUUID() + ";create=true"; 167 | 168 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.CONNECT_URL_KEY, connectionURL); 169 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.CONNECTION_DRIVER, driverClassName); 170 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.CONNECTION_USER_NAME, METASTORE_DB_USER); 171 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.PWD, METASTORE_DB_PASSWORD); 172 | 173 | conf.setVar(HiveConf.ConfVars.METASTORE_CONNECTION_POOLING_TYPE, "NONE"); 174 | conf.setBoolVar(HiveConf.ConfVars.HMSHANDLERFORCERELOADCONF, true); 175 | 176 | // Hive 2.x compatibility 177 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.AUTO_CREATE_ALL, "true"); 178 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.SCHEMA_VERIFICATION, "false"); 179 | } 180 | 181 | private void createAndSetFolderProperty(HiveConf.ConfVars var, String childFolderName) throws IOException { 182 | String folderPath = newFolder(baseDir, childFolderName).toAbsolutePath().toString(); 183 | conf.setVar(var, folderPath); 184 | } 185 | 186 | private Path newFolder(Path basedir, String folder) throws IOException { 187 | Path newFolder = Files.createTempDirectory(basedir, folder); 188 | FileUtil.setPermission(newFolder.toFile(), FsPermission.getDirDefault()); 189 | return newFolder; 190 | } 191 | 192 | private void createDerbyPaths() throws IOException { 193 | derbyHome = Files.createTempDirectory(baseDir, "derby-home-"); 194 | System.setProperty("derby.system.home", derbyHome.toString()); 195 | 196 | // overriding default derby log path to go to tmp 197 | String derbyLog = Files.createTempFile(baseDir, "derby", ".log").toString(); 198 | System.setProperty("derby.stream.error.file", derbyLog); 199 | } 200 | 201 | private void createWarehousePath() throws IOException { 202 | warehouseDir = Files.createTempDirectory(baseDir, "hive-warehouse-"); 203 | setHiveVar(HiveConf.ConfVars.METASTOREWAREHOUSE, warehouseDir.toString()); 204 | } 205 | 206 | public void cleanUp() { 207 | deleteDirectory(baseDir); 208 | } 209 | 210 | private void deleteDirectory(Path path) { 211 | try { 212 | FileUtils.deleteDirectory(path.toFile()); 213 | } catch (IOException e) { 214 | log.warn("Error cleaning up " + path, e); 215 | } 216 | } 217 | 218 | private void configure(Map customConfiguration) { 219 | if (customConfiguration != null) { 220 | for (Map.Entry entry : customConfiguration.entrySet()) { 221 | conf.set(entry.getKey(), entry.getValue()); 222 | } 223 | } 224 | } 225 | 226 | void setHiveVar(HiveConf.ConfVars variable, String value) { 227 | conf.setVar(variable, value); 228 | } 229 | 230 | void setHiveConf(String variable, String value) { 231 | conf.set(variable, value); 232 | } 233 | 234 | void setHiveIntVar(HiveConf.ConfVars variable, int value) { 235 | conf.setIntVar(variable, value); 236 | } 237 | 238 | /** 239 | * Create a new database with the specified name. 240 | * 241 | * @param databaseName Database name. 242 | * @throws TException If an error occurs creating the database. 243 | */ 244 | public void createDatabase(String databaseName) throws TException { 245 | File tempFile = warehouseDir.toFile(); 246 | String databaseFolder = new File(tempFile, databaseName).toURI().toString(); 247 | HiveMetaStoreClient client = newClient(); 248 | try { 249 | client.createDatabase(new Database(databaseName, null, databaseFolder, null)); 250 | } finally { 251 | client.close(); 252 | } 253 | } 254 | 255 | /** 256 | * @return a copy of the {@link HiveConf} used to create the Hive Metastore database. This {@link HiveConf} should be 257 | * used by tests wishing to connect to the database. 258 | */ 259 | public HiveConf conf() { 260 | return new HiveConf(conf); 261 | } 262 | 263 | /** 264 | * @return the name of the pre-created database. 265 | */ 266 | public String databaseName() { 267 | return databaseName; 268 | } 269 | 270 | /** 271 | * @return the name of the JDBC driver class used to access the database. 272 | */ 273 | public String driverClassName() { 274 | return driverClassName; 275 | } 276 | 277 | /** 278 | * @return the JDBC connection URL to the HSQLDB in-memory database. 279 | */ 280 | public String connectionURL() { 281 | return connectionURL; 282 | } 283 | 284 | public Path tempDir() { 285 | return baseDir; 286 | } 287 | 288 | public Path warehouseDir() { 289 | return warehouseDir; 290 | } 291 | 292 | /** 293 | * Creates a new HiveMetaStoreClient that can talk directly to the backed metastore database. 294 | *

295 | * The invoker is responsible for closing the client. 296 | *

297 | * 298 | * @return the {@link HiveMetaStoreClient} backed by an HSQLDB in-memory database. 299 | */ 300 | public HiveMetaStoreClient newClient() { 301 | try { 302 | return new HiveMetaStoreClient(conf); 303 | } catch (MetaException e) { 304 | throw new RuntimeException("Unable to create HiveMetaStoreClient", e); 305 | } 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /src/test/java/com/hotels/beeju/core/HiveServer2CoreTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2021 Expedia, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.hotels.beeju.core; 17 | 18 | import static org.hamcrest.CoreMatchers.is; 19 | import static org.hamcrest.MatcherAssert.assertThat; 20 | import static org.junit.jupiter.api.Assertions.assertEquals; 21 | import static org.junit.jupiter.api.Assertions.fail; 22 | 23 | import java.io.IOException; 24 | import java.sql.Connection; 25 | import java.sql.DriverManager; 26 | import java.sql.ResultSet; 27 | import java.sql.Statement; 28 | import java.util.Arrays; 29 | import java.util.List; 30 | 31 | import org.apache.hadoop.hive.conf.HiveConf; 32 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; 33 | import org.apache.hadoop.hive.metastore.api.FieldSchema; 34 | import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; 35 | import org.apache.hadoop.hive.metastore.api.Partition; 36 | import org.apache.hadoop.hive.metastore.api.SerDeInfo; 37 | import org.apache.hadoop.hive.metastore.api.StorageDescriptor; 38 | import org.apache.hadoop.hive.metastore.api.Table; 39 | import org.apache.hive.service.Service; 40 | import org.apache.thrift.TException; 41 | import org.junit.jupiter.api.AfterEach; 42 | import org.junit.jupiter.api.BeforeEach; 43 | import org.junit.jupiter.api.Test; 44 | 45 | public class HiveServer2CoreTest { 46 | 47 | private static final String DATABASE = "my_test_db"; 48 | private final BeejuCore core = new BeejuCore(DATABASE); 49 | private final HiveServer2Core server = new HiveServer2Core(core); 50 | 51 | @BeforeEach 52 | public void beforeEach() throws InterruptedException, IOException, TException { 53 | server.startServerSocket(); 54 | server.initialise(); 55 | server.getCore().createDatabase(DATABASE); 56 | } 57 | 58 | @AfterEach 59 | public void afterEach() { 60 | server.shutdown(); 61 | core.cleanUp(); 62 | } 63 | 64 | @Test 65 | public void initiateServer() { 66 | assertThat(server.getJdbcConnectionUrl(), 67 | is("jdbc:hive2://localhost:" + server.getPort() + "/" + core.databaseName())); 68 | assertThat(server.getHiveServer2().getServiceState(), is(Service.STATE.STARTED)); 69 | } 70 | 71 | @Test 72 | public void closeServer() throws InterruptedException { 73 | server.shutdown(); 74 | 75 | assertThat(server.getHiveServer2().getServiceState(), is(Service.STATE.STOPPED)); 76 | } 77 | 78 | @Test 79 | public void startServerSocket() { 80 | assertEquals(core.conf().getIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT), server.getPort()); 81 | } 82 | 83 | @Test 84 | public void dropTable() throws Exception { 85 | String tableName = "my_drop_table"; 86 | createUnpartitionedTable(DATABASE, tableName, server); 87 | 88 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl()); 89 | Statement statement = connection.createStatement()) { 90 | String dropHql = String.format("DROP TABLE %s.%s", DATABASE, tableName); 91 | statement.execute(dropHql); 92 | } 93 | 94 | HiveMetaStoreClient client = server.getCore().newClient(); 95 | try { 96 | client.getTable(DATABASE, tableName); 97 | fail(String.format("Table %s.%s was not deleted", DATABASE, tableName)); 98 | } catch (NoSuchObjectException e) { 99 | // expected 100 | } finally { 101 | client.close(); 102 | } 103 | } 104 | 105 | @Test 106 | public void createTable() throws Exception { 107 | String tableName = "my_test_table"; 108 | 109 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl()); 110 | Statement statement = connection.createStatement()) { 111 | String createHql = new StringBuilder() 112 | .append("CREATE TABLE `" + DATABASE + "." + tableName + "`(`id` int, `name` string) ") 113 | .append("ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' ") 114 | .append("STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' ") 115 | .append("OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'") 116 | .toString(); 117 | statement.execute(createHql); 118 | } 119 | 120 | HiveMetaStoreClient client = server.getCore().newClient(); 121 | Table table = client.getTable(DATABASE, tableName); 122 | client.close(); 123 | assertThat(table.getDbName(), is(DATABASE)); 124 | assertThat(table.getTableName(), is(tableName)); 125 | assertThat(table.getSd().getCols(), 126 | is(Arrays.asList(new FieldSchema("id", "int", null), new FieldSchema("name", "string", null)))); 127 | assertThat(table.getSd().getInputFormat(), is("org.apache.hadoop.mapred.TextInputFormat")); 128 | assertThat(table.getSd().getOutputFormat(), is("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat")); 129 | assertThat(table.getSd().getSerdeInfo().getSerializationLib(), 130 | is("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe")); 131 | } 132 | 133 | @Test 134 | public void showCreateTable() throws Exception { 135 | String tableName = "my_show_table"; 136 | Table table = createUnpartitionedTable(DATABASE, tableName, server); 137 | 138 | StringBuilder showCreateTable = new StringBuilder(); 139 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl()); 140 | Statement statement = connection.createStatement()) { 141 | String showHql = String.format("SHOW CREATE TABLE %s.%s", DATABASE, tableName); 142 | ResultSet result = statement.executeQuery(showHql); 143 | while (result.next()) { 144 | showCreateTable.append(result.getString(1)).append("\n"); 145 | } 146 | result.close(); 147 | } 148 | String expectedShowCreateTable = new StringBuilder() 149 | .append("CREATE TABLE `my_test_db." + tableName + "`(\n") 150 | .append(" `id` int, \n") 151 | .append(" `name` string)\n") 152 | .append("ROW FORMAT SERDE \n") 153 | .append(" 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' \n") 154 | .append("STORED AS INPUTFORMAT \n") 155 | .append(" 'org.apache.hadoop.mapred.TextInputFormat' \n") 156 | .append("OUTPUTFORMAT \n") 157 | .append(" 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'\n") 158 | .append("LOCATION\n") 159 | .append(" 'file:" + server.getCore().warehouseDir() + "/" + DATABASE + "/" + tableName + "'\n") 160 | .append("TBLPROPERTIES (\n") 161 | .append(" 'transient_lastDdlTime'='" + table.getParameters().get("transient_lastDdlTime") + "')\n") 162 | .toString(); 163 | assertThat(showCreateTable.toString(), is(expectedShowCreateTable)); 164 | } 165 | 166 | @Test 167 | public void dropDatabase() throws Exception { 168 | String databaseName = "Another_DB"; 169 | 170 | server.getCore().createDatabase(databaseName); 171 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl()); 172 | Statement statement = connection.createStatement()) { 173 | String dropHql = String.format("DROP DATABASE %s", databaseName); 174 | statement.execute(dropHql); 175 | } 176 | 177 | HiveMetaStoreClient client = server.getCore().newClient(); 178 | try { 179 | client.getDatabase(databaseName); 180 | fail(String.format("Database %s was not deleted", databaseName)); 181 | } catch (NoSuchObjectException e) { 182 | // expected 183 | } finally { 184 | client.close(); 185 | } 186 | } 187 | 188 | @Test 189 | public void addPartition() throws Exception { 190 | String tableName = "my_add_part_table"; 191 | createPartitionedTable(DATABASE, tableName, server); 192 | 193 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl()); 194 | Statement statement = connection.createStatement()) { 195 | String addPartitionHql = String.format("ALTER TABLE %s.%s ADD PARTITION (partcol=1)", DATABASE, tableName); 196 | statement.execute(addPartitionHql); 197 | } 198 | 199 | HiveMetaStoreClient client = server.getCore().newClient(); 200 | try { 201 | List partitions = client.listPartitions(DATABASE, tableName, (short) -1); 202 | assertThat(partitions.size(), is(1)); 203 | assertThat(partitions.get(0).getDbName(), is(DATABASE)); 204 | assertThat(partitions.get(0).getTableName(), is(tableName)); 205 | assertThat(partitions.get(0).getValues(), is(Arrays.asList("1"))); 206 | assertThat(partitions.get(0).getSd().getLocation(), 207 | is(String.format("file:%s/%s/%s/partcol=1", server.getCore().warehouseDir(), DATABASE, tableName))); 208 | } finally { 209 | client.close(); 210 | } 211 | } 212 | 213 | @Test 214 | public void dropPartition() throws Exception { 215 | String tableName = "my_drop_part_table"; 216 | HiveMetaStoreClient client = server.getCore().newClient(); 217 | 218 | try { 219 | Table table = createPartitionedTable(DATABASE, tableName, server); 220 | 221 | Partition partition = new Partition(); 222 | partition.setDbName(DATABASE); 223 | partition.setTableName(tableName); 224 | partition.setValues(Arrays.asList("1")); 225 | partition.setSd(new StorageDescriptor(table.getSd())); 226 | partition 227 | .getSd() 228 | .setLocation(String.format("file:%s/%s/%s/partcol=1", server.getCore().warehouseDir(), DATABASE, tableName)); 229 | client.add_partition(partition); 230 | 231 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl()); 232 | Statement statement = connection.createStatement()) { 233 | String dropPartitionHql = String.format("ALTER TABLE %s.%s DROP PARTITION (partcol=1)", DATABASE, tableName); 234 | statement.execute(dropPartitionHql); 235 | } 236 | 237 | List partitions = client.listPartitions(DATABASE, tableName, (short) -1); 238 | assertThat(partitions.size(), is(0)); 239 | } finally { 240 | client.close(); 241 | } 242 | } 243 | 244 | private Table createUnpartitionedTable(String databaseName, String tableName, HiveServer2Core server) 245 | throws Exception { 246 | Table table = new Table(); 247 | table.setDbName(databaseName); 248 | table.setTableName(tableName); 249 | table.setSd(new StorageDescriptor()); 250 | table.getSd().setCols(Arrays.asList(new FieldSchema("id", "int", null), new FieldSchema("name", "string", null))); 251 | table.getSd().setInputFormat("org.apache.hadoop.mapred.TextInputFormat"); 252 | table.getSd().setOutputFormat("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat"); 253 | table.getSd().setSerdeInfo(new SerDeInfo()); 254 | table.getSd().getSerdeInfo().setSerializationLib("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"); 255 | HiveMetaStoreClient client = server.getCore().newClient(); 256 | client.createTable(table); 257 | client.close(); 258 | return table; 259 | } 260 | 261 | private Table createPartitionedTable(String databaseName, String tableName, HiveServer2Core server) throws Exception { 262 | Table table = new Table(); 263 | table.setDbName(DATABASE); 264 | table.setTableName(tableName); 265 | table.setPartitionKeys(Arrays.asList(new FieldSchema("partcol", "int", null))); 266 | table.setSd(new StorageDescriptor()); 267 | table.getSd().setCols(Arrays.asList(new FieldSchema("id", "int", null), new FieldSchema("name", "string", null))); 268 | table.getSd().setInputFormat("org.apache.hadoop.mapred.TextInputFormat"); 269 | table.getSd().setOutputFormat("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat"); 270 | table.getSd().setSerdeInfo(new SerDeInfo()); 271 | table.getSd().getSerdeInfo().setSerializationLib("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"); 272 | HiveMetaStoreClient client = server.getCore().newClient(); 273 | client.createTable(table); 274 | client.close(); 275 | return table; 276 | } 277 | 278 | } 279 | --------------------------------------------------------------------------------