[CALCITE-2347] running ElasticSearch in embedded mode for unit tests of ES adapter...
[calcite.git] / elasticsearch2 / src / test / java / org / apache / calcite / adapter / elasticsearch2 / EmbeddedElasticRule.java
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to you under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.calcite.adapter.elasticsearch2;
18
19 import com.google.common.base.Preconditions;
20
21 import org.elasticsearch.client.Client;
22 import org.elasticsearch.common.transport.TransportAddress;
23 import org.junit.rules.ExternalResource;
24
25 /**
26 * Used to initialize a single elastic node. For performance reasons (node startup costs),
27 * same instance is usually shared across multiple tests.
28 *
29 * This rule should be used as follows:
30 * <pre>
31 * {@code
32 *
33 * public class MyTest {
34 * @literal @ClassRule
35 * public static final ElasticSearchRule RULE = ElasticSearchRule.create();
36 *
37 * @literal @BeforeClass
38 * public void setup() {
39 * // ... populate instance
40 * }
41 *
42 * @literal @Test
43 * public void myTest() {
44 * TransportAddress address = RULE.httpAddress();
45 * // ....
46 * }
47 * }
48 * }
49 * </pre>
50 *
51 * @see ExternalResource
52 */
53 class EmbeddedElasticRule extends ExternalResource {
54
55 private final EmbeddedElasticNode node;
56
57 private EmbeddedElasticRule(EmbeddedElasticNode resource) {
58 this.node = Preconditions.checkNotNull(resource, "resource");
59 }
60
61 @Override protected void before() throws Throwable {
62 node.start();
63 }
64
65 @Override protected void after() {
66 try {
67 node.close();
68 } catch (Exception e) {
69 throw new RuntimeException(e);
70 }
71 }
72
73 /**
74 * Factory method to create this rule.
75 */
76 public static EmbeddedElasticRule create() {
77 return new EmbeddedElasticRule(EmbeddedElasticNode.create());
78 }
79
80 /**
81 * Exposes current ES transport client.
82 */
83 Client client() {
84 return node.client();
85 }
86
87 /**
88 * HTTP address for rest clients (can be ES native or any other).
89 */
90 TransportAddress httpAddress() {
91 return node.httpAddress();
92 }
93
94
95 }
96
97 // End EmbeddedElasticRule.java