001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase; 019 020import java.io.IOException; 021import java.util.concurrent.CompletableFuture; 022import java.util.function.Supplier; 023import org.apache.hadoop.hbase.client.AsyncConnection; 024import org.junit.ClassRule; 025import org.junit.Rule; 026import org.junit.rules.ExternalResource; 027 028/** 029 * A {@link Rule} that manages the lifecycle of an instance of {@link AsyncConnection}. Can be used 030 * in either the {@link Rule} or {@link ClassRule} positions. 031 * </p> 032 * Use in combination with {@link MiniClusterRule}, for example: 033 * 034 * <pre>{@code 035 * public class TestMyClass { 036 * private static final MiniClusterRule miniClusterRule = MiniClusterRule.newBuilder().build(); 037 * private static final ConnectionRule connectionRule = 038 * new ConnectionRule(miniClusterRule::createConnection); 039 * 040 * @ClassRule 041 * public static final TestRule rule = RuleChain 042 * .outerRule(miniClusterRule) 043 * .around(connectionRule); 044 * } 045 * }</pre> 046 */ 047public class ConnectionRule extends ExternalResource { 048 049 private final Supplier<CompletableFuture<AsyncConnection>> connectionSupplier; 050 private AsyncConnection connection; 051 052 public ConnectionRule(final Supplier<CompletableFuture<AsyncConnection>> connectionSupplier) { 053 this.connectionSupplier = connectionSupplier; 054 } 055 056 public AsyncConnection getConnection() { 057 return connection; 058 } 059 060 @Override 061 protected void before() throws Throwable { 062 this.connection = connectionSupplier.get().join(); 063 } 064 065 @Override 066 protected void after() { 067 if (this.connection != null) { 068 try { 069 connection.close(); 070 } catch (IOException e) { 071 throw new RuntimeException(e); 072 } 073 } 074 } 075}