├── .gitignore
├── README.textile
├── pom.xml
└── src
├── main
└── java
│ └── com
│ └── github
│ └── tlrx
│ └── elasticsearch
│ └── test
│ ├── EsSetup.java
│ ├── EsSetupRuntimeException.java
│ ├── annotations
│ ├── ElasticsearchAdminClient.java
│ ├── ElasticsearchAnalysis.java
│ ├── ElasticsearchAnalyzer.java
│ ├── ElasticsearchBulkRequest.java
│ ├── ElasticsearchClient.java
│ ├── ElasticsearchFilter.java
│ ├── ElasticsearchIndex.java
│ ├── ElasticsearchIndexes.java
│ ├── ElasticsearchMapping.java
│ ├── ElasticsearchMappingField.java
│ ├── ElasticsearchMappingSubField.java
│ ├── ElasticsearchNode.java
│ ├── ElasticsearchSetting.java
│ ├── ElasticsearchTransportClient.java
│ ├── Index.java
│ ├── Store.java
│ ├── TermVector.java
│ └── Types.java
│ ├── provider
│ ├── ClassPathJSONProvider.java
│ ├── ClientProvider.java
│ ├── DefaultClientProvider.java
│ ├── JSONProvider.java
│ └── LocalClientProvider.java
│ ├── request
│ ├── Count.java
│ ├── CreateIndex.java
│ ├── CreateTemplate.java
│ ├── Delete.java
│ ├── DeleteIndices.java
│ ├── DeleteTemplates.java
│ ├── Exists.java
│ ├── Index.java
│ └── Request.java
│ └── support
│ └── junit
│ ├── handlers
│ ├── ClassLevelElasticsearchAnnotationHandler.java
│ ├── ElasticsearchAnnotationHandler.java
│ ├── FieldLevelElasticsearchAnnotationHandler.java
│ ├── MethodLevelElasticsearchAnnotationHandler.java
│ └── annotations
│ │ ├── AbstractAnnotationHandler.java
│ │ ├── ElasticsearchAdminClientAnnotationHandler.java
│ │ ├── ElasticsearchBulkRequestAnnotationHandler.java
│ │ ├── ElasticsearchClientAnnotationHandler.java
│ │ ├── ElasticsearchIndexAnnotationHandler.java
│ │ ├── ElasticsearchIndexesAnnotationHandler.java
│ │ ├── ElasticsearchNodeAnnotationHandler.java
│ │ └── ElasticsearchTransportClientAnnotationHandler.java
│ ├── rules
│ ├── AbstractElasticsearchRule.java
│ ├── ElasticsearchClassRule.java
│ ├── ElasticsearchFieldRule.java
│ └── ElasticsearchTestRule.java
│ └── runners
│ └── ElasticsearchRunner.java
└── test
├── java
└── com
│ └── github
│ └── tlrx
│ └── elasticsearch
│ ├── samples
│ ├── core
│ │ └── VersionTest.java
│ ├── indices
│ │ ├── AliasesTest.java
│ │ ├── OptimizeTest.java
│ │ └── analyze
│ │ │ └── AnalyzeTest.java
│ └── search
│ │ └── FilterTest.java
│ └── test
│ ├── EsSetupTest.java
│ ├── annotations
│ ├── ElasticsearchAdminClientAnnotationTest.java
│ ├── ElasticsearchAnalysisAnnotationTest.java
│ ├── ElasticsearchBulkRequestAnnotationTest.java
│ ├── ElasticsearchClientAnnotationTest.java
│ ├── ElasticsearchIndexAnnotationTest.java
│ ├── ElasticsearchIndexesAnnotationTest.java
│ ├── ElasticsearchMappingAnnotationTest.java
│ ├── ElasticsearchNodeAnnotationTest.java
│ ├── ElasticsearchSettingAnnotationTest.java
│ └── ElasticsearchTransportClientAnnotationTest.java
│ ├── request
│ └── DeleteTemplatesTest.java
│ └── rules
│ ├── ChildTest.java
│ └── ParentTest.java
└── resources
├── com
└── github
│ └── tlrx
│ └── elasticsearch
│ ├── samples
│ └── search
│ │ └── FilterTest.json
│ └── test
│ ├── annotations
│ ├── documents
│ │ ├── bulk1.json
│ │ ├── bulk2.json
│ │ └── settings.json
│ └── elasticsearch-node4.yml
│ ├── data
│ └── products.json
│ ├── indices
│ └── catalog-2011.json
│ ├── mappings
│ ├── customer.json
│ └── product.json
│ ├── settings
│ └── catalog.json
│ └── templates
│ └── template-1.json
└── config
└── elasticsearch.yml
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled source #
2 | ###################
3 | *.com
4 | *.class
5 | *.dll
6 | *.exe
7 | *.o
8 | *.so
9 | target/
10 | target/
11 | .classpath
12 | .project
13 | .settings
14 | .idea/
15 | elasticsearch-test.iml
16 |
17 | # Packages #
18 | ############
19 | # it's better to unpack these files and commit the raw source
20 | # git has its own built in compression methods
21 | *.7z
22 | *.dmg
23 | *.gz
24 | *.iso
25 | *.jar
26 | *.rar
27 | *.tar
28 | *.zip
29 |
30 | # Logs and databases #
31 | ######################
32 | *.log
33 | *.sql
34 | *.sqlite
35 |
36 | # OS generated files #
37 | ######################
38 | .DS_Store*
39 | ehthumbs.db
40 | Icon?
41 | Thumbs.db
42 |
43 |
--------------------------------------------------------------------------------
/README.textile:
--------------------------------------------------------------------------------
1 | elasticsearch-test, a framework that makes "ElasticSearch":http://www.elasticsearch.org/ unit testing a breeze.
2 |
3 | *Warning*: Since 0.90.7, the Elasticsearch team provides a JAR file containing all the test classes. This JAR can be included in third party projects. See the "pull request":https://github.com/elasticsearch/elasticsearch/pull/4126 for more information.
4 |
5 |
6 | Here you will find:
7 | * a simple Java API that can be used to easily set up ElasticSearch in your unit tests
8 | * some Java annotations that simplifies JUnit testing with ElasticSearch
9 |
10 |
11 | h3. Versions
12 |
13 | |_. elasticsearch-test |_. ElasticSearch|
14 | | master (1.2.2-SNAPSHOT) | 1.2.2 |
15 | | 1.2.1 | 1.2.1 |
16 | | 1.1.0 | 1.1.0 |
17 | | 0.90.6 | 0.90.6 |
18 | | 0.90.5 | 0.90.5 |
19 | | 0.0.10 | 0.90.3 |
20 | | 0.0.9 | 0.90.1 |
21 | | 0.0.8 | 0.90.0.Beta1 |
22 | | 0.0.7 | 0.20.1 |
23 | | 0.0.6 | 0.20.0 |
24 | | 0.0.5 | 0.19.11 |
25 | | 0.0.4 | 0.19.8 |
26 | | 0.0.3 | 0.19.7 |
27 | | 0.0.2 | 0.19.4 |
28 | | 0.0.1 | 0.19.4 |
29 |
30 | h3. Maven dependency
31 |
32 | Add a new dependency in your Maven POM file:
33 |
34 | bc.
35 | com.github.tlrx
36 | elasticsearch-test
37 | 1.2.1
38 |
39 |
40 |
41 | h2. Using the Java API
42 |
43 | The @EsSetup@ class helps to start and stop a local ElasticSearch node. Then, the @EsSetup.execute()@ method
44 | can be used to create indices (with mappings, settings and templates support) and import test data.
45 |
46 | The usage of @EsSetup@ is pretty self explanatory:
47 |
48 | import static com.github.tlrx.elasticsearch.test.EsSetup.*;
49 |
50 | public class MyTest {
51 | EsSetup esSetup;
52 | @Before public void setUp() throws Exception {
53 | // Instantiates a local node & client
54 | esSetup = new EsSetup();
55 | // Clean all, and creates some indices
56 | esSetup.execute(
57 | deleteAll(),
58 | createIndex("my_index_1"),
59 | createIndex("my_index_2")
60 | .withSettings(fromClassPath("path/to/settings.json"))
61 | .withMapping("type1", fromClassPath("path/to/mapping/of/type1.json"))
62 | .withData(fromClassPath("path/to/bulk.json")),
63 | createTemplate("template-1")
64 | .withSource(fromClassPath("path/to/template1.json")),
65 | );
66 | }
67 | @Test public void testMethod() {
68 | // check if the index exists
69 | assertTrue(esSetup.exists("my_index_2"));
70 | // Index a new document
71 | esSetup.execute(index("my_index_2", "type1", "1").withSource("{ \"field1\" : \"value1\" }"));
72 | // Count the number of documents
73 | Long nb = esSetup.countAll();
74 | // Delete a document
75 | esSetup.execute(delete("my_index_2", "type1", "1"));
76 | // Clean all indices
77 | esSetup.execute(deleteAll());
78 | }
79 | @After public void tearDown() throws Exception {
80 | // This will stop and clean the local node
81 | esSetup.terminate();
82 | }
83 | }
84 | More usages can be found in "BasicTest.java":https://github.com/tlrx/elasticsearch-test/blob/master/src/test/java/com/github/tlrx/elasticsearch/test/BasicTest.java
85 |
86 |
87 |
88 | h2. Using with JUnit
89 |
90 | Define the JUnit @Runner@ to use in your test classes with the annotation @@RunWith(ElasticsearchRunner.class)@ :
91 |
92 |
93 | package com.github.tlrx.elasticsearch.samples.core;
94 |
95 | @RunWith(ElasticsearchRunner.class)
96 | public class VersionTest {
97 | ...
98 | }
99 |
100 |
101 |
102 | h3. Annotations
103 |
104 | The library provides the following annotations:
105 |
106 | |_. Annotation |_. |
107 | | @ElasticsearchNode | Instantiate an elasticsearch Node |
108 | | @ElasticsearchClient | Instantiate an elasticsearch Client |
109 | | @ElasticsearchAdminClient | Instantiate an elasticsearch AdminClient |
110 | | @ElasticsearchTransportClient | Instantiate an elasticsearch TransportClient |
111 | | @ElasticsearchIndexes | Used to create multiple index |
112 | | @ElasticsearchIndex | Creates an index |
113 | | @ElasticsearchMapping | Defines a mapping for an index and a document type |
114 | | @ElasticsearchMappingField | Defines field properties in a mapping |
115 | | @ElasticsearchSetting | Defines settings (at node or index level) |
116 | | @ElasticsearchBulkRequest | Used to import data |
117 | | @ElasticsearchAnalysis | Used to define analysis settings of an ElasticsearchIndex |
118 | | @ElasticsearchAnalyzer | Used to define an analyzer |
119 | | @ElasticsearchFilter | Used to define an analysis filter |
120 |
121 | h3. @ElasticsearchNode
122 |
123 | Used to instantiate an elasticsearch @Node@ in a unit test class.
124 |
125 | Simple node has default name "elasticsearch-test-node" and is part of default cluster name "elasticsearch-test-cluster". Node is local and can hold data.
126 |
127 | package com.github.tlrx.elasticsearch.samples.core;
128 |
129 | @RunWith(ElasticsearchRunner.class)
130 | public class VersionTest {
131 |
132 | @ElasticsearchNode
133 | Node node;
134 |
135 | @Test
136 | public void test(){
137 | // Use of node
138 | }
139 | }
140 |
141 | Example with custom cluster and node names, and local set to true and data set to false:
142 |
143 | bc. @ElasticsearchNode(name = "node3", clusterName = "fourth-cluster-name", local = true, data = false)
144 | Node node3;
145 |
146 | Example with custom settings:
147 |
148 | @ElasticsearchNode(name = "node0", settings = {
149 | @ElasticsearchSetting(name = "http.enabled", value = "false"),
150 | @ElasticsearchSetting(name = "node.zone", value = "zone_one") })
151 | Node node;
152 |
153 |
154 | h3. @ElasticsearchClient
155 |
156 | Used to instantiate an elasticsearch @Client@ from a @Node@. The @nodeName@ parameter of the annotation is used to retrieve the node from which the client will be instantiated. If no nodeName is defined, a default node will be instantiated.
157 |
158 | Example with default node:
159 |
160 | bc. @ElasticsearchClient
161 | Client client;
162 |
163 | Example with a predefined node:
164 |
165 | @ElasticsearchNode(name = "node1")
166 | Node node1;
167 |
168 | @ElasticsearchClient(nodeName = "node1")
169 | Client client1;
170 |
171 | h3. @ElasticsearchAdminClient
172 |
173 | Same as @ElasticsearchClient@ but instantiates an @AdminClient@.
174 |
175 | @ElasticsearchAdminClient
176 | AdminClient adminClient0;
177 |
178 | @ElasticsearchNode(name = "node1")
179 | Node node1;
180 |
181 | @ElasticsearchAdminClient(nodeName = "node1")
182 | AdminClient adminClient1;
183 |
184 | h3. @ElasticsearchTransportClient
185 |
186 | Used to instantiate an elasticsearch @TransportClient@. By default the TransportClient will try to join localhost:9200.
187 |
188 | Connect to a remote node with a TransportClient:
189 |
190 | @ElasticsearchTransportClient(local = false, clusterName = "external",
191 | hostnames = {"host1", "host2"},
192 | ports= {9300, 9300})
193 | Client client;
194 |
195 |
196 | h3. @ElasticsearchIndex, @ElasticsearchIndexes
197 |
198 | Used to creates one or many index before a test method. A node must be instantiated before using this annotation.
199 |
200 | This example will create an index with default name @test@:
201 |
202 | @ElasticsearchAdminClient
203 | AdminClient adminClient;
204 |
205 | @Test
206 | @ElasticsearchIndex
207 | public void test(){...}
208 |
209 | This example will create an index "people":
210 |
211 | @Test
212 | @ElasticsearchIndex(indexName = "people")
213 | public void test(){
214 | ...
215 | }
216 |
217 | This example will create 2 indexs with settings:
218 |
219 | @Test
220 | @ElasticsearchIndexes(indexes = {
221 | @ElasticsearchIndex(indexName = "library",
222 | forceCreate = true,
223 | settings = {
224 | @ElasticsearchSetting(name = "number_of_shards", value = "2"),
225 | @ElasticsearchSetting(name = "number_of_replicas", value = "1") }),
226 | @ElasticsearchIndex(indexName = "people") })
227 | public void test(){
228 | ...
229 | }
230 |
231 | This example will create an index with settings:
232 |
233 | @Test
234 | @Test
235 | @ElasticsearchIndex(indexName = "documents", settingsFile = "path/to/settings.json")
236 | public void test() {
237 | ...
238 | }
239 |
240 |
241 | h3. Load data from JSON file with @ElasticsearchBulkRequest
242 |
243 | @Test
244 | @ElasticsearchIndex(indexName = "documents", forceCreate = true)
245 | @ElasticsearchBulkRequest(dataFile = "com/tlrx/elasticsearch/test/annotations/documents/bulk1.json")
246 | public void test() {
247 | // Data from JSON file are indexed
248 | }
249 |
250 | h3. @ElasticsearchMapping, @ElasticsearchMappingField and @ElasticsearchSetting
251 |
252 | Used to define the mappings and settings of an index
253 |
254 | This example will create 2 indexs, "people" and "library", with a mapping for document type "book":
255 | @ElasticsearchNode
256 | Node node;
257 |
258 | @Test
259 | @ElasticsearchIndexes(indexes = {
260 | @ElasticsearchIndex(indexName = "people", settings = {
261 | @ElasticsearchSetting(name = "number_of_shards", value = "2"),
262 | @ElasticsearchSetting(name = "number_of_replicas", value = "1")
263 | }),
264 | @ElasticsearchIndex(indexName = "library",
265 | mappings = {
266 | @ElasticsearchMapping(typeName = "book",
267 | properties = {
268 | @ElasticsearchMappingField(name = "title", store = Store.Yes, type = Types.String),
269 | @ElasticsearchMappingField(name = "author", store = Store.Yes, type = Types.String)
270 | })
271 | })
272 | })
273 | public void test(){
274 | ...
275 | }
276 |
277 | You can also look at "the unit tests for some inspiration":https://github.com/tlrx/elasticsearch-test/tree/master/src/test/java/com/github/tlrx/elasticsearch
278 |
279 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 | com.github.tlrx
5 | elasticsearch-test
6 | 1.2.2-SNAPSHOT
7 | jar
8 | elasticsearch-test
9 | elasticsearch-test, a framework that makes ElasticSearch unit testing a breeze
10 | https://github.com/tlrx/elasticsearch-test
11 |
12 |
13 |
14 | org.sonatype.oss
15 | oss-parent
16 | 7
17 |
18 |
19 |
20 | UTF-8
21 | 1.2.2
22 | github
23 |
24 |
25 |
26 |
27 | The Apache Software License, Version 2.0
28 | http://www.apache.org/licenses/LICENSE-2.0.txt
29 |
30 |
31 |
32 |
33 |
34 | tlrx
35 | Tanguy Leroux
36 | tlrx.dev@gmail.com
37 |
38 |
39 |
40 |
41 |
42 | junit
43 | junit
44 | 4.11
45 |
46 |
47 | org.elasticsearch
48 | elasticsearch
49 | ${elasticsearch.version}
50 |
51 |
52 |
53 |
54 | git:git@github.com:tlrx/elasticsearch-test.git
55 | scm:git:git@github.com:tlrx/elasticsearch-test.git
56 | scm:git:git@github.com:tlrx/elasticsearch-test.git
57 |
58 |
59 |
60 | GitHub
61 | https://github.com/tlrx/elasticsearch-test/issues/
62 |
63 |
64 |
65 |
66 |
67 | org.apache.maven.plugins
68 | maven-compiler-plugin
69 | 2.3.2
70 |
71 | 1.6
72 | 1.6
73 |
74 |
75 |
76 | org.apache.maven.plugins
77 | maven-javadoc-plugin
78 | 2.8
79 |
80 |
81 | org.apache.maven.plugins
82 | maven-source-plugin
83 | 2.1.2
84 |
85 |
86 | attach-sources
87 |
88 | jar
89 |
90 |
91 |
92 |
93 |
94 | org.apache.maven.plugins
95 | maven-jar-plugin
96 | 2.3.2
97 |
98 |
99 | org.apache.maven.plugins
100 | maven-scm-plugin
101 | 1.5
102 |
103 |
104 |
105 |
106 |
107 |
108 | sonatype-nexus-staging
109 | Nexus Staging Repository
110 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
111 |
112 |
113 |
114 |
115 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/EsSetup.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test;
20 |
21 | import com.github.tlrx.elasticsearch.test.provider.*;
22 | import com.github.tlrx.elasticsearch.test.request.*;
23 | import org.elasticsearch.client.Client;
24 | import org.elasticsearch.common.Preconditions;
25 | import org.elasticsearch.common.settings.Settings;
26 |
27 | /**
28 | * This class aims to simplify the ElasticSearch setup for unit testing. It allows to start and stop an embedded local
29 | * node (or it can connect to a remote cluster), and then execute a set of requests to setup ElasticSearch.
30 | *
31 | * This sample code shows how to use EsSetup for a local node, and how to execute requests against this node:
32 | *
33 | * public class MyTest {
34 | *
35 | * EsSetup esSetup;
36 | *
37 | * @Before
38 | * public void setUp() throws Exception {
39 | *
40 | * // Local node and client
41 | * esSetup = new EsSetup();
42 | *
43 | * // Clean all, and creates some indices
44 | * esSetup.execute(
45 | * deleteAll(),
46 | *
47 | * createIndex("my_index_1"),
48 | *
49 | * createIndex("my_index_2")
50 | * .withSettings(fromClassPath("path/to/settings.json"))
51 | * .withMapping("type1", fromClassPath("path/to/mapping/of/type1.json"))
52 | * .withData(fromClassPath("path/to/bulk.json"))
53 | * );
54 | * }
55 | *
56 | * @After
57 | * public void tearDown() throws Exception {
58 | * esSetup.terminate();
59 | * }
60 | * }
61 | *
62 | */
63 | public class EsSetup {
64 |
65 | private final ClientProvider provider;
66 |
67 | /**
68 | * This constructor uses the {@link ClientProvider} to retrieve an instance of {@link Client} and use it to execute requests.
69 | *
70 | * @param clientProvider the {@link ClientProvider} to use for requests execution
71 | */
72 | protected EsSetup(ClientProvider clientProvider) {
73 | Preconditions.checkNotNull(clientProvider, "No ClientProvider specified");
74 | provider = clientProvider;
75 | }
76 |
77 | /**
78 | * This constructor instantiates a local {@link org.elasticsearch.node.Node}.
79 | */
80 | public EsSetup() {
81 | this(new LocalClientProvider());
82 | }
83 |
84 | /**
85 | * This constructor instantiates a local {@link org.elasticsearch.node.Node} with specific {@link Settings}.
86 | */
87 | public EsSetup(Settings settings) {
88 | this(new LocalClientProvider(settings));
89 | }
90 |
91 | /**
92 | * This constructor allows to use a custom client (usually a TransportClient) to execute requests.
93 | * The client can be injected with a Dependency Injection framework or manually instantiated with Elasticsearch API:
94 | *
95 | * Client client = new TransportClient()
96 | * .addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
97 | * EsSetup esSetup = new EsSetup(client);
98 | *
99 | *
100 | * @param client the client to use
101 | */
102 | public EsSetup(Client client) {
103 | this(new DefaultClientProvider(client, false));
104 | }
105 |
106 | /**
107 | * Similar to previous constructor, but it will close the client when terminate() is called.
108 | *
109 | * @param client the client to use
110 | * @param closeClientOnTerminate if true, the client will be closed when terminate() method is called.
111 | */
112 | public EsSetup(Client client, boolean closeClientOnTerminate) {
113 | this(new DefaultClientProvider(client, closeClientOnTerminate));
114 | }
115 |
116 | /**
117 | * @return the provided {@link Client}
118 | */
119 | public Client client() {
120 | return provider.client();
121 | }
122 |
123 | /**
124 | * Executes one or more requests. The requests will use the provided client. Execution will stop if a request fails.
125 | *
126 | * @param requests an array of requests to execute
127 | * @return the current EsSetup instance
128 | */
129 | public EsSetup execute(Request... requests) {
130 | provider.open();
131 | for (Request request : requests) {
132 | doExecute(request);
133 | }
134 | return this;
135 | }
136 |
137 | /**
138 | * Executes a request
139 | *
140 | * @param request the request to execute
141 | * @param the type of the request execution's result
142 | * @return the result of the execution (can be {@link Void}
143 | */
144 | private T doExecute(Request request) {
145 | Preconditions.checkNotNull(request, "Request must not be null");
146 | provider.open();
147 | try {
148 | return (T) request.execute(provider.client());
149 | } catch (EsSetupRuntimeException e) {
150 | throw new EsSetupRuntimeException("Exception when executing request " + request, e);
151 | }
152 | }
153 |
154 | /**
155 | * Terminates and closes the node and client.
156 | */
157 | public void terminate() {
158 | provider.close();
159 | }
160 |
161 | /**
162 | * Util method to load a JSON file and get its content as a String.
163 | *
164 | * @param path the path of the file to load
165 | * @return a {@link JSONProvider} used to get file's content as JSON
166 | */
167 | public static JSONProvider fromClassPath(String path) {
168 | return new ClassPathJSONProvider(Thread.currentThread().getContextClassLoader(), path);
169 | }
170 |
171 | /**
172 | * Util method to load a JSON file and get its content as a String. This method uses {@link ClassLoader#getResourceAsStream(String)} to load the resource.
173 | *
174 | * @param classLoader the {@link ClassLoader} used to load the resource.
175 | * @param resourceName the name of the resource/file to load
176 | * @return
177 | */
178 | public static JSONProvider fromClassPath(ClassLoader classLoader, String resourceName) {
179 | return new ClassPathJSONProvider(classLoader, resourceName);
180 | }
181 |
182 | /**
183 | * Util method to load a JSON file and get its content as a String. This method uses {@link Class#getResourceAsStream(String)} to load the resource.
184 | *
185 | * @param klass the {@link Class} used to load the resource.
186 | * @param resourceName the name of the resource/file to load
187 | * @return
188 | */
189 | public static JSONProvider fromClassPath(Class klass, String resourceName) {
190 | return new ClassPathJSONProvider(klass, resourceName);
191 | }
192 |
193 | /**
194 | * Instantiates a request that can be used to create an index.
195 | * Here's a sample of how create an index:
196 | *
197 | * import static com.github.tlrx.elasticsearch.test.EsSetup.createIndex;
198 | * ...
199 | * createIndex("my_index")
200 | * .withSource(...)
201 | *
202 | *
203 | * @param index the index name
204 | * @return a {@link CreateIndex} request
205 | */
206 | public static CreateIndex createIndex(String index) {
207 | return new CreateIndex(index);
208 | }
209 |
210 | /**
211 | * Instantiates a request that can be used to index a document.
212 | *
213 | * @param index the index name
214 | * @param type the document type
215 | * @return a {@link Index} request
216 | */
217 | public static Index index(String index, String type) {
218 | return new Index(index, type);
219 | }
220 |
221 | /**
222 | * Instantiates a request that can be used to index a document.
223 | *
224 | * @param index the index name
225 | * @param type the document type
226 | * @param id the document id
227 | * @return a {@link Index} request
228 | */
229 | public static Index index(String index, String type, String id) {
230 | return new Index(index, type, id);
231 | }
232 |
233 | /**
234 | * Instantiates a request that can be used to delete a document.
235 | *
236 | * @param index the index name
237 | * @param type the document type
238 | * @param id the document id
239 | * @return a {@link Delete} request
240 | */
241 | public static Delete delete(String index, String type, String id) {
242 | return new Delete(index, type, id);
243 | }
244 |
245 | /**
246 | * Instantiates a request that can be used to delete an index
247 | *
248 | * @param index the index name
249 | * @return a {@link DeleteIndices} request
250 | */
251 | public static DeleteIndices deleteIndex(String index) {
252 | return new DeleteIndices(index);
253 | }
254 |
255 | /**
256 | * Instantiates a request that can be used to delete given indices
257 | *
258 | * @param indices the indices names
259 | * @return a {@link DeleteIndices} request
260 | */
261 | public static DeleteIndices deleteIndices(String... indices) {
262 | return new DeleteIndices(indices);
263 | }
264 |
265 | /**
266 | * Instantiates a request that can be used to delete given templates
267 | *
268 | * @param templates the templates names
269 | * @return a {@link DeleteTemplates} request
270 | */
271 | public static DeleteTemplates deleteTemplates(String... templates) {
272 | return new DeleteTemplates(templates);
273 | }
274 |
275 | /**
276 | * Instantiates a request that can be used to delete all indices/documents
277 | *
278 | * @return a {@link DeleteIndices} request
279 | */
280 | public static DeleteIndices deleteAll() {
281 | return new DeleteIndices("_all");
282 | }
283 |
284 | /**
285 | * Instantiates a request that can be used to create a template
286 | *
287 | * @param name the template name
288 | * @return a {@link CreateTemplate} request
289 | */
290 | public static CreateTemplate createTemplate(String name) {
291 | return new CreateTemplate(name);
292 | }
293 |
294 | /**
295 | * Used to check if the index exists or not.
296 | *
297 | * @param index the index name
298 | * @return true if the index exists, false otherwise
299 | */
300 | public Boolean exists(String index) {
301 | return doExecute(new Exists(index));
302 | }
303 |
304 | /**
305 | * Used to check if the document exists or not.
306 | *
307 | * @param index the index of the document
308 | * @param type the type of the document
309 | * @param id the id of the document
310 | * @return true if the document exists, false otherwise
311 | */
312 | public Boolean exists(String index, String type, String id) {
313 | return doExecute(new Exists(index, type, id));
314 | }
315 |
316 | /**
317 | * Counts all the documents in all indices
318 | *
319 | * @return the total number of documents
320 | */
321 | public Long countAll() {
322 | return doExecute(new Count());
323 | }
324 |
325 | /**
326 | * Counts all the documents in given indices
327 | *
328 | * @param indices an array of indices names
329 | * @return the total number of documents
330 | */
331 | public Long count(String... indices) {
332 | return doExecute(new Count(indices));
333 | }
334 |
335 | }
336 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/EsSetupRuntimeException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test;
20 |
21 | /**
22 | * RuntimeException for EsSetup
23 | */
24 | public class EsSetupRuntimeException extends RuntimeException {
25 |
26 | public EsSetupRuntimeException() {
27 | super();
28 | }
29 |
30 | public EsSetupRuntimeException(String message, Throwable cause) {
31 | super(message, cause);
32 | }
33 |
34 | public EsSetupRuntimeException(String message) {
35 | super(message);
36 | }
37 |
38 | public EsSetupRuntimeException(Throwable cause) {
39 | super(cause);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchAdminClient.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.ElementType;
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 | import java.lang.annotation.Target;
10 |
11 | /**
12 | * ElasticsearchAdminClient Annotation
13 | *
14 | * @author tlrx
15 | */
16 | @Retention(RetentionPolicy.RUNTIME)
17 | @Target(ElementType.FIELD)
18 | public @interface ElasticsearchAdminClient {
19 |
20 | /**
21 | * The node's name from which a client is instantiated, default to "elasticsearch-test-node"
22 | */
23 | String nodeName() default ElasticsearchNode.DEFAULT_NODE_NAME;
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchAnalysis.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 |
9 | /**
10 | * ElasticsearchAnalysis Annotation, used to define analysis settings of an
11 | * ElasticsearchIndex
12 | *
13 | * @author tlrx
14 | */
15 | @Retention(RetentionPolicy.RUNTIME)
16 | public @interface ElasticsearchAnalysis {
17 |
18 | /**
19 | * Filters
20 | */
21 | ElasticsearchFilter[] filters() default {};
22 |
23 | /**
24 | * Analyzers
25 | */
26 | ElasticsearchAnalyzer[] analyzers() default {};
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchAnalyzer.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 |
9 | /**
10 | * ElasticsearchAnalyzer annotation, used to define an analyzer in the analysis settings of an index
11 | *
12 | * @author tlrx
13 | */
14 | @Retention(RetentionPolicy.RUNTIME)
15 | public @interface ElasticsearchAnalyzer {
16 |
17 | /**
18 | * The name of the analyzer
19 | */
20 | String name();
21 |
22 | /**
23 | * The name of the tokenizer
24 | */
25 | String tokenizer();
26 |
27 | /**
28 | * Filters names
29 | */
30 | String[] filtersNames() default {};
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchBulkRequest.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.ElementType;
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 | import java.lang.annotation.Target;
10 |
11 | /**
12 | * ElasticsearchData Annotation used to execute Bulk request against a given
13 | * index
14 | *
15 | * @author tlrx
16 | */
17 | @Retention(RetentionPolicy.RUNTIME)
18 | @Target(ElementType.METHOD)
19 | public @interface ElasticsearchBulkRequest {
20 |
21 | /**
22 | * The default index's name used by default on bulk items that don't have an
23 | * explicit index name
24 | */
25 | String defaultIndexName() default "";
26 |
27 | /**
28 | * The default document type name used by default on bulk items that don't
29 | * have an explicit document type
30 | */
31 | String defaultTypeName() default "";
32 |
33 | /**
34 | * The node's name from which a client is instantiated to run bulk request
35 | */
36 | String nodeName() default ElasticsearchNode.DEFAULT_NODE_NAME;
37 |
38 | /**
39 | * JSON file containing the Bulk request items
40 | */
41 | String dataFile() default "";
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchClient.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.ElementType;
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 | import java.lang.annotation.Target;
10 |
11 | /**
12 | * ElasticsearchClient Annotation
13 | *
14 | * @author tlrx
15 | */
16 | @Retention(RetentionPolicy.RUNTIME)
17 | @Target(ElementType.FIELD)
18 | public @interface ElasticsearchClient {
19 |
20 | /**
21 | * The node's name from which a client is instantiated, default to "elasticsearch-test-node"
22 | */
23 | String nodeName() default ElasticsearchNode.DEFAULT_NODE_NAME;
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchFilter.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 |
9 | /**
10 | * ElasticsearchFilter annotation, used to define a filter in the analysis settings of an index
11 | *
12 | * @author tlrx
13 | */
14 | @Retention(RetentionPolicy.RUNTIME)
15 | public @interface ElasticsearchFilter {
16 |
17 | /**
18 | * The name of the filter
19 | */
20 | String name();
21 |
22 | /**
23 | * The type's name of the filter
24 | */
25 | String typeName();
26 |
27 | /**
28 | * Filter settings
29 | */
30 | ElasticsearchSetting[] settings() default {};
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchIndex.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.ElementType;
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 | import java.lang.annotation.Target;
10 |
11 | /**
12 | * ElasticsearchIndex Annotation
13 | *
14 | * @author tlrx
15 | */
16 | @Retention(RetentionPolicy.RUNTIME)
17 | @Target(ElementType.METHOD)
18 | public @interface ElasticsearchIndex {
19 |
20 | /**
21 | * Default index name
22 | */
23 | public static final String DEFAULT_NAME = "test";
24 |
25 | /**
26 | * The index's name, default to "test"
27 | */
28 | String indexName() default DEFAULT_NAME;
29 |
30 | /**
31 | * The node's name from which a client is instantiated to run operations
32 | */
33 | String nodeName() default ElasticsearchNode.DEFAULT_NODE_NAME;
34 |
35 | /**
36 | * Mappings of the index
37 | */
38 | ElasticsearchMapping[] mappings() default {};
39 |
40 | /**
41 | * Index settings, defined with {@link ElasticsearchSetting} annotation
42 | */
43 | ElasticsearchSetting[] settings() default {};
44 |
45 | /**
46 | * Analysis definitions
47 | */
48 | ElasticsearchAnalysis analysis() default @ElasticsearchAnalysis();
49 |
50 | /**
51 | * Index configuration (settings etc), loaded from a file's path
52 | */
53 | String settingsFile() default "";
54 |
55 | /**
56 | * Force the index creation (default to false)
57 | */
58 | boolean forceCreate() default false;
59 |
60 | /**
61 | * Delete all documents in index after test execution (default to false)
62 | */
63 | boolean cleanAfter() default false;
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchIndexes.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.ElementType;
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 | import java.lang.annotation.Target;
10 |
11 | /**
12 | * ElasticsearchIndexes Annotation
13 | *
14 | * This annotation is used to define multiple {@link ElasticsearchIndex}
15 | *
16 | * @author tlrx
17 | */
18 | @Retention(RetentionPolicy.RUNTIME)
19 | @Target(ElementType.METHOD)
20 | public @interface ElasticsearchIndexes {
21 |
22 | /**
23 | * Indexes
24 | */
25 | ElasticsearchIndex[] indexes() default {};
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchMapping.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 |
9 | /**
10 | * ElasticsearchMapping Annotation, used to create mapping for a given document type
11 | *
12 | * @author tlrx
13 | */
14 | @Retention(RetentionPolicy.RUNTIME)
15 | public @interface ElasticsearchMapping {
16 |
17 | /**
18 | * The type's name for which the mapping is defined
19 | */
20 | String typeName();
21 |
22 | /**
23 | * Fields of the mapping
24 | */
25 | ElasticsearchMappingField[] properties() default {};
26 |
27 | /**
28 | * The source's "enabled" value (default to true)
29 | */
30 | boolean source() default true;
31 |
32 | /**
33 | * The source's "compress" value (default to true (since v0.90))
34 | */
35 | boolean compress() default true;
36 |
37 | /**
38 | * Compress threshold value
39 | */
40 | String compressThreshold() default "";
41 |
42 | /**
43 | * Time To Live "enabled" value (default to false)
44 | */
45 | boolean ttl() default false;
46 |
47 | /**
48 | * Time To Live value
49 | */
50 | String ttlValue() default "";
51 |
52 | /**
53 | * Index the document's timestamp using the _timestamp field (default to false)
54 | */
55 | boolean timestamp() default false;
56 |
57 | /**
58 | * The path used to extract the timestamp from the document
59 | * (default to "", meaning the "_timestamp" field should be explicitly set when indexing)
60 | */
61 | String timestampPath() default "";
62 |
63 | /**
64 | * The date format of the "_timestamp" field (default to "dateOptionalTime")
65 | */
66 | String timestampFormat() default "dateOptionalTime";
67 |
68 | /**
69 | * The _parent's type
70 | */
71 | String parent() default "";
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchMappingField.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 |
9 | /**
10 | * ElasticsearchMappingField Annotation, used to define the mapping properties for a given document field
11 | *
12 | * @author tlrx
13 | */
14 | @Retention(RetentionPolicy.RUNTIME)
15 | public @interface ElasticsearchMappingField {
16 |
17 | /**
18 | * Globally defined analyzer
19 | */
20 | public static final String DEFAULT_ANALYZER = "default-analyzer";
21 |
22 | /**
23 | * The field's name for which properties are defined
24 | */
25 | String name();
26 |
27 | /**
28 | * Default field type
29 | */
30 | Types type() default Types.String;
31 |
32 | /**
33 | * Store property (true means "yes", false means "no" and default is set to false)
34 | */
35 | Store store() default Store.No;
36 |
37 | /**
38 | * Index property (analyzed, not_analyzed, no)
39 | */
40 | Index index() default Index.Undefined;
41 |
42 | /**
43 | * Name of the analyzer
44 | */
45 | String analyzerName() default DEFAULT_ANALYZER;
46 |
47 | /**
48 | * The analyzer used to analyze the text contents when analyzed during indexing.
49 | */
50 | String indexAnalyzerName() default DEFAULT_ANALYZER;
51 |
52 | /**
53 | * The analyzer used to analyze the field when part of a query string.
54 | */
55 | String searchAnalyzerName() default DEFAULT_ANALYZER;
56 |
57 | /**
58 | * The term_vector value for analyzed field
59 | */
60 | TermVector termVector() default TermVector.No;
61 |
62 | /**
63 | * The fields
64 | */
65 | ElasticsearchMappingSubField[] fields() default {};
66 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchMappingSubField.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 |
9 | /**
10 | * ElasticsearchMappingField Annotation, used to define the mapping properties for a given document field
11 | *
12 | * @author tlrx
13 | */
14 | @Retention(RetentionPolicy.RUNTIME)
15 | public @interface ElasticsearchMappingSubField {
16 |
17 | /**
18 | * Globally defined analyzer
19 | */
20 | public static final String DEFAULT_ANALYZER = "default-analyzer";
21 |
22 | /**
23 | * The field's name for which properties are defined
24 | */
25 | String name();
26 |
27 | /**
28 | * Default field type
29 | */
30 | Types type() default Types.String;
31 |
32 | /**
33 | * Store property (true means "yes", false means "no" and default is set to false)
34 | */
35 | Store store() default Store.No;
36 |
37 | /**
38 | * Index property (analyzed, not_analyzed, no)
39 | */
40 | Index index() default Index.Undefined;
41 |
42 | /**
43 | * Name of the analyzer
44 | */
45 | String analyzerName() default DEFAULT_ANALYZER;
46 |
47 | /**
48 | * The analyzer used to analyze the text contents when analyzed during indexing.
49 | */
50 | String indexAnalyzerName() default DEFAULT_ANALYZER;
51 |
52 | /**
53 | * The analyzer used to analyze the field when part of a query string.
54 | */
55 | String searchAnalyzerName() default DEFAULT_ANALYZER;
56 |
57 | /**
58 | * The term_vector value for analyzed field
59 | */
60 | TermVector termVector() default TermVector.No;
61 |
62 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchNode.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.ElementType;
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 | import java.lang.annotation.Target;
10 |
11 | /**
12 | * ElasticsearchNode Annotation, used to instantiate Elasticsearch nodes.
13 | *
14 | * The annotation can be placed on Class or Class attributes. By default, the
15 | * node is local, holds data, and has the name "elasticsearch-test-node" and the
16 | * cluster's name "elasticsearch-test-cluster".
17 | *
18 | *
19 | * @author tlrx
20 | */
21 | @Retention(RetentionPolicy.RUNTIME)
22 | @Target({ElementType.FIELD, ElementType.TYPE})
23 | public @interface ElasticsearchNode {
24 |
25 | /**
26 | * Default node name
27 | */
28 | public static final String DEFAULT_NODE_NAME = "elasticsearch-test-node";
29 |
30 | /**
31 | * The node's name, default to "elasticsearch-test-node"
32 | */
33 | String name() default DEFAULT_NODE_NAME;
34 |
35 | /**
36 | * Default cluster name
37 | */
38 | public static final String DEFAULT_CLUSTER_NAME = "elasticsearch-test-cluster";
39 |
40 | /**
41 | * The cluster's name, default to "elasticsearch-test-cluster"
42 | */
43 | String clusterName() default DEFAULT_CLUSTER_NAME;
44 |
45 | /**
46 | * The local property of the node, default to "true"
47 | */
48 | boolean local() default true;
49 |
50 | /**
51 | * The data property of the node, default to "true"
52 | */
53 | boolean data() default true;
54 |
55 | /**
56 | * Node settings, defined with annotations
57 | */
58 | ElasticsearchSetting[] settings() default {};
59 |
60 | /**
61 | * Node settings defined in a configuration file. By default, the file
62 | * /config/elasticsearch.yml is loaded.
63 | */
64 | String configFile() default "config/elasticsearch.yml";
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchSetting.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import org.elasticsearch.common.settings.Settings;
7 |
8 | import java.lang.annotation.ElementType;
9 | import java.lang.annotation.Retention;
10 | import java.lang.annotation.RetentionPolicy;
11 | import java.lang.annotation.Target;
12 |
13 | /**
14 | * ElasticsearchSetting Annotation
15 | *
16 | * This annotation is used to define elasticsearch {@link Settings}
17 | *
18 | * @author tlrx
19 | */
20 | @Retention(RetentionPolicy.RUNTIME)
21 | @Target(ElementType.METHOD)
22 | public @interface ElasticsearchSetting {
23 |
24 | /**
25 | * Name
26 | */
27 | String name();
28 |
29 | /**
30 | * Value
31 | */
32 | String value();
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchTransportClient.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.annotations;
5 |
6 | import java.lang.annotation.ElementType;
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 | import java.lang.annotation.Target;
10 |
11 | /**
12 | * ElasticsearchTransportClient Annotation
13 | *
14 | * @author tlrx
15 | */
16 | @Retention(RetentionPolicy.RUNTIME)
17 | @Target(ElementType.FIELD)
18 | public @interface ElasticsearchTransportClient {
19 |
20 | /**
21 | * The cluster's name, default to "elasticsearch-test-cluster"
22 | */
23 | String clusterName() default ElasticsearchNode.DEFAULT_CLUSTER_NAME;
24 |
25 | /**
26 | * Array of host names, default to "localhost"
27 | */
28 | String[] hostnames() default {"localhost"};
29 |
30 | /**
31 | * Array of port numbers, default to 9300
32 | */
33 | int[] ports() default {9300};
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/Index.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | /**
4 | * Field "index" value.
5 | */
6 | public enum Index {
7 | Undefined, Analyzed, Not_Analyzed, No
8 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/Store.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | /**
4 | * Field "store" value.
5 | */
6 | public enum Store {
7 | Yes, No
8 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/TermVector.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | /**
4 | * Field "term_vector" value.
5 | */
6 | public enum TermVector {
7 | Yes, No, With_Offsets, With_Positions, With_Positions_Offsets
8 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/annotations/Types.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | /**
4 | * Field "type" value.
5 | */
6 | public enum Types {
7 | String, Integer, Long, Boolean, Date, Float, Double, Null
8 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/provider/ClassPathJSONProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.provider;
20 |
21 | import com.github.tlrx.elasticsearch.test.EsSetupRuntimeException;
22 | import org.elasticsearch.common.Preconditions;
23 | import org.elasticsearch.common.io.Streams;
24 |
25 | import java.io.FileNotFoundException;
26 | import java.io.IOException;
27 | import java.io.InputStream;
28 | import java.io.InputStreamReader;
29 |
30 | /**
31 | * A ClassPathJSONProvider is able to load a file from the classpath and returns its content as a JSON String.
32 | */
33 | public class ClassPathJSONProvider implements JSONProvider {
34 |
35 | private Class klass;
36 | private ClassLoader classLoader;
37 | private String path;
38 |
39 | public ClassPathJSONProvider(ClassLoader classLoader, String path) {
40 | Preconditions.checkNotNull(classLoader, "No ClassLoader specified");
41 | this.classLoader = classLoader;
42 | this.path = path;
43 | }
44 |
45 | public ClassPathJSONProvider(Class klass, String path) {
46 | Preconditions.checkNotNull(klass, "No Class specified");
47 | this.klass = klass;
48 | this.path = path;
49 | }
50 |
51 | @Override
52 | public String toJson() {
53 | return toString();
54 | }
55 |
56 | @Override
57 | public String toString() {
58 | try {
59 | if (klass != null) {
60 | InputStream inputStream = klass.getResourceAsStream(path);
61 | if (inputStream == null) {
62 | throw new FileNotFoundException("Resource [" + path + "] not found in classpath with class [" + klass.getName() + "]");
63 | }
64 | return Streams.copyToString(new InputStreamReader(inputStream, "UTF-8"));
65 | } else {
66 | return Streams.copyToStringFromClasspath(classLoader, path);
67 | }
68 | } catch (IOException e) {
69 | throw new EsSetupRuntimeException(e);
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/provider/ClientProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.provider;
20 |
21 | import org.elasticsearch.client.Client;
22 |
23 | /**
24 | * A ClientProvider provides an instance of {@link Client}. This instance will be used for request
25 | * execution in EsSetup class.
26 | */
27 | public interface ClientProvider {
28 |
29 | /**
30 | * Opens the provider.
31 | */
32 | void open();
33 |
34 | /**
35 | * Returns a client instance.
36 | *
37 | * @return
38 | */
39 | Client client();
40 |
41 | /**
42 | * Closes the provider.
43 | */
44 | void close();
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/provider/DefaultClientProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.provider;
20 |
21 | import org.elasticsearch.client.Client;
22 | import org.elasticsearch.common.Preconditions;
23 | import org.elasticsearch.common.unit.TimeValue;
24 |
25 | /**
26 | * DefaultClientProvider uses a given {@link Client} instance. This provider is useful when the client is instantiated
27 | * by a Dependency Injection framework.
28 | */
29 | public class DefaultClientProvider implements ClientProvider {
30 |
31 | private final Client client;
32 | private final boolean closeOnTerminate;
33 |
34 | public DefaultClientProvider(Client client, boolean closeClientOnTerminate) {
35 | Preconditions.checkNotNull(client, "No Client specified");
36 | this.closeOnTerminate = closeClientOnTerminate;
37 | this.client = client;
38 | }
39 |
40 | @Override
41 | public void open() {
42 | // Wait for Yellow status
43 | client().admin().cluster()
44 | .prepareHealth()
45 | .setWaitForYellowStatus()
46 | .setTimeout(TimeValue.timeValueMinutes(1))
47 | .execute()
48 | .actionGet();
49 | }
50 |
51 | @Override
52 | public Client client() {
53 | return client;
54 | }
55 |
56 | @Override
57 | public void close() {
58 | if (closeOnTerminate) {
59 | client().close();
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/provider/JSONProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.provider;
20 |
21 | /**
22 | * JSONProvider provides JSON content as String objects.
23 | */
24 | public interface JSONProvider {
25 | String toJson();
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/provider/LocalClientProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.provider;
20 |
21 |
22 | import org.elasticsearch.client.Client;
23 | import org.elasticsearch.common.io.FileSystemUtils;
24 | import org.elasticsearch.common.network.NetworkUtils;
25 | import org.elasticsearch.common.settings.ImmutableSettings;
26 | import org.elasticsearch.common.settings.Settings;
27 | import org.elasticsearch.common.unit.TimeValue;
28 | import org.elasticsearch.node.Node;
29 | import org.elasticsearch.node.NodeBuilder;
30 |
31 | import java.io.File;
32 |
33 | /**
34 | * LocalClientProvider instantiates a local node with in-memory index store type.
35 | */
36 | public class LocalClientProvider implements ClientProvider {
37 |
38 | private Node node = null;
39 | private Client client = null;
40 | private Settings settings = null;
41 |
42 | public LocalClientProvider() {
43 | }
44 |
45 | public LocalClientProvider(Settings settings) {
46 | this.settings = settings;
47 | }
48 |
49 | @Override
50 | public void open() {
51 | if (node == null || node.isClosed()) {
52 | // Build and start the node
53 | node = NodeBuilder.nodeBuilder().settings(buildNodeSettings()).node();
54 |
55 | // Get a client
56 | client = node.client();
57 |
58 | // Wait for Yellow status
59 | client.admin().cluster()
60 | .prepareHealth()
61 | .setWaitForYellowStatus()
62 | .setTimeout(TimeValue.timeValueMinutes(1))
63 | .execute()
64 | .actionGet();
65 | }
66 | }
67 |
68 | @Override
69 | public Client client() {
70 | return client;
71 | }
72 |
73 | @Override
74 | public void close() {
75 | if (client() != null) {
76 | client.close();
77 | }
78 |
79 | if ((node != null) && (!node.isClosed())) {
80 | node.close();
81 |
82 | FileSystemUtils.deleteRecursively(new File("./target/elasticsearch-test/"), true);
83 | }
84 | }
85 |
86 | protected Settings buildNodeSettings() {
87 | // Build settings
88 | ImmutableSettings.Builder builder = ImmutableSettings.settingsBuilder()
89 | .put("node.name", "node-test-" + System.currentTimeMillis())
90 | .put("node.data", true)
91 | .put("cluster.name", "cluster-test-" + NetworkUtils.getLocalAddress().getHostName())
92 | .put("index.store.type", "memory")
93 | .put("index.store.fs.memory.enabled", "true")
94 | .put("gateway.type", "none")
95 | .put("path.data", "./target/elasticsearch-test/data")
96 | .put("path.work", "./target/elasticsearch-test/work")
97 | .put("path.logs", "./target/elasticsearch-test/logs")
98 | .put("index.number_of_shards", "1")
99 | .put("index.number_of_replicas", "0")
100 | .put("cluster.routing.schedule", "50ms")
101 | .put("node.local", true);
102 |
103 | if (settings != null) {
104 | builder.put(settings);
105 | }
106 |
107 | return builder.build();
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/Count.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import org.elasticsearch.ElasticsearchException;
22 | import org.elasticsearch.action.count.CountResponse;
23 | import org.elasticsearch.client.Client;
24 |
25 | import java.util.Arrays;
26 |
27 | /**
28 | * A {@link Request} used to count the documents stored in indices.
29 | */
30 | public class Count implements Request {
31 |
32 | private String[] indices;
33 |
34 | public Count() {
35 | }
36 |
37 | public Count(String... indices) {
38 | this.indices = indices;
39 | }
40 |
41 | @Override
42 | public Long execute(Client client) throws ElasticsearchException {
43 | CountResponse response = client.prepareCount(indices).execute().actionGet();
44 | return response.getCount();
45 | }
46 |
47 | @Override
48 | public String toString() {
49 | return "count [" +
50 | "indices=" + (indices == null ? null : Arrays.asList(indices)) +
51 | ']';
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/CreateIndex.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import com.github.tlrx.elasticsearch.test.EsSetupRuntimeException;
22 | import com.github.tlrx.elasticsearch.test.provider.JSONProvider;
23 | import org.elasticsearch.ElasticsearchException;
24 | import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
25 | import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
26 | import org.elasticsearch.action.bulk.BulkRequestBuilder;
27 | import org.elasticsearch.action.bulk.BulkResponse;
28 | import org.elasticsearch.client.Client;
29 | import org.elasticsearch.common.settings.ImmutableSettings;
30 | import org.elasticsearch.common.settings.Settings;
31 |
32 | import java.util.ArrayList;
33 | import java.util.List;
34 | import java.util.Map;
35 |
36 | /**
37 | * A {@link Request} used to create indices.
38 | */
39 | public class CreateIndex implements Request {
40 |
41 | private final CreateIndexRequest request;
42 | private final String index;
43 | private final List bulks;
44 |
45 | public CreateIndex(String index) {
46 | this.index = index;
47 | request = new CreateIndexRequest(index);
48 | bulks = new ArrayList();
49 | }
50 |
51 | public CreateIndex withSettings(Settings settings) {
52 | request.settings(settings);
53 | return this;
54 | }
55 |
56 | public CreateIndex withSettings(String source) {
57 | Settings settings = ImmutableSettings.settingsBuilder()
58 | .loadFromSource(source)
59 | .build();
60 | withSettings(settings);
61 | return this;
62 | }
63 |
64 | public CreateIndex withSettings(JSONProvider jsonProvider) {
65 | withSettings(jsonProvider.toJson());
66 | return this;
67 | }
68 |
69 | public CreateIndex withMapping(String type, Map mapping) {
70 | request.mapping(type, mapping);
71 | return this;
72 | }
73 |
74 | public CreateIndex withMapping(String type, String source) {
75 | request.mapping(type, source);
76 | return this;
77 | }
78 |
79 | public CreateIndex withMapping(String type, JSONProvider jsonProvider) {
80 | withMapping(type, jsonProvider.toJson());
81 | return this;
82 | }
83 |
84 | public CreateIndex withSource(String source) {
85 | request.source(source);
86 | return this;
87 | }
88 |
89 | public CreateIndex withSource(JSONProvider jsonProvider) {
90 | request.source(jsonProvider.toJson());
91 | return this;
92 | }
93 |
94 | public CreateIndex withData(JSONProvider jsonProvider) {
95 | bulks.add(jsonProvider);
96 | return this;
97 | }
98 |
99 | @Override
100 | public Void execute(final Client client) throws ElasticsearchException {
101 | BulkRequestBuilder bulkRequestBuilder = null;
102 | try {
103 | if ((bulks != null) && (!bulks.isEmpty())) {
104 | bulkRequestBuilder = client.prepareBulk();
105 | for (JSONProvider jsonProvider : bulks) {
106 | byte[] content = jsonProvider.toJson().getBytes("UTF-8");
107 | bulkRequestBuilder.add(content, 0, content.length, true);
108 | }
109 | }
110 |
111 | CreateIndexResponse response = client.admin().indices().create(request).get();
112 | if ((response.isAcknowledged()) && (bulkRequestBuilder != null)) {
113 | BulkResponse bulkResponse = bulkRequestBuilder.setRefresh(true).execute().actionGet();
114 | if (bulkResponse.hasFailures()) {
115 | throw new EsSetupRuntimeException("Bulk request has failures: "+bulkResponse.buildFailureMessage());
116 | }
117 | }
118 | } catch (Exception e) {
119 | throw new EsSetupRuntimeException(e);
120 | }
121 | return null;
122 | }
123 |
124 | @Override
125 | public String toString() {
126 | return "create index [" +
127 | "index='" + index + '\'' +
128 | ']';
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/CreateTemplate.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import com.github.tlrx.elasticsearch.test.EsSetupRuntimeException;
22 | import com.github.tlrx.elasticsearch.test.provider.JSONProvider;
23 | import org.elasticsearch.ElasticsearchException;
24 | import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateAction;
25 | import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest;
26 | import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse;
27 | import org.elasticsearch.client.Client;
28 | import org.elasticsearch.common.settings.ImmutableSettings;
29 | import org.elasticsearch.common.settings.Settings;
30 |
31 | import java.util.Map;
32 |
33 | /**
34 | * A {@link Request} used to create indices templates.
35 | */
36 | public class CreateTemplate implements Request {
37 |
38 | private final PutIndexTemplateRequest request;
39 | private String name;
40 |
41 | public CreateTemplate(String name) {
42 | this.name = name;
43 | this.request = new PutIndexTemplateRequest(name);
44 | }
45 |
46 | public CreateTemplate withTemplate(String template) {
47 | request.template(template);
48 | return this;
49 | }
50 |
51 | public CreateTemplate withSettings(Settings settings) {
52 | request.settings(settings);
53 | return this;
54 | }
55 |
56 | public CreateTemplate withSettings(String source) {
57 | Settings settings = ImmutableSettings.settingsBuilder()
58 | .loadFromSource(source)
59 | .build();
60 | withSettings(settings);
61 | return this;
62 | }
63 |
64 | public CreateTemplate withSettings(JSONProvider jsonProvider) {
65 | withSettings(jsonProvider.toJson());
66 | return this;
67 | }
68 |
69 | public CreateTemplate withMapping(String type, Map mapping) {
70 | request.mapping(type, mapping);
71 | return this;
72 | }
73 |
74 | public CreateTemplate withMapping(String type, String source) {
75 | request.mapping(type, source);
76 | return this;
77 | }
78 |
79 | public CreateTemplate withMapping(String type, JSONProvider jsonProvider) {
80 | withMapping(type, jsonProvider.toJson());
81 | return this;
82 | }
83 |
84 | public CreateTemplate withSource(String source) {
85 | request.source(source);
86 | return this;
87 | }
88 |
89 | public CreateTemplate withSource(JSONProvider jsonProvider) {
90 | request.source(jsonProvider.toJson());
91 | return this;
92 | }
93 |
94 | @Override
95 | public Void execute(final Client client) throws ElasticsearchException {
96 | try {
97 | PutIndexTemplateResponse response = client.admin().indices().execute(PutIndexTemplateAction.INSTANCE, request).get();
98 |
99 | if (!response.isAcknowledged()) {
100 | throw new EsSetupRuntimeException("Exception when putting index template");
101 | }
102 | } catch (Exception e) {
103 | throw new EsSetupRuntimeException(e);
104 | }
105 | return null;
106 | }
107 |
108 | @Override
109 | public String toString() {
110 | return "create template [" +
111 | "name='" + name + '\'' +
112 | ']';
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/Delete.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import com.github.tlrx.elasticsearch.test.EsSetupRuntimeException;
22 | import com.github.tlrx.elasticsearch.test.provider.JSONProvider;
23 | import org.elasticsearch.ElasticsearchException;
24 | import org.elasticsearch.action.delete.DeleteRequest;
25 | import org.elasticsearch.action.delete.DeleteResponse;
26 | import org.elasticsearch.action.index.IndexRequest;
27 | import org.elasticsearch.action.index.IndexResponse;
28 | import org.elasticsearch.client.Client;
29 |
30 | /**
31 | * A {@link Request} used to delete documents.
32 | */
33 | public class Delete implements Request {
34 |
35 | private final DeleteRequest request;
36 |
37 | public Delete(String index, String type, String id) {
38 | request = new DeleteRequest(index, type, id).refresh(true);
39 | }
40 |
41 | @Override
42 | public Void execute(final Client client) throws ElasticsearchException {
43 | try {
44 | DeleteResponse response = client.delete(request).get();
45 | } catch (Exception e) {
46 | throw new EsSetupRuntimeException(e);
47 | }
48 | return null;
49 | }
50 |
51 | @Override
52 | public String toString() {
53 | return "delete [" +
54 | "index='" + request.index() + "\'," +
55 | "type='" + request.type() + '\'' +
56 | "id='" + request.id() + '\'' +
57 | ']';
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/DeleteIndices.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import org.elasticsearch.ElasticsearchException;
22 | import org.elasticsearch.client.Client;
23 |
24 | import java.util.Arrays;
25 |
26 | /**
27 | * A {@link Request} used to delete one or more indices.
28 | */
29 | public class DeleteIndices implements Request {
30 |
31 | private String[] indices;
32 |
33 | public DeleteIndices(String... indices) {
34 | this.indices = indices;
35 | }
36 |
37 | @Override
38 | public Void execute(Client client) throws ElasticsearchException {
39 | client.admin().indices().prepareDelete(indices).execute().actionGet();
40 | return null;
41 | }
42 |
43 | @Override
44 | public String toString() {
45 | return "delete indices [" +
46 | "indices=" + (indices == null ? null : Arrays.asList(indices)) +
47 | ']';
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/DeleteTemplates.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import com.github.tlrx.elasticsearch.test.EsSetupRuntimeException;
22 | import org.elasticsearch.ElasticsearchException;
23 | import org.elasticsearch.action.admin.cluster.state.ClusterStateAction;
24 | import org.elasticsearch.action.admin.cluster.state.ClusterStateRequestBuilder;
25 | import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
26 | import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateAction;
27 | import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest;
28 | import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateResponse;
29 | import org.elasticsearch.client.Client;
30 | import org.elasticsearch.common.collect.Lists;
31 |
32 | import java.util.Arrays;
33 | import java.util.Collection;
34 | import java.util.HashSet;
35 | import java.util.Set;
36 | import java.util.concurrent.ExecutionException;
37 |
38 | /**
39 | * A {@link com.github.tlrx.elasticsearch.test.request.Request} used to delete one, many templates or all templates.
40 | */
41 | public class DeleteTemplates implements Request {
42 | /**
43 | * Templates to delete
44 | */
45 | private final String[] templates;
46 | /**
47 | * Fail-fast mode (disabled by default)
48 | */
49 | private boolean failFast = false;
50 |
51 | /**
52 | * Constructor
53 | *
54 | * @param templates Templates to delete, if no template is specified all templates will be used
55 | */
56 | public DeleteTemplates(String... templates) {
57 | this.templates = templates;
58 | }
59 |
60 | /**
61 | * Enables fail-fast mode (if an template can not be deleted, others won't)
62 | */
63 | public DeleteTemplates failFast() {
64 | this.failFast = true;
65 | return this;
66 | }
67 |
68 | /**
69 | * Get the names of templates to delete, if no template is provided the complete list of templates is retrieved
70 | */
71 | private Collection getTemplates(Client client) {
72 | Collection templatesColl;
73 | if (this.templates==null || this.templates.length==0) {
74 | // Retrieve all templates
75 | ClusterStateRequestBuilder clusterStateRequestBuilder =
76 | ClusterStateAction.INSTANCE.newRequestBuilder(client.admin().cluster())
77 | .all().setMetaData(false);
78 | ClusterStateResponse clusterStateResponse = clusterStateRequestBuilder.execute().actionGet();
79 | templatesColl = Lists.newArrayList(clusterStateResponse.getState().getMetaData().getTemplates().keysIt());
80 | } else {
81 | // Use provided templates
82 | templatesColl = Arrays.asList(templates);
83 | }
84 | return templatesColl;
85 | }
86 | @Override
87 | public Void execute(Client client) throws ElasticsearchException {
88 | Set unacknowledgedTemplates = new HashSet();
89 | EsSetupRuntimeException runtimeException = null;
90 | for (String template : getTemplates(client)) {
91 | try {
92 | DeleteIndexTemplateRequest request = new DeleteIndexTemplateRequest(template);
93 | DeleteIndexTemplateResponse response = client.admin().indices()
94 | .execute(DeleteIndexTemplateAction.INSTANCE, request).get();
95 | if (!response.isAcknowledged()) {
96 | if (failFast) {
97 | throw new EsSetupRuntimeException("Exception when deleting index template: " + template);
98 | } else {
99 | unacknowledgedTemplates.add(template);
100 | }
101 | }
102 | } catch (InterruptedException e) {
103 | Thread.currentThread().interrupt();
104 | runtimeException = handleException(runtimeException, e);
105 | } catch (ExecutionException e) {
106 | runtimeException = handleException(runtimeException, e);
107 | }
108 | }
109 | if (runtimeException != null) {
110 | throw runtimeException;
111 | } else if (!unacknowledgedTemplates.isEmpty()) {
112 | throw new EsSetupRuntimeException("Exception when deleting index template: " + unacknowledgedTemplates);
113 | }
114 | return null;
115 | }
116 |
117 | private EsSetupRuntimeException handleException(EsSetupRuntimeException currentException, Exception newException) {
118 | if (failFast) {
119 | throw new EsSetupRuntimeException(newException);
120 | } else if (currentException == null) {
121 | currentException = new EsSetupRuntimeException(newException);
122 | }
123 | return currentException;
124 | }
125 |
126 | @Override
127 | public String toString() {
128 | return "delete templates [" +
129 | "templates=" + (templates == null ? null : Arrays.asList(templates)) +
130 | ']';
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/Exists.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import org.elasticsearch.ElasticsearchException;
22 | import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
23 | import org.elasticsearch.action.get.GetResponse;
24 | import org.elasticsearch.client.Client;
25 |
26 | /**
27 | * A {@link Request} used to check if a document or index exists.
28 | */
29 | public class Exists implements Request {
30 |
31 | private String index;
32 | private String type;
33 | private String id;
34 |
35 | public Exists(String index) {
36 | this.index = index;
37 | }
38 |
39 | public Exists(String index, String type, String id) {
40 | this(index);
41 | this.type = type;
42 | this.id = id;
43 | }
44 |
45 | @Override
46 | public Boolean execute(Client client) throws ElasticsearchException {
47 | if ((index != null) && (type != null) && (id != null)) {
48 |
49 | // Check if a document exists
50 | GetResponse response = client.prepareGet(index, type, id).setRefresh(true).execute().actionGet();
51 | return response.isExists();
52 |
53 | } else {
54 |
55 | // Check if index exists
56 | IndicesExistsResponse response = client.admin().indices().prepareExists(index).execute().actionGet();
57 | return response.isExists();
58 | }
59 | }
60 |
61 | @Override
62 | public String toString() {
63 | return "exists [" +
64 | "index='" + index + '\'' +
65 | ", type='" + type + '\'' +
66 | ", id='" + id + '\'' +
67 | ']';
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/Index.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import com.github.tlrx.elasticsearch.test.EsSetupRuntimeException;
22 | import com.github.tlrx.elasticsearch.test.provider.JSONProvider;
23 | import org.elasticsearch.ElasticsearchException;
24 | import org.elasticsearch.action.index.IndexRequest;
25 | import org.elasticsearch.action.index.IndexResponse;
26 | import org.elasticsearch.client.Client;
27 |
28 | /**
29 | * A {@link com.github.tlrx.elasticsearch.test.request.Request} used to index documents.
30 | */
31 | public class Index implements Request {
32 |
33 | private final IndexRequest request;
34 |
35 | public Index(String index, String type) {
36 | request = new IndexRequest(index, type).refresh(true);
37 | }
38 |
39 | public Index(String index, String type, String id) {
40 | this(index, type);
41 | request.id(id);
42 | }
43 |
44 | public Index withSource(String source) {
45 | request.source(source);
46 | return this;
47 | }
48 |
49 | public Index withSource(JSONProvider jsonProvider) {
50 | request.source(jsonProvider.toJson());
51 | return this;
52 | }
53 |
54 | @Override
55 | public Void execute(final Client client) throws ElasticsearchException {
56 | try {
57 | IndexResponse response = client.index(request).get();
58 | } catch (Exception e) {
59 | throw new EsSetupRuntimeException(e);
60 | }
61 | return null;
62 | }
63 |
64 | @Override
65 | public String toString() {
66 | return "index [" +
67 | "index='" + request.index() + "\'," +
68 | "type='" + request.type() + '\'' +
69 | ']';
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/request/Request.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to ElasticSearch and Shay Banon under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. ElasticSearch licenses this
6 | * file to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations
17 | * under the License.
18 | */
19 | package com.github.tlrx.elasticsearch.test.request;
20 |
21 | import org.elasticsearch.ElasticsearchException;
22 | import org.elasticsearch.client.Client;
23 |
24 | /**
25 | * A request executed by {@link com.github.tlrx.elasticsearch.test.EsSetup}. Requests can return a result.
26 | *
27 | * @param
28 | */
29 | public interface Request {
30 |
31 | T execute(Client client) throws ElasticsearchException;
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/ClassLevelElasticsearchAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers;
5 |
6 | import java.lang.annotation.Annotation;
7 | import java.util.Map;
8 |
9 |
10 | /**
11 | * Interface of Class-Level Elasticsearch's annotations handlers.
12 | *
13 | * @author tlrx
14 | */
15 | public interface ClassLevelElasticsearchAnnotationHandler extends ElasticsearchAnnotationHandler {
16 |
17 | /**
18 | * Call the handler at class instanciation time
19 | *
20 | * @param testClass
21 | * @param context Test execution context
22 | * @throws Exception
23 | * @see org.junit.BeforeClass
24 | */
25 | public void beforeClass(Object testClass, Map context) throws Exception;
26 |
27 | /**
28 | * Handle an annotation at class instanciation time
29 | *
30 | * @param annotation
31 | * @param testClass
32 | * @param context Test execution context
33 | * @throws Exception
34 | * @see org.junit.BeforeClass
35 | */
36 | public void handleBeforeClass(Annotation annotation, Object testClass, Map context) throws Exception;
37 |
38 | /**
39 | * Handle an annotation at class destroying time
40 | *
41 | * @param annotation
42 | * @param testClass
43 | * @param context Test execution context
44 | * @throws Exception
45 | * @see org.junit.AfterClass
46 | */
47 | public void handleAfterClass(Annotation annotation, Object testClass, Map context) throws Exception;
48 |
49 | /**
50 | * Call the handler at class destroying time
51 | *
52 | * @param testClass
53 | * @param context Test execution context
54 | * @throws Exception
55 | * @see org.junit.AfterClass
56 | */
57 | public void afterClass(Object testClass, Map context) throws Exception;
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/ElasticsearchAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers;
5 |
6 | import java.lang.annotation.Annotation;
7 |
8 | /**
9 | * Marker interface for Elasticsearch's annotations handlers.
10 | *
11 | * @author tlrx
12 | */
13 | public interface ElasticsearchAnnotationHandler {
14 |
15 | /**
16 | * Check if the handler supports a given annotation
17 | *
18 | * @param annotation
19 | * @return true if the annotation is supported
20 | */
21 | public boolean support(Annotation annotation);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/FieldLevelElasticsearchAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers;
5 |
6 | import java.lang.annotation.Annotation;
7 | import java.lang.reflect.Field;
8 | import java.util.Map;
9 |
10 | /**
11 | * Interface of Field-Level (class attributes) Elasticsearch's annotations
12 | * handlers.
13 | *
14 | * @author tlrx
15 | */
16 | public interface FieldLevelElasticsearchAnnotationHandler extends ElasticsearchAnnotationHandler {
17 |
18 | /**
19 | * Handle an annotation on a Field before executing a first test
20 | *
21 | * @param annotation
22 | * @param instance
23 | * @param context Test execution context
24 | * @param field
25 | * @throws Exception
26 | */
27 | public void handleField(Annotation annotation, Object instance, Map context, Field field) throws Exception;
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/MethodLevelElasticsearchAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers;
5 |
6 | import java.lang.annotation.Annotation;
7 | import java.util.Map;
8 |
9 |
10 | /**
11 | * Interface of Method-Level Elasticsearch's annotations handlers.
12 | *
13 | * @author tlrx
14 | */
15 | public interface MethodLevelElasticsearchAnnotationHandler extends ElasticsearchAnnotationHandler {
16 |
17 | /**
18 | * Handle an annotation before method execution
19 | *
20 | * @param annotation
21 | * @param instance
22 | * @param context Test execution context
23 | * @throws Exception
24 | * @see org.junit.Before
25 | */
26 | public void handleBefore(Annotation annotation, Object instance, Map context) throws Exception;
27 |
28 | /**
29 | * Handle an annotation after method execution
30 | *
31 | * @param annotation
32 | * @param instance
33 | * @param context Test execution context
34 | * @throws Exception
35 | * @see org.junit.After
36 | */
37 | public void handleAfter(Annotation annotation, Object instance, Map context) throws Exception;
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/annotations/AbstractAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.support.junit.handlers.annotations;
2 |
3 | import org.elasticsearch.client.AdminClient;
4 | import org.elasticsearch.client.Client;
5 | import org.elasticsearch.node.Node;
6 |
7 | import java.util.Map;
8 |
9 | /**
10 | * Abstract annotation Handler
11 | *
12 | * @author tlrx
13 | */
14 | public class AbstractAnnotationHandler {
15 |
16 |
17 | /**
18 | * Creates an {@link Client} given a node's name and the current
19 | * execution context
20 | *
21 | * @param context
22 | * @param nodeName
23 | * @return
24 | * @throws Exception
25 | */
26 | protected Client client(Map context, String nodeName) throws Exception {
27 | // Get a node
28 | Node node = (Node) context.get(nodeName);
29 | if (node == null) {
30 | if (context.size() == 1) {
31 | node = (Node) context.values().iterator().next();
32 | } else {
33 | throw new Exception("Unable to manage index: nodeName must be defined.");
34 | }
35 | }
36 | return node.client();
37 | }
38 |
39 | /**
40 | * Creates an {@link AdminClient} given a node's name and the current
41 | * execution context
42 | *
43 | * @param context
44 | * @param nodeName
45 | * @return
46 | * @throws Exception
47 | */
48 | protected AdminClient admin(Map context, String nodeName) throws Exception {
49 | return client(context, nodeName).admin();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/annotations/ElasticsearchAdminClientAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers.annotations;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchAdminClient;
7 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.FieldLevelElasticsearchAnnotationHandler;
8 | import org.elasticsearch.node.Node;
9 |
10 | import java.lang.annotation.Annotation;
11 | import java.lang.reflect.Field;
12 | import java.util.Map;
13 | import java.util.logging.Logger;
14 |
15 | /**
16 | * Handle {@link ElasticsearchAdminClient} annotation
17 | *
18 | * @author tlrx
19 | */
20 | public class ElasticsearchAdminClientAnnotationHandler implements FieldLevelElasticsearchAnnotationHandler {
21 |
22 | private final static Logger LOGGER = Logger.getLogger(ElasticsearchAdminClientAnnotationHandler.class.getName());
23 |
24 | public boolean support(Annotation annotation) {
25 | return (annotation instanceof ElasticsearchAdminClient);
26 | }
27 |
28 | public void handleField(Annotation annotation, Object instance, Map context, Field field) {
29 | ElasticsearchAdminClient elasticsearchAdminClient = (ElasticsearchAdminClient) annotation;
30 | String nodeName = elasticsearchAdminClient.nodeName();
31 |
32 | if (nodeName != null) {
33 | Node node = (Node) context.get(nodeName);
34 | if (node != null) {
35 | try {
36 | field.setAccessible(true);
37 | field.set(instance, node.client().admin());
38 | } catch (Exception e) {
39 | LOGGER.severe("Unable to set node for field " + field.getName() + ": " + e.getMessage());
40 | }
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/annotations/ElasticsearchBulkRequestAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers.annotations;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchBulkRequest;
7 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.MethodLevelElasticsearchAnnotationHandler;
8 | import org.elasticsearch.action.bulk.BulkResponse;
9 | import org.elasticsearch.client.Client;
10 |
11 | import java.io.ByteArrayOutputStream;
12 | import java.io.InputStream;
13 | import java.lang.annotation.Annotation;
14 | import java.util.Map;
15 | import java.util.logging.Logger;
16 |
17 | /**
18 | * Handle {@link ElasticsearchBulkRequest} annotation
19 | *
20 | * @author tlrx
21 | */
22 | public class ElasticsearchBulkRequestAnnotationHandler extends AbstractAnnotationHandler implements MethodLevelElasticsearchAnnotationHandler {
23 |
24 | private final static Logger LOGGER = Logger.getLogger(ElasticsearchBulkRequestAnnotationHandler.class.getName());
25 |
26 | public boolean support(Annotation annotation) {
27 | return (annotation instanceof ElasticsearchBulkRequest);
28 | }
29 |
30 | public void handleBefore(Annotation annotation, Object instance, Map context) throws Exception {
31 | ElasticsearchBulkRequest elasticsearchBulkRequest = (ElasticsearchBulkRequest) annotation;
32 |
33 | InputStream input = null;
34 | ByteArrayOutputStream output = null;
35 |
36 | try {
37 | // Get an AdminClient for the node
38 | Client client = client(context, elasticsearchBulkRequest.nodeName());
39 |
40 | // Load file as byte array
41 | input = getClass().getResourceAsStream(elasticsearchBulkRequest.dataFile());
42 | if (input == null) {
43 | input = Thread.currentThread()
44 | .getContextClassLoader()
45 | .getResourceAsStream(
46 | elasticsearchBulkRequest.dataFile());
47 | }
48 | if (input == null) {
49 | throw new IllegalArgumentException("Bulk file " + elasticsearchBulkRequest.dataFile() + " not found!");
50 | }
51 | output = new ByteArrayOutputStream();
52 |
53 | byte[] buffer = new byte[512 * 1024];
54 | while (input.read(buffer) > 0) {
55 | output.write(buffer);
56 | }
57 |
58 | buffer = output.toByteArray();
59 |
60 | // Execute the BulkRequest
61 | BulkResponse response = client.prepareBulk()
62 | .add(buffer, 0, buffer.length, true, elasticsearchBulkRequest.defaultIndexName(), elasticsearchBulkRequest.defaultTypeName())
63 | .setRefresh(true)
64 | .execute()
65 | .actionGet();
66 |
67 | LOGGER.info(String.format("Bulk request for data file '%s' executed in %d ms with %sfailures",
68 | elasticsearchBulkRequest.dataFile(),
69 | response.getTookInMillis(),
70 | response.hasFailures() ? "" : "no "));
71 | } finally {
72 | try {
73 | if (output != null) {
74 | output.close();
75 | }
76 | } catch (Exception e) {
77 | }
78 | try {
79 | if (input != null) {
80 | input.close();
81 | }
82 | } catch (Exception e) {
83 | }
84 | }
85 | }
86 |
87 | public void handleAfter(Annotation annotation, Object instance, Map context) throws Exception {
88 | // Nothing to do here
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/annotations/ElasticsearchClientAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers.annotations;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchClient;
7 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.FieldLevelElasticsearchAnnotationHandler;
8 | import org.elasticsearch.node.Node;
9 |
10 | import java.lang.annotation.Annotation;
11 | import java.lang.reflect.Field;
12 | import java.util.Map;
13 | import java.util.logging.Logger;
14 |
15 | /**
16 | * Handle {@link ElasticsearchClient} annotation
17 | *
18 | * @author tlrx
19 | */
20 | public class ElasticsearchClientAnnotationHandler implements FieldLevelElasticsearchAnnotationHandler {
21 |
22 | private final static Logger LOGGER = Logger.getLogger(ElasticsearchClientAnnotationHandler.class.getName());
23 |
24 | public boolean support(Annotation annotation) {
25 | return (annotation instanceof ElasticsearchClient);
26 | }
27 |
28 | public void handleField(Annotation annotation, Object instance, Map context, Field field) {
29 | ElasticsearchClient elasticsearchClient = (ElasticsearchClient) annotation;
30 | String nodeName = elasticsearchClient.nodeName();
31 |
32 | if (nodeName != null) {
33 | Node node = (Node) context.get(nodeName);
34 | if (node != null) {
35 | try {
36 | field.setAccessible(true);
37 | field.set(instance, node.client());
38 | } catch (Exception e) {
39 | LOGGER.severe("Unable to set node for field " + field.getName() + ":" + e.getMessage());
40 | }
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/annotations/ElasticsearchIndexesAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers.annotations;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchIndex;
7 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchIndexes;
8 |
9 | import java.lang.annotation.Annotation;
10 | import java.util.Map;
11 |
12 | /**
13 | * Handle {@link ElasticsearchIndexes} annotation
14 | *
15 | * @author tlrx
16 | */
17 | public class ElasticsearchIndexesAnnotationHandler extends ElasticsearchIndexAnnotationHandler {
18 |
19 | public boolean support(Annotation annotation) {
20 | return (annotation instanceof ElasticsearchIndexes);
21 | }
22 |
23 | public void handleBefore(Annotation annotation, Object instance, Map context) throws Exception {
24 | // Manage @ElasticsearchIndexes
25 | for (ElasticsearchIndex index : ((ElasticsearchIndexes) annotation).indexes()) {
26 | buildIndex((ElasticsearchIndex) index, context);
27 | }
28 | }
29 |
30 | public void handleAfter(Annotation annotation, Object instance, Map context) throws Exception {
31 | // TODO clean after Nothing
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/annotations/ElasticsearchNodeAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers.annotations;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchNode;
7 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchSetting;
8 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.ClassLevelElasticsearchAnnotationHandler;
9 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.FieldLevelElasticsearchAnnotationHandler;
10 | import org.elasticsearch.common.io.FileSystemUtils;
11 | import org.elasticsearch.common.settings.ImmutableSettings;
12 | import org.elasticsearch.common.settings.ImmutableSettings.Builder;
13 | import org.elasticsearch.common.settings.Settings;
14 | import org.elasticsearch.node.Node;
15 | import org.elasticsearch.node.NodeBuilder;
16 |
17 | import java.io.File;
18 | import java.lang.annotation.Annotation;
19 | import java.lang.reflect.Field;
20 | import java.util.Map;
21 |
22 | /**
23 | * Handle {@link ElasticsearchNode} annotation
24 | *
25 | * @author tlrx
26 | */
27 | public class ElasticsearchNodeAnnotationHandler implements ClassLevelElasticsearchAnnotationHandler, FieldLevelElasticsearchAnnotationHandler {
28 |
29 | /**
30 | * Elasticsearch home directory
31 | */
32 | private static final String ES_HOME = "./target/elasticsearch-test";
33 | private static final String NODE_NAME = "node.name";
34 |
35 | public boolean support(Annotation annotation) {
36 | return (annotation instanceof ElasticsearchNode);
37 | }
38 |
39 | public void beforeClass(Object testClass, Map context) throws Exception {
40 | // Nothing to do here
41 | }
42 |
43 | public void handleBeforeClass(Annotation annotation, Object testClass, Map context) {
44 | // Instantiate a node
45 | buildNode((ElasticsearchNode) annotation, context);
46 | }
47 |
48 | public void handleAfterClass(Annotation annotation, Object testClass, Map context) {
49 | // Nothing to do here
50 | }
51 |
52 | public void afterClass(Object testClass, Map context) throws Exception {
53 | for (Object obj : context.values()) {
54 | if (obj instanceof Node) {
55 | Node node = (Node) obj;
56 |
57 | if (!node.isClosed()) {
58 | node.close();
59 | }
60 | }
61 | }
62 | FileSystemUtils.deleteRecursively(new File(ES_HOME));
63 | }
64 |
65 | public void handleField(Annotation annotation, Object instance, Map context, Field field) throws Exception {
66 | // Get the node
67 | Node node = buildNode((ElasticsearchNode) annotation, context);
68 |
69 | // Sets the node as the field's value
70 | try {
71 | field.setAccessible(true);
72 | field.set(instance, node);
73 | } catch (Exception e) {
74 | throw new Exception("Exception when setting the node:" + e.getMessage(), e);
75 | }
76 | }
77 |
78 | /**
79 | * Builds & start a new node, or retrieves an existing one from context
80 | *
81 | * @param elasticsearchNode
82 | * @param context
83 | * @return a {@link Node}
84 | */
85 | private Node buildNode(ElasticsearchNode elasticsearchNode, Map context) {
86 |
87 | // Create the node's settings
88 | Settings settings = buildNodeSettings(elasticsearchNode);
89 |
90 | // Search for the node in current context
91 | String nodeName = settings.get(NODE_NAME);
92 | Node node = (Node) context.get(nodeName);
93 |
94 | if (node == null) {
95 | // No node with this name has been found, let's instantiate a new one
96 | node = NodeBuilder.nodeBuilder()
97 | .settings(settings)
98 | .local(elasticsearchNode.local())
99 | .node();
100 | context.put(nodeName, node);
101 | }
102 | return node;
103 | }
104 |
105 | /**
106 | * Build node settings
107 | */
108 | private Settings buildNodeSettings(ElasticsearchNode elasticsearchNode) {
109 |
110 | // Build default settings
111 | Builder settingsBuilder = ImmutableSettings.settingsBuilder()
112 | .put(NODE_NAME, elasticsearchNode.name())
113 | .put("node.data", elasticsearchNode.data())
114 | .put("cluster.name", elasticsearchNode.clusterName())
115 | .put("index.store.type", "memory")
116 | .put("index.store.fs.memory.enabled", "true")
117 | .put("gateway.type", "none")
118 | .put("path.data", ES_HOME + "/data")
119 | .put("path.work", ES_HOME + "/work")
120 | .put("path.logs", ES_HOME + "/logs")
121 | .put("index.number_of_shards", "1")
122 | .put("index.number_of_replicas", "0");
123 |
124 | // Loads settings from configuration file
125 | Settings configSettings = ImmutableSettings.settingsBuilder().loadFromClasspath(elasticsearchNode.configFile()).build();
126 | settingsBuilder.put(configSettings);
127 |
128 | // Other settings
129 | ElasticsearchSetting[] settings = elasticsearchNode.settings();
130 | for (ElasticsearchSetting setting : settings) {
131 | settingsBuilder.put(setting.name(), setting.value());
132 | }
133 |
134 | // Build the settings
135 | return settingsBuilder.build();
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/handlers/annotations/ElasticsearchTransportClientAnnotationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.test.support.junit.handlers.annotations;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchTransportClient;
7 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.ClassLevelElasticsearchAnnotationHandler;
8 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.FieldLevelElasticsearchAnnotationHandler;
9 | import org.elasticsearch.client.transport.TransportClient;
10 | import org.elasticsearch.common.settings.ImmutableSettings;
11 | import org.elasticsearch.common.settings.Settings;
12 | import org.elasticsearch.common.transport.InetSocketTransportAddress;
13 |
14 | import java.lang.annotation.Annotation;
15 | import java.lang.reflect.Field;
16 | import java.util.Map;
17 | import java.util.logging.Logger;
18 |
19 | /**
20 | * Handle {@link ElasticsearchTransportClient} annotation
21 | *
22 | * @author tlrx
23 | */
24 | public class ElasticsearchTransportClientAnnotationHandler implements ClassLevelElasticsearchAnnotationHandler, FieldLevelElasticsearchAnnotationHandler {
25 |
26 | private final static Logger LOGGER = Logger.getLogger(ElasticsearchTransportClientAnnotationHandler.class.getName());
27 |
28 | public boolean support(Annotation annotation) {
29 | return (annotation instanceof ElasticsearchTransportClient);
30 | }
31 |
32 | public void handleField(Annotation annotation, Object instance, Map context, Field field) {
33 | ElasticsearchTransportClient elasticsearchTransportClient = (ElasticsearchTransportClient) annotation;
34 |
35 | // Settings
36 | Settings settings = ImmutableSettings.settingsBuilder()
37 | .put("cluster.name", String.valueOf(elasticsearchTransportClient.clusterName()))
38 | .build();
39 |
40 | TransportClient client = new TransportClient(settings);
41 |
42 | int n = 0;
43 | for (String host : elasticsearchTransportClient.hostnames()) {
44 | client.addTransportAddress(new InetSocketTransportAddress(host, elasticsearchTransportClient.ports()[n++]));
45 | }
46 |
47 | if (client != null) {
48 | try {
49 | field.setAccessible(true);
50 | field.set(instance, client);
51 |
52 | context.put(client.toString(), client);
53 | } catch (Exception e) {
54 | LOGGER.severe("Unable to set transport client for field " + field.getName() + ":" + e.getMessage());
55 | }
56 | }
57 | }
58 |
59 | public void beforeClass(Object testClass, Map context) throws Exception {
60 | // Nothing to do here
61 | }
62 |
63 | public void handleBeforeClass(Annotation annotation, Object testClass, Map context) throws Exception {
64 | // Nothing to do here
65 | }
66 |
67 | public void handleAfterClass(Annotation annotation, Object testClass, Map context) throws Exception {
68 | // Nothing to do here
69 | }
70 |
71 | public void afterClass(Object testClass, Map context) throws Exception {
72 | // Closing all TransportClient
73 | for (Object obj : context.values()) {
74 | if (obj instanceof TransportClient) {
75 | TransportClient client = (TransportClient) obj;
76 | client.close();
77 | }
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/rules/AbstractElasticsearchRule.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.support.junit.rules;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.ElasticsearchAnnotationHandler;
4 | import org.junit.rules.TestRule;
5 | import org.junit.runner.Description;
6 | import org.junit.runners.model.Statement;
7 |
8 | import java.lang.annotation.Annotation;
9 | import java.lang.reflect.Field;
10 | import java.util.ArrayList;
11 | import java.util.Collection;
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | /**
16 | * Abstract {@link TestRule}
17 | */
18 | public abstract class AbstractElasticsearchRule implements TestRule {
19 |
20 | /**
21 | * Handlers for specific elasticsearch annotations
22 | */
23 | protected List handlers = new ArrayList();
24 |
25 | /**
26 | * Test execution context
27 | */
28 | protected final Map context;
29 |
30 | /**
31 | * Constructor
32 | *
33 | * @param context
34 | */
35 | public AbstractElasticsearchRule(Map context) {
36 | super();
37 | this.context = context;
38 | }
39 |
40 | /**
41 | * Add an elasticsearch annotation handler
42 | *
43 | * @param handler
44 | * @return true (as specified by Collection.add)
45 | */
46 | public boolean addHandler(ElasticsearchAnnotationHandler handler) {
47 | return handlers.add(handler);
48 | }
49 |
50 | /**
51 | * {@inheritDoc}
52 | */
53 | public Statement apply(final Statement base, final Description description) {
54 | return new Statement() {
55 | @Override
56 | public void evaluate() throws Throwable {
57 | try {
58 | // Execute handlers before statement execution
59 | before(description.getAnnotations());
60 |
61 | // Execute statements
62 | base.evaluate();
63 | } finally {
64 | // Execute handlers after statement execution
65 | after(description.getAnnotations());
66 | }
67 | }
68 | };
69 | }
70 |
71 | /**
72 | * Process before statement execution
73 | *
74 | * @param annotations
75 | */
76 | protected void before(Collection annotations) throws Exception {
77 | // Nothing here
78 | }
79 |
80 | /**
81 | * Process after statement execution
82 | *
83 | * @param annotations
84 | */
85 | protected void after(Collection annotations) throws Exception {
86 | // Nothing here
87 | }
88 |
89 | /**
90 | * Get all declared and inherited attributes of a given class
91 | *
92 | * @param type
93 | * @return a {@link List} of {@link Field}
94 | */
95 | protected List getAllFields(Class> type) {
96 | List fields = new ArrayList();
97 | if (type != null) {
98 | for (Field field : type.getDeclaredFields()) {
99 | fields.add(field);
100 | }
101 |
102 | if (type.getSuperclass() != null) {
103 | fields.addAll(getAllFields(type.getSuperclass()));
104 | }
105 | }
106 | return fields;
107 | }
108 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/rules/ElasticsearchClassRule.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.support.junit.rules;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.ClassLevelElasticsearchAnnotationHandler;
4 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.ElasticsearchAnnotationHandler;
5 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.FieldLevelElasticsearchAnnotationHandler;
6 | import org.junit.rules.TestRule;
7 | import org.junit.runners.model.TestClass;
8 |
9 | import java.lang.annotation.Annotation;
10 | import java.lang.reflect.Field;
11 | import java.util.Collection;
12 | import java.util.Map;
13 |
14 | /**
15 | * Simple {@link TestRule} automatically added to test classes that have an
16 | * {@link ESRunner}.
17 | *
18 | * This class adds BeforeClass and AfterClass class rules, which will call
19 | * {@link ElasticsearchAnnotationHandler}s.
20 | */
21 | public class ElasticsearchClassRule extends AbstractElasticsearchRule {
22 |
23 | /**
24 | * The current test class
25 | */
26 | private final TestClass testClass;
27 |
28 | /**
29 | * Constructor
30 | *
31 | * @param testClass
32 | */
33 | public ElasticsearchClassRule(Map context, TestClass testClass) {
34 | super(context);
35 | this.testClass = testClass;
36 | }
37 |
38 | @Override
39 | protected void before(Collection annotations) throws Exception {
40 | // Manage annotations on class
41 | executeBeforeOrAfterClassHandlers(true, annotations);
42 | }
43 |
44 | @Override
45 | protected void after(Collection annotations) throws Exception {
46 | // Manage annotations before destroying object class
47 | executeBeforeOrAfterClassHandlers(false, annotations);
48 | }
49 |
50 | /**
51 | * Execute handlers at Before/AfterClass time
52 | *
53 | * @throws Exception
54 | */
55 | private void executeBeforeOrAfterClassHandlers(boolean isBefore, Collection annotations) throws Exception {
56 | if ((annotations != null) && (!annotations.isEmpty())) {
57 |
58 | // Handle annotations at Before or After time
59 | for (ElasticsearchAnnotationHandler handler : handlers) {
60 | if (handler instanceof ClassLevelElasticsearchAnnotationHandler) {
61 | ClassLevelElasticsearchAnnotationHandler classHandler = (ClassLevelElasticsearchAnnotationHandler) handler;
62 |
63 | // Call the handler first
64 | if (isBefore) {
65 | classHandler.beforeClass(testClass, context);
66 | }
67 |
68 | // Iterate over annotations
69 | for (Annotation annotation : annotations) {
70 | if (handler.support(annotation)) {
71 | if (isBefore) {
72 | classHandler.handleBeforeClass(annotation, testClass, context);
73 | } else {
74 | classHandler.handleAfterClass(annotation, testClass, context);
75 | }
76 | }
77 | }
78 |
79 | // Call the handler after
80 | if (!isBefore) {
81 | classHandler.afterClass(testClass, context);
82 | }
83 | }
84 | }
85 | }
86 | }
87 |
88 | /**
89 | * Manage annotations on class attributes (fields)
90 | *
91 | * @param instance test class instance
92 | * @throws Exception
93 | */
94 | public void executeBeforeTestExecution(Object instance) throws Exception {
95 | for (ElasticsearchAnnotationHandler handler : handlers) {
96 | if (handler instanceof FieldLevelElasticsearchAnnotationHandler) {
97 | FieldLevelElasticsearchAnnotationHandler fieldHandler = (FieldLevelElasticsearchAnnotationHandler) handler;
98 |
99 | for (Field field : getAllFields(instance.getClass())) {
100 | // Iterate over annotations
101 | for (Annotation annotation : field.getAnnotations()) {
102 | if (handler.support(annotation)) {
103 | fieldHandler.handleField(annotation, instance, context, field);
104 | }
105 | }
106 | }
107 | }
108 | }
109 | }
110 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/rules/ElasticsearchFieldRule.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.support.junit.rules;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.ElasticsearchAnnotationHandler;
4 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.FieldLevelElasticsearchAnnotationHandler;
5 | import org.junit.rules.TestRule;
6 | import org.junit.runners.model.TestClass;
7 |
8 | import java.lang.annotation.Annotation;
9 | import java.lang.reflect.Field;
10 | import java.util.Map;
11 |
12 | /**
13 | * Simple {@link TestRule} automatically added to test classes that have an
14 | * {@link ESRunner}.
15 | *
16 | * This class manages class attributes (fields) and call
17 | * {@link ElasticsearchAnnotationHandler}s.
18 | */
19 | public class ElasticsearchFieldRule extends AbstractElasticsearchRule {
20 |
21 | /**
22 | * Constructor
23 | *
24 | * @param testClass
25 | */
26 | public ElasticsearchFieldRule(Map context, TestClass testClass) {
27 | super(context);
28 | }
29 |
30 | /**
31 | * Manage annotations on class attributes (fields)
32 | *
33 | * @param instance test class instance
34 | * @throws Exception
35 | */
36 | public void executeBeforeTestExecution(Object instance) throws Exception {
37 | for (ElasticsearchAnnotationHandler handler : handlers) {
38 | if (handler instanceof FieldLevelElasticsearchAnnotationHandler) {
39 | FieldLevelElasticsearchAnnotationHandler fieldHandler = (FieldLevelElasticsearchAnnotationHandler) handler;
40 |
41 | for (Field field : getAllFields(instance.getClass())) {
42 | // Iterate over annotations
43 | for (Annotation annotation : field.getAnnotations()) {
44 | if (handler.support(annotation)) {
45 | fieldHandler.handleField(annotation, instance, context, field);
46 | }
47 | }
48 | }
49 | }
50 | }
51 | }
52 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/rules/ElasticsearchTestRule.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.support.junit.rules;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.ElasticsearchAnnotationHandler;
4 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.MethodLevelElasticsearchAnnotationHandler;
5 | import org.junit.rules.TestRule;
6 |
7 | import java.lang.annotation.Annotation;
8 | import java.util.Collection;
9 | import java.util.Map;
10 | import java.util.logging.Logger;
11 |
12 | /**
13 | * Simple {@link TestRule} automatically added to test classes that have an {@link ESRunner}.
14 | *
15 | * This class adds Before and After class rules, which will call {@link ElasticsearchAnnotationHandler}s.
16 | */
17 | public class ElasticsearchTestRule extends AbstractElasticsearchRule {
18 |
19 | private final static Logger LOGGER = Logger.getLogger(ElasticsearchTestRule.class.getName());
20 |
21 | /**
22 | * The current test instance
23 | */
24 | private final Object instance;
25 |
26 | /**
27 | * Constructor
28 | *
29 | * @param testInstance
30 | */
31 | public ElasticsearchTestRule(Map context, Object testInstance) {
32 | super(context);
33 | this.instance = testInstance;
34 | }
35 |
36 | @Override
37 | protected void before(Collection annotations) throws Exception {
38 | executeBeforeOrAfterMethodHandlers(true, annotations);
39 | }
40 |
41 | @Override
42 | protected void after(Collection annotations) throws Exception {
43 | executeBeforeOrAfterMethodHandlers(false, annotations);
44 | }
45 |
46 | /**
47 | * Execute handlers at Before/After method time
48 | *
49 | * @throws Exception
50 | */
51 | private void executeBeforeOrAfterMethodHandlers(boolean isBefore, Collection annotations) throws Exception {
52 | if ((annotations != null) && (!annotations.isEmpty())) {
53 |
54 | // Handle annotations at Before or after time
55 | for (ElasticsearchAnnotationHandler handler : handlers) {
56 | if (handler instanceof MethodLevelElasticsearchAnnotationHandler) {
57 |
58 | // Iterate over annotations
59 | for (Annotation annotation : annotations) {
60 | if (handler.support(annotation)) {
61 | if (isBefore) {
62 | ((MethodLevelElasticsearchAnnotationHandler) handler).handleBefore(annotation, instance, context);
63 | } else {
64 | try {
65 | ((MethodLevelElasticsearchAnnotationHandler) handler).handleAfter(annotation, instance, context);
66 | } catch (Exception e) {
67 | LOGGER.severe(e.getMessage());
68 | }
69 | }
70 | }
71 | }
72 | }
73 | }
74 | }
75 | }
76 | }
--------------------------------------------------------------------------------
/src/main/java/com/github/tlrx/elasticsearch/test/support/junit/runners/ElasticsearchRunner.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.support.junit.runners;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.handlers.annotations.*;
4 | import com.github.tlrx.elasticsearch.test.support.junit.rules.ElasticsearchClassRule;
5 | import com.github.tlrx.elasticsearch.test.support.junit.rules.ElasticsearchFieldRule;
6 | import com.github.tlrx.elasticsearch.test.support.junit.rules.ElasticsearchTestRule;
7 | import org.elasticsearch.common.netty.util.internal.ConcurrentHashMap;
8 | import org.junit.rules.TestRule;
9 | import org.junit.runners.BlockJUnit4ClassRunner;
10 | import org.junit.runners.model.InitializationError;
11 |
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | /**
16 | * JUnit Runner used to run test classes that have Elasticsearch annotations.
17 | *
18 | * @author tlrx
19 | */
20 | public class ElasticsearchRunner extends BlockJUnit4ClassRunner {
21 |
22 | /**
23 | * Map used to store test execution context
24 | */
25 | Map context = new ConcurrentHashMap();
26 |
27 | /**
28 | * Constructor
29 | *
30 | * @param klass
31 | * @throws InitializationError
32 | */
33 | public ElasticsearchRunner(Class> klass) throws InitializationError {
34 | super(klass);
35 | }
36 |
37 | @Override
38 | protected List getTestRules(Object target) {
39 | // Get BlockJUnit4ClassRunner's default class rules
40 | List testRules = super.getTestRules(target);
41 |
42 | // Instantiate a specific JUnit TestRule
43 | ElasticsearchTestRule testRule = new ElasticsearchTestRule(context, target);
44 |
45 | // Declares the elasticsearch annotations handlers to use
46 | // Be careful, order is important
47 | testRule.addHandler(new ElasticsearchIndexesAnnotationHandler());
48 | testRule.addHandler(new ElasticsearchIndexAnnotationHandler());
49 | testRule.addHandler(new ElasticsearchBulkRequestAnnotationHandler());
50 |
51 | // Add a TestRule to manage method-level Elasticsearch annotations
52 | testRules.add(testRule);
53 |
54 | return testRules;
55 | }
56 |
57 | @Override
58 | protected List classRules() {
59 | // Get BlockJUnit4ClassRunner's default class rules
60 | List classRules = super.classRules();
61 |
62 | // Instantiate a specific JUnit TestRule, executed before/after every test class instantiation
63 | ElasticsearchClassRule classRule = new ElasticsearchClassRule(context, getTestClass());
64 |
65 | // Declares the elasticsearch annotations handlers to use
66 | // Be careful, order is important
67 | classRule.addHandler(new ElasticsearchNodeAnnotationHandler());
68 | classRule.addHandler(new ElasticsearchTransportClientAnnotationHandler());
69 |
70 | // Add a ClassRule to manage class-level Elasticsearch annotations
71 | classRules.add(classRule);
72 |
73 | return classRules;
74 | }
75 |
76 | @Override
77 | protected Object createTest() throws Exception {
78 | Object instance = super.createTest();
79 |
80 | // Instantiate a specific JUnit TestRule, executed before every test class instantiation
81 | ElasticsearchFieldRule fieldsRule = new ElasticsearchFieldRule(context, getTestClass());
82 |
83 | // Declares the elasticsearch annotations handlers to use
84 | // Be careful, order is important
85 | fieldsRule.addHandler(new ElasticsearchNodeAnnotationHandler());
86 | fieldsRule.addHandler(new ElasticsearchClientAnnotationHandler());
87 | fieldsRule.addHandler(new ElasticsearchAdminClientAnnotationHandler());
88 | fieldsRule.addHandler(new ElasticsearchTransportClientAnnotationHandler());
89 |
90 | // Manage annotations on class attributes
91 | fieldsRule.executeBeforeTestExecution(instance);
92 |
93 | return instance;
94 | }
95 |
96 | }
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/samples/core/VersionTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.samples.core;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchClient;
7 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchIndex;
8 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchNode;
9 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
10 | import org.elasticsearch.action.index.IndexResponse;
11 | import org.elasticsearch.client.Client;
12 | import org.elasticsearch.common.xcontent.XContentBuilder;
13 | import org.elasticsearch.common.xcontent.json.JsonXContent;
14 | import org.elasticsearch.index.VersionType;
15 | import org.elasticsearch.index.engine.VersionConflictEngineException;
16 | import org.junit.Test;
17 | import org.junit.runner.RunWith;
18 |
19 | import java.io.IOException;
20 |
21 | import static org.junit.Assert.*;
22 |
23 | /**
24 | * Test Java API / Core / Index : Versionning
25 | *
26 | * @author tlrx
27 | */
28 | @RunWith(ElasticsearchRunner.class)
29 | @ElasticsearchNode
30 | public class VersionTest {
31 |
32 | @ElasticsearchClient
33 | Client client;
34 |
35 | @Test
36 | @ElasticsearchIndex(indexName = "library")
37 | public void indexInternalVersion() throws IOException {
38 | XContentBuilder builder = JsonXContent.contentBuilder();
39 |
40 | // Book #1
41 | builder.startObject()
42 | .field("title", "Les Miserables")
43 | .field("author", "Victor Hugo")
44 | .endObject();
45 |
46 | // Index book #1
47 | IndexResponse response = client.prepareIndex("library", "book", "1")
48 | .setSource(builder)
49 | .execute()
50 | .actionGet();
51 |
52 | assertEquals("First document version must be 1", 1, response.getVersion());
53 |
54 | // Modify book #1
55 | builder = JsonXContent.contentBuilder().startObject()
56 | .field("title", "Les Misérables")
57 | .field("author", "Victor Hugo")
58 | .endObject();
59 |
60 |
61 | // Update book #1
62 | response = client.prepareIndex("library", "book", "1")
63 | .setSource(builder)
64 | .execute()
65 | .actionGet();
66 |
67 | assertEquals("Updated version must be 2", 2, response.getVersion());
68 |
69 | // Try to update book #1 with a wrong version number
70 | try {
71 | response = client.prepareIndex("library", "book", "1")
72 | .setSource(builder)
73 | .setVersion(1)
74 | .execute().actionGet();
75 |
76 | fail("Expected a VersionConflictEngineException");
77 | } catch (VersionConflictEngineException e) {
78 | assertNotNull(e);
79 | assertEquals("Current version must be 2", 2, e.getCurrentVersion());
80 | }
81 |
82 | // Update book #1 with a right version number
83 | response = client.prepareIndex("library", "book", "1")
84 | .setSource(builder)
85 | .setVersion(2)
86 | .execute().actionGet();
87 |
88 | assertEquals("Updated version must be 3", 3, response.getVersion());
89 |
90 | // Try to update book #1 with a wrong version number
91 | try {
92 | response = client.prepareIndex("library", "book", "1")
93 | .setSource(builder)
94 | .setVersion(5)
95 | .execute().actionGet();
96 |
97 | fail("Expected a VersionConflictEngineException");
98 | } catch (VersionConflictEngineException e) {
99 | assertNotNull(e);
100 | assertEquals("Current version must be 3", 3, e.getCurrentVersion());
101 | }
102 | }
103 |
104 |
105 | @Test
106 | @ElasticsearchIndex(indexName = "library")
107 | public void indexExternalVersion() throws IOException {
108 | XContentBuilder builder = JsonXContent.contentBuilder();
109 |
110 | // Book #2
111 | builder.startObject()
112 | .field("title", "Notre Dame de Paris")
113 | .field("author", "Victor Hugo")
114 | .endObject();
115 |
116 | long startVersion = System.currentTimeMillis();
117 |
118 | // Try to index book #2 with a custom version but no external
119 | try {
120 | client.prepareIndex("library", "book", "2")
121 | .setSource(builder)
122 | .setVersion(startVersion)
123 | .execute()
124 | .actionGet();
125 |
126 | fail("Expected a VersionConflictEngineException");
127 | } catch (VersionConflictEngineException e) {
128 | assertNotNull(e);
129 | assertEquals("Current version must be -1", -1, e.getCurrentVersion());
130 | }
131 |
132 | // Index book #2 with a custom version with external
133 | IndexResponse response = client.prepareIndex("library", "book", "2")
134 | .setSource(builder)
135 | .setVersion(startVersion)
136 | .setVersionType(VersionType.EXTERNAL)
137 | .execute()
138 | .actionGet();
139 |
140 | assertEquals("Document version must be incremented", startVersion, response.getVersion());
141 |
142 | // Modify book #2
143 | builder = JsonXContent.contentBuilder().startObject()
144 | .field("title", "Notre-Dame de Paris")
145 | .field("author", "Victor Hugo")
146 | .endObject();
147 |
148 | // Update book #2 without version control
149 | response = client.prepareIndex("library", "book", "2")
150 | .setSource(builder)
151 | .execute()
152 | .actionGet();
153 |
154 | assertEquals("Document updated must have an incremented version number", startVersion + 1, response.getVersion());
155 |
156 | // Try to index book #2 with lower version number
157 | try {
158 | response = client.prepareIndex("library", "book", "2")
159 | .setSource(builder)
160 | .setVersion(startVersion - 10)
161 | .setVersionType(VersionType.EXTERNAL)
162 | .execute()
163 | .actionGet();
164 |
165 | fail("Expected a VersionConflictEngineException");
166 | } catch (VersionConflictEngineException e) {
167 | assertNotNull(e);
168 | assertEquals(startVersion + 1, e.getCurrentVersion());
169 | }
170 |
171 | // Try to index book #2 with same version number
172 | try {
173 | response = client.prepareIndex("library", "book", "2")
174 | .setSource(builder)
175 | .setVersion(startVersion + 1)
176 | .setVersionType(VersionType.EXTERNAL)
177 | .execute()
178 | .actionGet();
179 |
180 | fail("Expected a VersionConflictEngineException");
181 | } catch (VersionConflictEngineException e) {
182 | assertNotNull(e);
183 | assertEquals(startVersion + 1, e.getCurrentVersion());
184 | }
185 |
186 | // Try to index book #2 with greater version number
187 | response = client.prepareIndex("library", "book", "2")
188 | .setSource(builder)
189 | .setVersion(startVersion + 10)
190 | .setVersionType(VersionType.EXTERNAL)
191 | .execute()
192 | .actionGet();
193 | assertEquals("Updated version must be " + startVersion + 10, startVersion + 10, response.getVersion());
194 |
195 | // Try to index book #2 with lower version number and no version_type = external
196 | try {
197 | response = client.prepareIndex("library", "book", "2")
198 | .setSource(builder)
199 | .setVersion(startVersion + 5)
200 | .setVersionType(VersionType.EXTERNAL)
201 | .execute()
202 | .actionGet();
203 |
204 | fail("Expected a VersionConflictEngineException");
205 | } catch (VersionConflictEngineException e) {
206 | assertNotNull(e);
207 | assertEquals(startVersion + 10, e.getCurrentVersion());
208 | }
209 |
210 | // Update book #2 with same version number but no version_type = external
211 | response = client.prepareIndex("library", "book", "2")
212 | .setSource(builder)
213 | .setVersion(startVersion + 10)
214 | .execute()
215 | .actionGet();
216 |
217 | assertEquals("Document updated must have an incremented version number", startVersion + 11, response.getVersion());
218 |
219 | // Try to index book #2 with greater version number and no version_type = external
220 | try {
221 | response = client.prepareIndex("library", "book", "2")
222 | .setSource(builder)
223 | .setVersion(startVersion + 30)
224 | .execute()
225 | .actionGet();
226 |
227 | fail("Expected a VersionConflictEngineException");
228 | } catch (VersionConflictEngineException e) {
229 | assertNotNull(e);
230 | assertEquals(startVersion + 11, e.getCurrentVersion());
231 | }
232 | }
233 | }
234 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/samples/indices/AliasesTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.samples.indices;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.*;
7 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
8 | import org.elasticsearch.action.admin.indices.alias.IndicesAliasesResponse;
9 | import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
10 | import org.elasticsearch.action.get.GetResponse;
11 | import org.elasticsearch.action.index.IndexResponse;
12 | import org.elasticsearch.action.search.SearchResponse;
13 | import org.elasticsearch.client.AdminClient;
14 | import org.elasticsearch.client.Client;
15 | import org.elasticsearch.common.xcontent.json.JsonXContent;
16 | import org.elasticsearch.node.Node;
17 | import org.junit.Test;
18 | import org.junit.runner.RunWith;
19 |
20 | import java.io.IOException;
21 |
22 | import static org.junit.Assert.*;
23 |
24 | /**
25 | * Test Java API / Indices : Aliases
26 | *
27 | * @author tlrx
28 | */
29 | @RunWith(ElasticsearchRunner.class)
30 | public class AliasesTest {
31 |
32 | @ElasticsearchNode(name = "node0")
33 | Node node0;
34 |
35 | @ElasticsearchNode(name = "node1")
36 | Node node1;
37 |
38 | @ElasticsearchAdminClient(nodeName = "node0")
39 | AdminClient adminClient;
40 |
41 | @ElasticsearchClient(nodeName = "node1")
42 | Client client;
43 |
44 | @Test
45 | @ElasticsearchIndexes(indexes = {
46 | @ElasticsearchIndex(indexName = "library1", nodeName = "node0"),
47 | @ElasticsearchIndex(indexName = "library2", nodeName = "node0"),
48 | @ElasticsearchIndex(indexName = "library3", nodeName = "node0")
49 | })
50 | public void testAliases() throws IOException {
51 |
52 | // Drop "library" index if already exists
53 | IndicesExistsResponse existsResponse = adminClient.indices().prepareExists("library").execute().actionGet();
54 | if (existsResponse.isExists()) {
55 | adminClient.indices().prepareDelete("library").execute().actionGet();
56 | }
57 |
58 | // Create an alias "library" that targets the index "library1"
59 | IndicesAliasesResponse aliasReponse = adminClient.indices().prepareAliases()
60 | .addAlias("library1", "library")
61 | .execute()
62 | .actionGet();
63 | assertTrue(aliasReponse.isAcknowledged());
64 |
65 | // Index book #1 in the index "library1"
66 | IndexResponse indexResponse = client
67 | .prepareIndex("library1", "book", "1")
68 | .setRefresh(true)
69 | .setSource(
70 | JsonXContent.contentBuilder().startObject()
71 | .field("title", "Les Miserables")
72 | .field("author", "Victor Hugo").endObject())
73 | .execute().actionGet();
74 | assertNotNull(indexResponse.getId());
75 |
76 | // Retrieves book #1 on index "library1"
77 | GetResponse getResponse = client.prepareGet("library1", "book", "1").execute().actionGet();
78 | assertTrue(getResponse.isExists());
79 |
80 | // Retrieves book #1 on alias "library"
81 | getResponse = client.prepareGet("library", "book", "1").execute().actionGet();
82 | assertTrue(getResponse.isExists());
83 |
84 | // Index another book #1 in the index "library2"
85 | indexResponse = client
86 | .prepareIndex("library2", "book", "1")
87 | .setRefresh(true)
88 | .setSource(
89 | JsonXContent.contentBuilder().startObject()
90 | .field("title", "Notre-Dame de Paris")
91 | .field("author", "Victor Hugo").endObject())
92 | .execute().actionGet();
93 | assertNotNull(indexResponse.getId());
94 |
95 | // Retrieves another book #1 on index "library2"
96 | getResponse = client.prepareGet("library2", "book", "1").execute().actionGet();
97 | assertTrue(getResponse.isExists());
98 |
99 | // Create an alias "library" that targets the index "library2"
100 | aliasReponse = adminClient.indices().prepareAliases()
101 | .addAlias("library2", "library")
102 | .execute()
103 | .actionGet();
104 | assertTrue(aliasReponse.isAcknowledged());
105 |
106 | // Search for all books in alias "library"
107 | SearchResponse searchResponse = client.prepareSearch("library").execute().actionGet();
108 | assertEquals(2, searchResponse.getHits().getTotalHits());
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/samples/indices/OptimizeTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.samples.indices;
2 |
3 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchAdminClient;
4 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchClient;
5 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchNode;
6 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
7 | import org.elasticsearch.action.admin.indices.status.DocsStatus;
8 | import org.elasticsearch.action.admin.indices.status.IndicesStatusResponse;
9 | import org.elasticsearch.action.bulk.BulkRequestBuilder;
10 | import org.elasticsearch.action.bulk.BulkResponse;
11 | import org.elasticsearch.action.count.CountResponse;
12 | import org.elasticsearch.action.delete.DeleteResponse;
13 | import org.elasticsearch.action.index.IndexRequest;
14 | import org.elasticsearch.client.AdminClient;
15 | import org.elasticsearch.client.Client;
16 | import org.elasticsearch.common.xcontent.json.JsonXContent;
17 | import org.elasticsearch.node.Node;
18 | import org.junit.Before;
19 | import org.junit.Test;
20 | import org.junit.runner.RunWith;
21 |
22 | import java.io.IOException;
23 | import java.util.logging.Logger;
24 |
25 | import static org.junit.Assert.assertEquals;
26 |
27 | /**
28 | * Test Java API / Indices : Optimize
29 | *
30 | * @author tlrx
31 | */
32 | @RunWith(ElasticsearchRunner.class)
33 | public class OptimizeTest {
34 |
35 | private final static Logger LOGGER = Logger.getLogger(OptimizeTest.class.getName());
36 |
37 | @ElasticsearchNode
38 | Node node0;
39 |
40 | @ElasticsearchClient
41 | Client client;
42 |
43 | @ElasticsearchAdminClient
44 | AdminClient admin;
45 |
46 | private static int NB = 500;
47 | private static String INDEX = "my_index";
48 | private static String TYPE = "my_type";
49 | private static int deleted = 0;
50 |
51 | @Before
52 | public void setUp() throws IOException {
53 |
54 | // Creates NB documents
55 | BulkRequestBuilder bulkRequestBuilder = new BulkRequestBuilder(client);
56 |
57 | for (int i = 0; i < NB; i++) {
58 | IndexRequest indexRequest = new IndexRequest(INDEX)
59 | .type(TYPE)
60 | .id(String.valueOf(i))
61 | .source(JsonXContent.contentBuilder()
62 | .startObject()
63 | .field("title", "Object #" + i)
64 | .endObject()
65 | );
66 | bulkRequestBuilder.add(indexRequest);
67 | }
68 |
69 | BulkResponse bulkResponse = bulkRequestBuilder.setRefresh(true).execute().actionGet();
70 | LOGGER.info(String.format("Bulk request executed in %d ms, %d document(s) indexed, failures : %s.\r\n", bulkResponse.getTookInMillis(), NB, bulkResponse.hasFailures()));
71 |
72 | // Deletes some documents
73 | for (int i = 0; i < NB; i = i + 9) {
74 | DeleteResponse deleteResponse = client
75 | .prepareDelete(INDEX, TYPE, String.valueOf(i))
76 | .setRefresh(true)
77 | .execute()
78 | .actionGet();
79 |
80 | if (!deleteResponse.isFound()) {
81 | LOGGER.info(String.format("Unable to delete document [id:%d], not found.\r\n", i));
82 | } else {
83 | deleted++;
84 | LOGGER.info(String.format("Document [id:%d] deleted.\r\n", i));
85 | }
86 | }
87 | LOGGER.info(String.format("%d document(s) deleted.\r\n", deleted));
88 | }
89 |
90 | @Test
91 | public void testOptimize() {
92 |
93 | // Count documents number
94 | CountResponse countResponse = client.prepareCount(INDEX).setTypes(TYPE).execute().actionGet();
95 | assertEquals((NB - deleted), countResponse.getCount());
96 |
97 | // Retrieves document status for the index
98 | IndicesStatusResponse status = admin.indices().prepareStatus(INDEX).execute().actionGet();
99 | DocsStatus docsStatus = status.getIndex(INDEX).getDocs();
100 |
101 | // Check docs status
102 | LOGGER.info(String.format("DocsStatus before optimize: %d numDocs, %d maxDocs, %d deletedDocs\r\n", docsStatus.getNumDocs(), docsStatus.getMaxDoc(), docsStatus.getDeletedDocs()));
103 | assertEquals((NB - deleted), docsStatus.getNumDocs());
104 | assertEquals(NB, docsStatus.getMaxDoc());
105 | assertEquals(deleted, docsStatus.getDeletedDocs());
106 |
107 | // Now optimize the index
108 | admin.indices().prepareOptimize(INDEX)
109 | .setFlush(true)
110 | .setOnlyExpungeDeletes(true)
111 | .setWaitForMerge(true)
112 | .execute()
113 | .actionGet();
114 |
115 | // Retrieves document status gain
116 | docsStatus = admin.indices().prepareStatus(INDEX).execute().actionGet().getIndex(INDEX).getDocs();
117 |
118 | // Check again docs status
119 | LOGGER.info(String.format("DocsStatus after optimize: %d numDocs, %d maxDocs, %d deletedDocs\r\n", docsStatus.getNumDocs(), docsStatus.getMaxDoc(), docsStatus.getDeletedDocs()));
120 | assertEquals((NB - deleted), docsStatus.getNumDocs());
121 | assertEquals((NB - deleted), docsStatus.getMaxDoc());
122 | // Must be zero
123 | assertEquals(0, docsStatus.getDeletedDocs());
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/samples/indices/analyze/AnalyzeTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.samples.indices.analyze;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchAdminClient;
7 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchNode;
8 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
9 | import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse;
10 | import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse.AnalyzeToken;
11 | import org.elasticsearch.client.AdminClient;
12 | import org.junit.Test;
13 | import org.junit.runner.RunWith;
14 |
15 | import java.util.List;
16 | import java.util.logging.Logger;
17 |
18 | import static org.junit.Assert.assertEquals;
19 |
20 | /**
21 | * Test Java API / Indices / Analyze
22 | *
23 | * @author tlrx
24 | */
25 | @RunWith(ElasticsearchRunner.class)
26 | @ElasticsearchNode
27 | public class AnalyzeTest {
28 |
29 | private final static Logger LOGGER = Logger.getLogger(AnalyzeTest.class.getName());
30 |
31 | @ElasticsearchAdminClient
32 | AdminClient adminClient;
33 |
34 | @Test
35 | public void testUAXUrlEmailTokenizer() {
36 |
37 | // Analyze a string with uax_url_email tokenizer
38 | AnalyzeResponse response = adminClient.indices()
39 | .prepareAnalyze("My email address is foo@bar.com")
40 | .setTokenizer("uax_url_email")
41 | .execute()
42 | .actionGet();
43 |
44 | assertEquals(5, response.getTokens().size());
45 | printTokens(response.getTokens());
46 |
47 | // Analyze another string
48 | response = adminClient.indices()
49 | .prepareAnalyze("But I also own foo.bar@domain.com, bar.foo@domain.com and mys web site is http://www.elasticsearch.org/is-so-great?truth=true feel free to visit it")
50 | .setTokenizer("uax_url_email")
51 | .execute()
52 | .actionGet();
53 |
54 | assertEquals(17, response.getTokens().size());
55 | printTokens(response.getTokens());
56 | }
57 |
58 | /**
59 | * Prints a token list on standard out
60 | *
61 | * @param tokens
62 | */
63 | private void printTokens(List tokens) {
64 | if (tokens != null) {
65 | LOGGER.info(String.format("Printing %d tokens:\r\n", tokens.size()));
66 | for (AnalyzeToken token : tokens) {
67 | LOGGER.info(String.format("\tToken %d term=[%s], type=[%s], startOffset=[%d], endOffset=[%d]\r\n",
68 | token.getPosition(), token.getTerm(), token.getType(),
69 | token.getStartOffset(), token.getEndOffset()));
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/samples/search/FilterTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.github.tlrx.elasticsearch.samples.search;
5 |
6 | import com.github.tlrx.elasticsearch.test.annotations.*;
7 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
8 | import org.elasticsearch.action.search.SearchResponse;
9 | import org.elasticsearch.client.Client;
10 | import org.elasticsearch.index.query.FilterBuilders;
11 | import org.elasticsearch.index.query.QueryBuilders;
12 | import org.junit.Test;
13 | import org.junit.runner.RunWith;
14 |
15 | import java.io.IOException;
16 |
17 | import static org.junit.Assert.assertEquals;
18 |
19 | /**
20 | * Test Java API / Search : Filters
21 | *
22 | * @author tlrx
23 | */
24 | @RunWith(ElasticsearchRunner.class)
25 | @ElasticsearchNode
26 | public class FilterTest {
27 |
28 | private static final String INDEX = "books";
29 |
30 | @ElasticsearchClient
31 | Client client;
32 |
33 | @Test
34 | @ElasticsearchIndex(indexName = INDEX,
35 | mappings = {@ElasticsearchMapping(typeName = "book",
36 | properties = {
37 | @ElasticsearchMappingField(name = "title", store = Store.Yes, type = Types.String),
38 | @ElasticsearchMappingField(name = "tags", store = Store.Yes, type = Types.String),
39 | @ElasticsearchMappingField(name = "year", store = Store.Yes, type = Types.Integer),
40 | @ElasticsearchMappingField(name = "author.firstname", store = Store.Yes, type = Types.String),
41 | @ElasticsearchMappingField(name = "author.lastname", store = Store.Yes, type = Types.String)
42 | })
43 | })
44 | @ElasticsearchBulkRequest(dataFile = "com/github/tlrx/elasticsearch/samples/search/FilterTest.json")
45 | public void testFilters() throws IOException {
46 |
47 | // Verify if bulk import succeed
48 | SearchResponse response = client.prepareSearch(INDEX).setQuery(QueryBuilders.matchAllQuery()).execute().actionGet();
49 | assertEquals(7L, response.getHits().totalHits());
50 |
51 | // Search for match_all and filter "tags:french"
52 | response = client.prepareSearch(INDEX)
53 | .setQuery(QueryBuilders.matchAllQuery())
54 | .setPostFilter(FilterBuilders.termFilter("tags", "french"))
55 | .execute()
56 | .actionGet();
57 | assertEquals(7L, response.getHits().totalHits());
58 |
59 | // Search for match_all and filter "tags:poetry"
60 | response = client.prepareSearch(INDEX)
61 | .setQuery(QueryBuilders.matchAllQuery())
62 | .setPostFilter(FilterBuilders.termFilter("tags", "poetry"))
63 | .execute()
64 | .actionGet();
65 | assertEquals(3L, response.getHits().totalHits());
66 |
67 | // Search for match_all and filter "tags:literature" and "year:1829"
68 | response = client.prepareSearch(INDEX)
69 | .setQuery(QueryBuilders.matchAllQuery())
70 | .setPostFilter(FilterBuilders.andFilter(
71 | FilterBuilders.termFilter("tags", "literature"),
72 | FilterBuilders.termFilter("year", "1829")))
73 | .execute()
74 | .actionGet();
75 | assertEquals(2L, response.getHits().totalHits());
76 |
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/EsSetupTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test;
2 |
3 |
4 | import org.elasticsearch.client.Client;
5 | import org.elasticsearch.client.transport.TransportClient;
6 | import org.elasticsearch.common.transport.InetSocketTransportAddress;
7 | import org.junit.After;
8 | import org.junit.Before;
9 | import org.junit.Test;
10 |
11 | import static com.github.tlrx.elasticsearch.test.EsSetup.*;
12 | import static org.junit.Assert.*;
13 |
14 | /**
15 | * Test class for {@link EsSetup}
16 | */
17 | public class EsSetupTest {
18 |
19 | EsSetup esSetup;
20 |
21 | @Before
22 | public void setUp() throws Exception {
23 |
24 | // Using a local node & client
25 | esSetup = new EsSetup();
26 |
27 | /* Using a remote client
28 | Client client = new TransportClient()
29 | .addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
30 | esSetup = new EsSetup(client);
31 | */
32 |
33 | /* Using specific Settings
34 | esSetup = new EsSetup();
35 | */
36 |
37 | esSetup.execute(
38 | deleteAll(),
39 |
40 | createIndex("catalog-2009"),
41 |
42 | createIndex("catalog-2010")
43 | .withSource("{\n" +
44 | " \"settings\" : {\n" +
45 | " \"number_of_shards\" : 2\n" +
46 | " },\n" +
47 | " \"mappings\" : {\n" +
48 | " \"type2010\" : {\n" +
49 | " \"_source\" : { \"enabled\" : false },\n" +
50 | " \"properties\" : {\n" +
51 | " \"field1\" : { \"type\" : \"string\", \"index\" : \"not_analyzed\" }\n" +
52 | " }\n" +
53 | " }\n" +
54 | " }\n" +
55 | "}"),
56 |
57 | createIndex("catalog-2011")
58 | .withSource(fromClassPath("com/github/tlrx/elasticsearch/test/indices/catalog-2011.json")),
59 |
60 | createIndex("catalog-2012")
61 | .withSettings("com/github/tlrx/elasticsearch/test/settings/catalog.json"),
62 |
63 | createIndex("catalog-2013")
64 | .withSettings(fromClassPath("com/github/tlrx/elasticsearch/test/settings/catalog.json"))
65 | .withMapping("product", fromClassPath("com/github/tlrx/elasticsearch/test/mappings/product.json"))
66 | .withMapping("customer", fromClassPath("com/github/tlrx/elasticsearch/test/mappings/customer.json"))
67 | .withData(fromClassPath("com/github/tlrx/elasticsearch/test/data/products.json")),
68 |
69 | createTemplate("template-1")
70 | .withSource(fromClassPath("com/github/tlrx/elasticsearch/test/templates/template-1.json")),
71 |
72 | createTemplate("template-2")
73 | .withTemplate("test*")
74 | .withSettings(fromClassPath("com/github/tlrx/elasticsearch/test/settings/catalog.json"))
75 | .withMapping("customer", fromClassPath("com/github/tlrx/elasticsearch/test/mappings/customer.json"))
76 | );
77 | }
78 |
79 | @Test
80 | public void testRequests() {
81 |
82 | // Test access to Client
83 | assertNotNull(esSetup.client());
84 |
85 | // test exists()
86 | assertTrue(esSetup.exists("catalog-2009"));
87 | assertTrue(esSetup.exists("catalog-2010"));
88 | assertTrue(esSetup.exists("catalog-2011"));
89 | assertTrue(esSetup.exists("catalog-2012"));
90 | assertTrue(esSetup.exists("catalog-2013"));
91 |
92 | // test exists(index, type, id)
93 | assertTrue(esSetup.exists("catalog-2013", "product", "1"));
94 | assertTrue(esSetup.exists("catalog-2013", "product", "5"));
95 |
96 | // test countAll()
97 | assertEquals(new Long(4), esSetup.countAll());
98 |
99 | // test index()
100 | esSetup.execute(index("catalog-2013", "product", "6").withSource("{ \"field1\" : \"value6\" }"));
101 | esSetup.execute(index("catalog-2013", "product", "7").withSource("{ \"field1\" : \"value7\" }"));
102 | assertEquals(new Long(6), esSetup.countAll());
103 |
104 | // test delete()
105 | esSetup.execute(delete("catalog-2013", "product", "6"));
106 | assertEquals(new Long(5), esSetup.countAll());
107 |
108 | // test count(index)
109 | assertEquals(esSetup.countAll(), esSetup.count("catalog-2013"));
110 |
111 | // test createIndex() and createTemplate()
112 | esSetup.execute(createIndex("toomuch"));
113 | esSetup.execute(createIndex("tests"));
114 |
115 | // test deleteIndex()
116 | esSetup.execute(deleteIndex("catalog-2009"));
117 | assertFalse(esSetup.exists("catalog-2009"));
118 |
119 | // test deleteIndices()
120 | esSetup.execute(deleteIndices("catalog-2010", "catalog-2011"));
121 | assertFalse(esSetup.exists("catalog-2010"));
122 | assertFalse(esSetup.exists("catalog-2011"));
123 |
124 | // test deleteAll()
125 | esSetup.execute(deleteAll());
126 | assertFalse(esSetup.exists("catalog-2012"));
127 | assertFalse(esSetup.exists("catalog-2013"));
128 |
129 | }
130 |
131 | @Test
132 | public void testSecondRequests() {
133 |
134 | // Test second test access to Client
135 | assertNotNull(esSetup.client());
136 |
137 | // test second access to exists()
138 | assertTrue(esSetup.exists("catalog-2009"));
139 | assertTrue(esSetup.exists("catalog-2010"));
140 | assertTrue(esSetup.exists("catalog-2011"));
141 | assertTrue(esSetup.exists("catalog-2012"));
142 | assertTrue(esSetup.exists("catalog-2013"));
143 |
144 | }
145 |
146 | @After
147 | public void tearDown() throws Exception {
148 | esSetup.terminate();
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchAdminClientAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.client.AdminClient;
5 | import org.elasticsearch.node.Node;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 |
9 | import static org.junit.Assert.assertNotNull;
10 | import static org.junit.Assert.assertNotSame;
11 |
12 | /**
13 | * Test class for {@link ElasticsearchAdminClient} annotation.
14 | *
15 | * @author tlrx
16 | */
17 | @RunWith(ElasticsearchRunner.class)
18 | @ElasticsearchNode
19 | public class ElasticsearchAdminClientAnnotationTest {
20 |
21 | @ElasticsearchAdminClient
22 | AdminClient adminClient0;
23 |
24 | @ElasticsearchNode(name = "node1")
25 | Node node1;
26 |
27 | @ElasticsearchAdminClient(nodeName = "node1")
28 | AdminClient adminClient1;
29 |
30 | @Test
31 | public void testElasticsearchAdminClients() {
32 | assertNotNull(adminClient0);
33 |
34 | assertNotNull(node1);
35 | assertNotNull(adminClient1);
36 |
37 | assertNotSame(adminClient0, adminClient1);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchAnalysisAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
5 | import org.elasticsearch.client.AdminClient;
6 | import org.elasticsearch.common.settings.Settings;
7 | import org.elasticsearch.node.Node;
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.assertEquals;
12 |
13 | /**
14 | * Test class for {@link ElasticsearchAnalysis} annotation.
15 | *
16 | * @author tlrx
17 | */
18 | @RunWith(ElasticsearchRunner.class)
19 | public class ElasticsearchAnalysisAnnotationTest {
20 |
21 | @ElasticsearchNode(name = "node0", local = false)
22 | Node node;
23 |
24 | @ElasticsearchAdminClient(nodeName = "node0")
25 | AdminClient adminClient;
26 |
27 | @Test
28 | @ElasticsearchIndexes(indexes = {
29 | @ElasticsearchIndex(indexName = "library", settings = {
30 | @ElasticsearchSetting(name = "number_of_shards", value = "7"),
31 | @ElasticsearchSetting(name = "number_of_replicas", value = "8")},
32 | analysis = @ElasticsearchAnalysis(
33 | filters = {
34 | @ElasticsearchFilter(name = "myLength", typeName = "length",
35 | settings = {
36 | @ElasticsearchSetting(name = "min", value = "0"),
37 | @ElasticsearchSetting(name = "max", value = "5")
38 | }),
39 | @ElasticsearchFilter(name = "myEdgeNGram", typeName = "edgeNGram",
40 | settings = {
41 | @ElasticsearchSetting(name = "min_gram", value = "2"),
42 | @ElasticsearchSetting(name = "max_gram", value = "10"),
43 | @ElasticsearchSetting(name = "side", value = "front")
44 | })
45 | },
46 | analyzers = {
47 | @ElasticsearchAnalyzer(name = "untouched", tokenizer = "keyword", filtersNames = {"lowercase", "asciifolding"}),
48 | @ElasticsearchAnalyzer(name = "basic", tokenizer = "standard", filtersNames = {"lowercase", "myEdgeNGram", "myLength"})
49 | })
50 | ),
51 | @ElasticsearchIndex(indexName = "people")})
52 | public void testElasticsearchSettings() {
53 |
54 | // Check custom settings on index
55 | ClusterStateResponse response = adminClient.cluster().prepareState()
56 | .execute().actionGet();
57 |
58 | Settings indexSettings = response.getState().metaData().index("library").settings();
59 | assertEquals("7", indexSettings.get("index.number_of_shards"));
60 | assertEquals("8", indexSettings.get("index.number_of_replicas"));
61 |
62 | // Check filters
63 | assertEquals("length", indexSettings.get("index.analysis.filter.myLength.type"));
64 | assertEquals("0", indexSettings.get("index.analysis.filter.myLength.min"));
65 | assertEquals("5", indexSettings.get("index.analysis.filter.myLength.max"));
66 |
67 | assertEquals("edgeNGram", indexSettings.get("index.analysis.filter.myEdgeNGram.type"));
68 | assertEquals("2", indexSettings.get("index.analysis.filter.myEdgeNGram.min_gram"));
69 | assertEquals("10", indexSettings.get("index.analysis.filter.myEdgeNGram.max_gram"));
70 | assertEquals("front", indexSettings.get("index.analysis.filter.myEdgeNGram.side"));
71 |
72 | // Check analyzers
73 | assertEquals("keyword", indexSettings.get("index.analysis.analyzer.untouched.tokenizer"));
74 | assertEquals("lowercase", indexSettings.get("index.analysis.analyzer.untouched.filter.0"));
75 | assertEquals("asciifolding", indexSettings.get("index.analysis.analyzer.untouched.filter.1"));
76 |
77 | assertEquals("standard", indexSettings.get("index.analysis.analyzer.basic.tokenizer"));
78 | assertEquals("lowercase", indexSettings.get("index.analysis.analyzer.basic.filter.0"));
79 | assertEquals("myEdgeNGram", indexSettings.get("index.analysis.analyzer.basic.filter.1"));
80 | assertEquals("myLength", indexSettings.get("index.analysis.analyzer.basic.filter.2"));
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchBulkRequestAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.action.count.CountResponse;
5 | import org.elasticsearch.client.Client;
6 | import org.elasticsearch.node.Node;
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.assertEquals;
11 |
12 | /**
13 | * Test class for {@link ElasticsearchBulkRequest} annotation.
14 | *
15 | * @author tlrx
16 | */
17 | @RunWith(ElasticsearchRunner.class)
18 | public class ElasticsearchBulkRequestAnnotationTest {
19 |
20 | @ElasticsearchNode(local = false)
21 | Node node;
22 |
23 | @ElasticsearchClient
24 | Client client;
25 |
26 | @Test
27 | @ElasticsearchIndex(indexName = "documents", forceCreate = true)
28 | @ElasticsearchBulkRequest(dataFile = "com/github/tlrx/elasticsearch/test/annotations/documents/bulk1.json")
29 | public void testElasticsearchBulkRequest1() {
30 | // Count number of documents
31 | CountResponse countResponse = client.prepareCount("documents").setTypes("doc1").execute().actionGet();
32 | assertEquals(6, countResponse.getCount());
33 | }
34 |
35 | @Test
36 | @ElasticsearchIndex(indexName = "documents")
37 | @ElasticsearchBulkRequest(dataFile = "com/github/tlrx/elasticsearch/test/annotations/documents/bulk2.json")
38 | public void testElasticsearchBulkRequest2() {
39 | // Count number of documents
40 | CountResponse countResponse = client.prepareCount("documents").setTypes("doc1").execute().actionGet();
41 | assertEquals(9, countResponse.getCount());
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchClientAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.client.Client;
5 | import org.elasticsearch.node.Node;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 |
9 | import static org.junit.Assert.assertNotNull;
10 | import static org.junit.Assert.assertNotSame;
11 |
12 | /**
13 | * Test class for {@link ElasticsearchClient} annotation.
14 | *
15 | * @author tlrx
16 | */
17 | @RunWith(ElasticsearchRunner.class)
18 | @ElasticsearchNode
19 | public class ElasticsearchClientAnnotationTest {
20 |
21 | @ElasticsearchClient
22 | Client client0;
23 |
24 | @ElasticsearchNode(name = "node1")
25 | Node node1;
26 |
27 | @ElasticsearchClient(nodeName = "node1")
28 | Client client1;
29 |
30 | @Test
31 | public void testElasticsearchClients() {
32 | assertNotNull(client0);
33 |
34 | assertNotNull(node1);
35 | assertNotNull(client1);
36 |
37 | assertNotSame(client0, client1);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchIndexAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.ElasticsearchException;
5 | import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
6 | import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
7 | import org.elasticsearch.client.AdminClient;
8 | import org.elasticsearch.client.Client;
9 | import org.elasticsearch.common.settings.Settings;
10 | import org.elasticsearch.common.xcontent.json.JsonXContent;
11 | import org.elasticsearch.index.query.QueryBuilders;
12 | import org.elasticsearch.node.Node;
13 | import org.junit.FixMethodOrder;
14 | import org.junit.Test;
15 | import org.junit.runner.RunWith;
16 | import org.junit.runners.MethodSorters;
17 |
18 | import java.io.IOException;
19 |
20 | import static org.junit.Assert.*;
21 |
22 | /**
23 | * Test class for {@link ElasticsearchIndex} annotation.
24 | *
25 | * @author tlrx
26 | */
27 | @RunWith(ElasticsearchRunner.class)
28 | @FixMethodOrder(MethodSorters.NAME_ASCENDING)
29 | public class ElasticsearchIndexAnnotationTest {
30 |
31 | @ElasticsearchNode(local = false)
32 | Node node;
33 |
34 | @ElasticsearchClient
35 | Client client;
36 |
37 | @ElasticsearchAdminClient
38 | AdminClient adminClient;
39 |
40 | @Test
41 | @ElasticsearchIndex
42 | public void testElasticsearchIndex() {
43 | // Checks if a default index has been created
44 | IndicesExistsResponse existResponse = adminClient.indices()
45 | .prepareExists(ElasticsearchIndex.DEFAULT_NAME)
46 | .execute().actionGet();
47 |
48 | assertTrue("Index must exist", existResponse.isExists());
49 | }
50 |
51 | @Test
52 | @ElasticsearchIndex(indexName = "people")
53 | public void testElasticsearchIndex2() throws ElasticsearchException, IOException {
54 | // Checks if the index has been created
55 | IndicesExistsResponse existResponse = adminClient.indices()
56 | .prepareExists("people")
57 | .execute().actionGet();
58 |
59 | assertTrue("Index must exist", existResponse.isExists());
60 |
61 | // Index a simple doc
62 | client.prepareIndex("people", "person", "1")
63 | .setSource(JsonXContent.contentBuilder().startObject().field("Name", "John Doe").endObject())
64 | .setRefresh(true)
65 | .execute()
66 | .actionGet();
67 |
68 | // Check if document is indexed
69 | assertTrue("Document #1 must be found", client.prepareGet("people", "person", "1").execute().actionGet().isExists());
70 | }
71 |
72 | @Test
73 | @ElasticsearchIndex(indexName = "people", cleanAfter = true)
74 | public void testElasticsearchIndexCleanAfter1() {
75 | // Checks if the index has been found
76 | IndicesExistsResponse existResponse = adminClient.indices()
77 | .prepareExists("people")
78 | .execute().actionGet();
79 |
80 | assertTrue("Index must exist", existResponse.isExists());
81 |
82 | // Check if document is still here
83 | assertTrue("Document #1 must be found", client.prepareGet("people", "person", "1").execute().actionGet().isExists());
84 | }
85 |
86 | @Test
87 | @ElasticsearchIndex(indexName = "people")
88 | public void testElasticsearchIndexCleanAfter2() throws ElasticsearchException, IOException {
89 | // Checks if the index has been found
90 | IndicesExistsResponse existResponse = adminClient.indices()
91 | .prepareExists("people")
92 | .execute().actionGet();
93 |
94 | assertTrue("Index must exist", existResponse.isExists());
95 |
96 | // Check that document has been cleaned/deleted after previous @Test method execution
97 | assertFalse("Document #1 must be found", client.prepareGet("people", "person", "1").execute().actionGet().isExists());
98 |
99 | // Index a simple doc
100 | client.prepareIndex("people", "person", "1")
101 | .setSource(JsonXContent.contentBuilder().startObject().field("Name", "John Doe").endObject())
102 | .setRefresh(true)
103 | .execute()
104 | .actionGet();
105 | }
106 |
107 | @Test
108 | @ElasticsearchIndex(indexName = "people")
109 | public void testElasticsearchIndexCleanAfter3() {
110 | // Checks if the index has been found
111 | IndicesExistsResponse existResponse = adminClient.indices()
112 | .prepareExists("people")
113 | .execute().actionGet();
114 |
115 | assertTrue("Index must exist", existResponse.isExists());
116 |
117 | // Check if document is still here
118 | assertTrue("Document #1 must be found", client.prepareGet("people", "person", "1").execute().actionGet().isExists());
119 | }
120 |
121 |
122 | @Test
123 | @ElasticsearchIndex(indexName = "people", forceCreate = true)
124 | public void testElasticsearchIndexForceCreate() {
125 | // Checks if the index has been found
126 | IndicesExistsResponse existResponse = adminClient.indices()
127 | .prepareExists("people")
128 | .execute().actionGet();
129 |
130 | assertTrue("Index must exist", existResponse.isExists());
131 |
132 | adminClient.cluster().prepareHealth("people").request().waitForGreenStatus();
133 |
134 | // Check that document has been cleaned/deleted after previous @Test method execution
135 | assertEquals("Document #1 must not exist", 0, client.prepareSearch("people").setQuery(QueryBuilders.idsQuery("person").addIds("1")).execute().actionGet().getHits().totalHits());
136 | }
137 |
138 |
139 | @Test
140 | @ElasticsearchIndex(indexName = "documents", settingsFile = "com/github/tlrx/elasticsearch/test/annotations/documents/settings.json")
141 | public void testElasticsearchIndexSettingsFile() {
142 | // Check custom settings on index
143 | ClusterStateResponse response = adminClient.cluster().prepareState()
144 | .execute().actionGet();
145 |
146 | Settings indexSettings = response.getState().metaData().index("documents").settings();
147 | assertEquals("3", indexSettings.get("index.number_of_shards"));
148 | assertEquals("7", indexSettings.get("index.number_of_replicas"));
149 | assertEquals("true", indexSettings.get("index.analysis.filter.test_word_delimiter.split_on_numerics"));
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchIndexesAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
5 | import org.elasticsearch.client.AdminClient;
6 | import org.elasticsearch.node.Node;
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.assertTrue;
11 |
12 | /**
13 | * Test class for {@link ElasticsearchIndexes} annotation.
14 | *
15 | * @author tlrx
16 | */
17 | @RunWith(ElasticsearchRunner.class)
18 | public class ElasticsearchIndexesAnnotationTest {
19 |
20 | @ElasticsearchNode(local = false)
21 | Node node;
22 |
23 | @ElasticsearchAdminClient
24 | AdminClient adminClient;
25 |
26 | @Test
27 | @ElasticsearchIndexes(indexes = {@ElasticsearchIndex(indexName = "people")})
28 | public void testElasticsearchIndexWithName() {
29 | // Checks if the index has been created
30 | IndicesExistsResponse existResponse = adminClient.indices()
31 | .prepareExists("people")
32 | .execute().actionGet();
33 |
34 | assertTrue("Index must exist", existResponse.isExists());
35 | }
36 |
37 | @Test
38 | @ElasticsearchIndexes(indexes = {
39 | @ElasticsearchIndex(indexName = "people1"),
40 | @ElasticsearchIndex(indexName = "people2")})
41 | public void testElasticsearchIndexAlreadyExist() {
42 | // Checks if the index people1 has been found
43 | IndicesExistsResponse existResponse = adminClient.indices()
44 | .prepareExists("people1")
45 | .execute().actionGet();
46 |
47 | assertTrue("Index people1 must exist", existResponse.isExists());
48 |
49 | // Checks if the index people2 has been found
50 | existResponse = adminClient.indices()
51 | .prepareExists("people2")
52 | .execute().actionGet();
53 |
54 | assertTrue("Index people2 must exist", existResponse.isExists());
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchMappingAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
5 | import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
6 | import org.elasticsearch.client.AdminClient;
7 | import org.elasticsearch.cluster.metadata.IndexMetaData;
8 | import org.elasticsearch.cluster.metadata.MappingMetaData;
9 | import org.elasticsearch.node.Node;
10 | import org.junit.Test;
11 | import org.junit.runner.RunWith;
12 |
13 | import java.io.IOException;
14 | import java.util.Map;
15 |
16 | import static org.junit.Assert.*;
17 |
18 | /**
19 | * Test class for {@link ElasticsearchMapping} and {@link ElasticsearchMappingField} annotations.
20 | *
21 | * @author tlrx
22 | */
23 | @RunWith(ElasticsearchRunner.class)
24 | public class ElasticsearchMappingAnnotationTest {
25 |
26 | @ElasticsearchNode
27 | Node node;
28 |
29 | @ElasticsearchAdminClient
30 | AdminClient adminClient;
31 |
32 | @Test
33 | @SuppressWarnings("unchecked")
34 | @ElasticsearchIndex(indexName = "library",
35 | mappings = {
36 | @ElasticsearchMapping(typeName = "book",
37 | source = false,
38 | compress = false,
39 | ttl = true,
40 | ttlValue = "2d",
41 | timestamp = true,
42 | timestampFormat = "YYYY-MM-dd",
43 | timestampPath = "publication_date",
44 | properties = {
45 | @ElasticsearchMappingField(name = "title", store = Store.Yes, type = Types.String),
46 | @ElasticsearchMappingField(name = "author", store = Store.No, type = Types.String, index = Index.Not_Analyzed),
47 | @ElasticsearchMappingField(name = "description", store = Store.Yes, type = Types.String, index = Index.Analyzed, analyzerName = "standard"),
48 | @ElasticsearchMappingField(name = "role", store = Store.No, type = Types.String, index = Index.Analyzed, indexAnalyzerName = "keyword", searchAnalyzerName = "standard"),
49 | @ElasticsearchMappingField(name = "publication_date", store = Store.No, type = Types.Date, index = Index.Not_Analyzed),
50 | @ElasticsearchMappingField(name = "name", type = Types.String, index = Index.Analyzed, termVector = TermVector.With_Offsets,
51 | fields = {
52 | @ElasticsearchMappingSubField(name = "untouched", type = Types.String, index = Index.Not_Analyzed, termVector = TermVector.With_Positions_Offsets),
53 | @ElasticsearchMappingSubField(name = "stored", type = Types.String, index = Index.No, store = Store.Yes)
54 | }
55 | )
56 | }),
57 | @ElasticsearchMapping(typeName = "rating",
58 | source = true,
59 | compress = true,
60 | compressThreshold = "10kb",
61 | parent = "book",
62 | properties = {
63 | @ElasticsearchMappingField(name = "stars", index = Index.Not_Analyzed, type = Types.Integer)
64 | }
65 | )
66 | })
67 | public void testElasticsearchMapping() {
68 |
69 | // Checks if the index has been created
70 | IndicesExistsResponse existResponse = adminClient.indices()
71 | .prepareExists("library")
72 | .execute().actionGet();
73 |
74 | assertTrue("Index must exist", existResponse.isExists());
75 |
76 | // Checks if mapping has been created
77 | ClusterStateResponse stateResponse = adminClient.cluster()
78 | .prepareState()
79 | .setIndices("library").execute()
80 | .actionGet();
81 |
82 | IndexMetaData indexMetaData = stateResponse.getState().getMetaData().index("library");
83 |
84 | // Test book mapping
85 | MappingMetaData mappingMetaData = indexMetaData.getMappings().get("book");
86 | assertNotNull("Mapping must exists", mappingMetaData);
87 |
88 | try {
89 | Map def = mappingMetaData.sourceAsMap();
90 |
91 | // Check _source
92 | Map source = (Map) def.get("_source");
93 | assertNotNull("_source must exists", source);
94 | assertEquals(Boolean.FALSE, source.get("compress"));
95 | assertEquals(Boolean.FALSE, source.get("enabled"));
96 |
97 | // Check TTL
98 | Map ttl = (Map) def.get("_ttl");
99 | assertNotNull("_ttl must exists", ttl);
100 | assertEquals(Boolean.TRUE, ttl.get("enabled"));
101 | assertEquals(172800000, ttl.get("default"));
102 |
103 | // Check _timestamp
104 | Map timestamp = (Map) def.get("_timestamp");
105 | assertNotNull("_timestamp must exist", timestamp);
106 | assertEquals(Boolean.TRUE, timestamp.get("enabled"));
107 | assertEquals("YYYY-MM-dd", timestamp.get("format"));
108 | assertEquals("publication_date", timestamp.get("path"));
109 |
110 | // Check properties
111 | Map properties = (Map) def.get("properties");
112 | assertNotNull("properties must exists", properties);
113 |
114 | // Check title
115 | Map title = (Map) properties.get("title");
116 | assertEquals("string", title.get("type"));
117 | assertEquals(Boolean.TRUE, title.get("store"));
118 |
119 | // Check author
120 | Map author = (Map) properties.get("author");
121 | assertEquals("not_analyzed", author.get("index"));
122 | assertEquals("string", author.get("type"));
123 | assertNull("Store = No must be null", author.get("store"));
124 |
125 | // Check description
126 | Map description = (Map) properties.get("description");
127 | assertNull("index = analyzed must be null", description.get("index"));
128 | assertEquals("string", description.get("type"));
129 | assertEquals(Boolean.TRUE, description.get("store"));
130 | assertEquals("standard", description.get("analyzer"));
131 |
132 | // Check role
133 | Map role = (Map) properties.get("role");
134 | assertNull("index = analyzed must be null", role.get("index"));
135 | assertEquals("string", role.get("type"));
136 | assertNull("Store = No must be null", role.get("store"));
137 | assertEquals("keyword", role.get("index_analyzer"));
138 | assertEquals("standard", role.get("search_analyzer"));
139 |
140 | // Check name
141 | Map name = (Map) properties.get("name");
142 | assertEquals("string", name.get("type"));
143 | Map fields = (Map) name.get("fields");
144 | assertNotNull("fields must exists", fields);
145 |
146 | // Check name.untouched
147 | Map untouched = (Map) fields.get("untouched");
148 | assertEquals("string", untouched.get("type"));
149 | assertNull("Store = No must be null", untouched.get("store"));
150 | assertEquals("not_analyzed", untouched.get("index"));
151 | assertEquals("with_positions_offsets", untouched.get("term_vector"));
152 |
153 | // Check name.stored
154 | Map stored = (Map) fields.get("stored");
155 | assertEquals("string", stored.get("type"));
156 | assertEquals(Boolean.TRUE, stored.get("store"));
157 | assertEquals("no", stored.get("index"));
158 |
159 | } catch (IOException e) {
160 | fail("Exception when reading mapping metadata");
161 | }
162 |
163 | // Test rating mapping
164 | mappingMetaData = indexMetaData.getMappings().get("rating");
165 | assertNotNull("Mapping must exists", mappingMetaData);
166 |
167 | try {
168 | Map def = mappingMetaData.sourceAsMap();
169 |
170 | // Check _source
171 | Map source = (Map) def.get("_source");
172 | assertNotNull("_source must exists", source);
173 | assertEquals(Boolean.TRUE, source.get("compress"));
174 | assertEquals("10kb", source.get("compress_threshold"));
175 |
176 | // Check _parent
177 | Map parent = (Map) def.get("_parent");
178 | assertNotNull("_parent must exists", parent);
179 | assertEquals("book", parent.get("type"));
180 |
181 | // Check properties
182 | Map properties = (Map) def.get("properties");
183 | assertNotNull("properties must exists", properties);
184 |
185 | // Check stars
186 | Map stars = (Map) properties.get("stars");
187 | assertEquals("integer", stars.get("type"));
188 |
189 | } catch (IOException e) {
190 | fail("Exception when reading mapping metadata");
191 | }
192 | }
193 |
194 | }
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchNodeAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.node.Node;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 |
8 | import static org.junit.Assert.*;
9 |
10 | /**
11 | * Test class for {@link ElasticsearchNode} annotation.
12 | *
13 | * @author tlrx
14 | */
15 | @RunWith(ElasticsearchRunner.class)
16 | public class ElasticsearchNodeAnnotationTest {
17 |
18 | private static final String CLUSTER_NAME = "cluster.name";
19 | private static final String NODE_NAME = "node.name";
20 | private static final String NODE_LOCAL = "node.local";
21 | private static final String NODE_DATA = "node.data";
22 | private static final String INDEX_NUMBER_OF_SHARDS = "index.number_of_shards";
23 | private static final String INDEX_NUMBER_OF_REPLICAS = "index.number_of_replicas";
24 |
25 | @ElasticsearchNode
26 | Node node0;
27 |
28 | @ElasticsearchNode
29 | Node node0bis;
30 |
31 | @ElasticsearchNode(name = "node1", clusterName = "second-cluster-name")
32 | Node node1;
33 |
34 | @ElasticsearchNode(name = "node2", clusterName = "third-cluster-name", local = false)
35 | Node node2;
36 |
37 | @ElasticsearchNode(name = "node3", clusterName = "fourth-cluster-name", local = true, data = false)
38 | Node node3;
39 |
40 | @ElasticsearchNode(name = "node3")
41 | Node node3bis;
42 |
43 | @ElasticsearchNode(name = "node3-1", clusterName = "fourth-cluster-name")
44 | Node node3_1;
45 |
46 | // This node has his own configuration file
47 | @ElasticsearchNode(configFile = "com/github/tlrx/elasticsearch/test/annotations/elasticsearch-node4.yml")
48 | Node node4;
49 |
50 | @Test
51 | public void testElasticsearchNodes() {
52 | assertNotNull(node0);
53 | assertEquals("elasticsearch-test-node", node0.settings().get(NODE_NAME));
54 | assertEquals("elasticsearch-test-cluster", node0.settings().get(CLUSTER_NAME));
55 | assertEquals(ElasticsearchNode.DEFAULT_NODE_NAME, node0.settings().get(NODE_NAME));
56 | assertEquals(ElasticsearchNode.DEFAULT_CLUSTER_NAME, node0.settings().get(CLUSTER_NAME));
57 | assertTrue(node0.settings().getAsBoolean(NODE_LOCAL, null));
58 | assertTrue(node0.settings().getAsBoolean(NODE_DATA, null));
59 | // This node will have default configuration file: /config/elasticsearch.yml
60 | assertEquals("zone1", node0.settings().get("node.zone"));
61 | assertEquals("1", node0.settings().get(INDEX_NUMBER_OF_SHARDS));
62 | assertEquals("0", node0.settings().get(INDEX_NUMBER_OF_REPLICAS));
63 |
64 | assertEquals(node0, node0bis);
65 | assertEquals("elasticsearch-test-node", node0bis.settings().get(NODE_NAME));
66 | assertEquals(node0.settings().get(CLUSTER_NAME), node0bis.settings().get(CLUSTER_NAME));
67 |
68 | assertNotNull(node1);
69 | assertEquals("node1", node1.settings().get(NODE_NAME));
70 | assertEquals("second-cluster-name", node1.settings().get(CLUSTER_NAME));
71 | assertTrue(node1.settings().getAsBoolean(NODE_LOCAL, null));
72 | assertTrue(node1.settings().getAsBoolean(NODE_DATA, null));
73 |
74 | assertNotNull(node2);
75 | assertEquals("node2", node2.settings().get(NODE_NAME));
76 | assertEquals("third-cluster-name", node2.settings().get(CLUSTER_NAME));
77 | assertFalse(node2.settings().getAsBoolean(NODE_LOCAL, null));
78 | assertTrue(node2.settings().getAsBoolean(NODE_DATA, null));
79 |
80 | assertNotNull(node3);
81 | assertEquals("node3", node3.settings().get(NODE_NAME));
82 | assertEquals("fourth-cluster-name", node3.settings().get(CLUSTER_NAME));
83 | assertTrue(node3.settings().getAsBoolean(NODE_LOCAL, null));
84 | assertFalse(node3.settings().getAsBoolean(NODE_DATA, null));
85 |
86 | assertEquals(node3, node3bis);
87 | assertEquals("node3", node3bis.settings().get(NODE_NAME));
88 | assertEquals(node3.settings().get(CLUSTER_NAME), node3bis.settings().get(CLUSTER_NAME));
89 |
90 | assertNotSame(node3, node3_1);
91 | assertEquals(node3.settings().get(CLUSTER_NAME), node3_1.settings().get(CLUSTER_NAME));
92 |
93 | assertNotNull(node4);
94 | assertEquals("node4", node4.settings().get(NODE_NAME));
95 | assertEquals("my-cluster", node4.settings().get(CLUSTER_NAME));
96 | assertFalse(node4.settings().getAsBoolean(NODE_DATA, null));
97 | assertTrue(node4.settings().getAsBoolean(NODE_LOCAL, null));
98 | assertEquals("3", node4.settings().get(INDEX_NUMBER_OF_SHARDS));
99 | assertEquals("1", node4.settings().get(INDEX_NUMBER_OF_REPLICAS));
100 |
101 | // This node also has default configuration file: /config/elasticsearch.yml
102 | assertEquals("zone1", node4.settings().get("node.zone"));
103 |
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchSettingAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
5 | import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
6 | import org.elasticsearch.client.AdminClient;
7 | import org.elasticsearch.common.settings.Settings;
8 | import org.elasticsearch.node.Node;
9 | import org.junit.Test;
10 | import org.junit.runner.RunWith;
11 |
12 | import static org.junit.Assert.assertEquals;
13 |
14 | /**
15 | * Test class for {@link ElasticsearchSetting} annotation.
16 | *
17 | * @author tlrx
18 | */
19 | @RunWith(ElasticsearchRunner.class)
20 | public class ElasticsearchSettingAnnotationTest {
21 |
22 | @ElasticsearchNode(name = "node0", settings = {
23 | @ElasticsearchSetting(name = "http.enabled", value = "false"),
24 | @ElasticsearchSetting(name = "node.zone", value = "zone_one")})
25 | Node node;
26 |
27 | @ElasticsearchAdminClient(nodeName = "node0")
28 | AdminClient adminClient;
29 |
30 | @Test
31 | @ElasticsearchIndexes(indexes = {
32 | @ElasticsearchIndex(indexName = "library",
33 | forceCreate = true,
34 | settings = {
35 | @ElasticsearchSetting(name = "number_of_shards", value = "2"),
36 | @ElasticsearchSetting(name = "number_of_replicas", value = "1")}),
37 | @ElasticsearchIndex(indexName = "people")})
38 | public void testElasticsearchSettings() {
39 |
40 | // Check custom settings on node
41 | NodesInfoResponse infoResponse = adminClient.cluster()
42 | .prepareNodesInfo("node0")
43 | .setSettings(true)
44 | .execute()
45 | .actionGet();
46 |
47 | Settings nodeSettings = infoResponse.getAt(0).getSettings();
48 | assertEquals("false", nodeSettings.get("http.enabled"));
49 | assertEquals("zone_one", nodeSettings.get("node.zone"));
50 |
51 | // Check custom settings on index
52 | ClusterStateResponse response = adminClient.cluster().prepareState()
53 | .execute().actionGet();
54 |
55 | Settings indexSettings = response.getState().metaData().index("library").settings();
56 | assertEquals("2", indexSettings.get("index.number_of_shards"));
57 | assertEquals("1", indexSettings.get("index.number_of_replicas"));
58 |
59 | // Check default settings
60 | indexSettings = response.getState().metaData().index("people").settings();
61 | assertEquals("1", indexSettings.get("index.number_of_shards"));
62 | assertEquals("0", indexSettings.get("index.number_of_replicas"));
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/annotations/ElasticsearchTransportClientAnnotationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.annotations;
2 |
3 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
4 | import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
5 | import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
6 | import org.elasticsearch.client.transport.TransportClient;
7 | import org.elasticsearch.node.Node;
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Test class for {@link ElasticsearchTransportClient} annotation.
15 | *
16 | * @author tlrx
17 | */
18 | @RunWith(ElasticsearchRunner.class)
19 | public class ElasticsearchTransportClientAnnotationTest {
20 |
21 | @ElasticsearchNode(name = "node0", local = false, clusterName = "external", settings = @ElasticsearchSetting(name = "transport.tcp.port", value = "9500"))
22 | Node node0;
23 |
24 | @ElasticsearchTransportClient(clusterName = "external",
25 | hostnames = {"127.0.0.1"},
26 | ports = {9500})
27 | TransportClient client0;
28 |
29 | @Test
30 | @ElasticsearchIndex(indexName = "sites", nodeName = "node0")
31 | public void testTransportClient() {
32 |
33 | assertNotNull(node0);
34 | assertNotNull(client0);
35 |
36 | // Checks if the index has been created
37 | IndicesExistsResponse existResponse = client0.admin().indices()
38 | .prepareExists("sites")
39 | .execute().actionGet();
40 | assertTrue("Index must exist", existResponse.isExists());
41 | }
42 |
43 | @ElasticsearchNode(local = false)
44 | Node node1;
45 |
46 | @ElasticsearchTransportClient
47 | TransportClient client1;
48 |
49 | @Test
50 | @ElasticsearchIndex(indexName = "sites")
51 | public void testLocalTransportClient() {
52 |
53 | assertNotNull(node1);
54 | assertNotNull(client1);
55 | assertNotSame(node0, node1);
56 | assertNotSame(client0, client1);
57 |
58 | NodesInfoResponse nodeInfos = client1.admin().cluster().prepareNodesInfo().execute().actionGet();
59 | assertFalse(client1.connectedNodes().isEmpty());
60 |
61 | // Checks if the index has been created
62 | IndicesExistsResponse existResponse = client1.admin().indices()
63 | .prepareExists("sites")
64 | .execute().actionGet();
65 | assertTrue("Index must exist", existResponse.isExists());
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/request/DeleteTemplatesTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.request;
2 |
3 | import com.github.tlrx.elasticsearch.test.EsSetup;
4 | import com.github.tlrx.elasticsearch.test.EsSetupRuntimeException;
5 | import org.elasticsearch.action.admin.cluster.state.ClusterStateAction;
6 | import org.elasticsearch.action.admin.cluster.state.ClusterStateRequestBuilder;
7 | import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
8 | import org.elasticsearch.cluster.metadata.IndexTemplateMetaData;
9 | import org.junit.Before;
10 | import org.junit.Test;
11 |
12 | import static com.github.tlrx.elasticsearch.test.EsSetup.createTemplate;
13 | import static com.github.tlrx.elasticsearch.test.EsSetup.deleteTemplates;
14 | import static org.junit.Assert.assertFalse;
15 | import static org.junit.Assert.assertTrue;
16 |
17 | /**
18 | * Unit test for the {@link DeleteTemplates} request
19 | */
20 | public class DeleteTemplatesTest {
21 | private static final String TEST_TEMPLATE_NAME = "test-template";
22 | private EsSetup esSetup;
23 | private static final String TEST_TEMPLATE_SOURCE = "{\n" +
24 | "\t\"template\": \""+TEST_TEMPLATE_NAME+"\",\n" +
25 | "\t\"mappings\": {\n" +
26 | "\t\t\"test\": {\n" +
27 | "\t\t\t\"properties\" : {\n" +
28 | "\t\t\t\t\"name\" : {\n" +
29 | "\t\t\t\t\t\"type\" : \"string\"\n" +
30 | "\t\t\t\t}" +
31 | "\t\t\t}\n" +
32 | "\t\t}\n" +
33 | "\t}\n" +
34 | "}";
35 |
36 | @Before
37 | public void setUp() {
38 | esSetup = new EsSetup();
39 | }
40 | public void tearDown() {
41 | esSetup.execute(deleteTemplates());
42 | }
43 | public boolean existsTemplate(String templateName) {
44 | ClusterStateRequestBuilder clusterStateRequestBuilder =
45 | ClusterStateAction.INSTANCE.newRequestBuilder(esSetup.client().admin().cluster())
46 | .all().setMetaData(false);
47 | ClusterStateResponse clusterStateResponse = clusterStateRequestBuilder.execute().actionGet();
48 | IndexTemplateMetaData indexTemplateMetaData = clusterStateResponse.getState().getMetaData()
49 | .getTemplates().get(templateName);
50 | return indexTemplateMetaData != null;
51 | }
52 |
53 | @Test
54 | public void testDeleteTemplates() {
55 | esSetup.execute(createTemplate(TEST_TEMPLATE_NAME).withSource(TEST_TEMPLATE_SOURCE));
56 | esSetup.execute(deleteTemplates(TEST_TEMPLATE_NAME));
57 | assertFalse(existsTemplate(TEST_TEMPLATE_NAME));
58 | }
59 |
60 | @Test
61 | public void testDeleteAllTemplates() {
62 | esSetup.execute(createTemplate(TEST_TEMPLATE_NAME).withSource(TEST_TEMPLATE_SOURCE));
63 | esSetup.execute(deleteTemplates());
64 | assertFalse(existsTemplate(TEST_TEMPLATE_NAME));
65 | }
66 |
67 |
68 | @Test(expected = EsSetupRuntimeException.class)
69 | public void testDeleteTemplatesFailSlow() {
70 | EsSetup esSetup = new EsSetup();
71 | esSetup.execute(createTemplate(TEST_TEMPLATE_NAME).withSource(TEST_TEMPLATE_SOURCE));
72 | esSetup.execute(deleteTemplates("test-fail", TEST_TEMPLATE_NAME));
73 | assertFalse(existsTemplate(TEST_TEMPLATE_NAME));
74 | }
75 |
76 | @Test(expected = EsSetupRuntimeException.class)
77 | public void testDeleteTemplatesFailFast() {
78 | EsSetup esSetup = new EsSetup();
79 | esSetup.execute(createTemplate(TEST_TEMPLATE_NAME).withSource(TEST_TEMPLATE_SOURCE));
80 | esSetup.execute(deleteTemplates("test-fail", TEST_TEMPLATE_NAME).failFast());
81 | assertTrue(existsTemplate(TEST_TEMPLATE_NAME));
82 | }
83 | }
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/rules/ChildTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.rules;
2 |
3 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchClient;
4 | import com.github.tlrx.elasticsearch.test.support.junit.rules.ElasticsearchFieldRule;
5 | import org.elasticsearch.client.Client;
6 | import org.junit.Test;
7 |
8 | import static org.junit.Assert.assertNotNull;
9 |
10 | /**
11 | * Simple child class to check that {@link ElasticsearchFieldRule} manage
12 | * declared and inherited class attributes.
13 | *
14 | * @author tlrx
15 | */
16 | public class ChildTest extends ParentTest {
17 |
18 | @ElasticsearchClient
19 | Client client;
20 |
21 | @Test
22 | public void test() {
23 | assertNotNull(client);
24 | assertNotNull(node);
25 | assertNotNull(transportClient);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/github/tlrx/elasticsearch/test/rules/ParentTest.java:
--------------------------------------------------------------------------------
1 | package com.github.tlrx.elasticsearch.test.rules;
2 |
3 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchNode;
4 | import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchTransportClient;
5 | import com.github.tlrx.elasticsearch.test.support.junit.rules.ElasticsearchFieldRule;
6 | import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
7 | import org.elasticsearch.client.transport.TransportClient;
8 | import org.elasticsearch.node.Node;
9 | import org.junit.runner.RunWith;
10 |
11 | /**
12 | * Simple parent class to check that {@link ElasticsearchFieldRule} manage
13 | * declared and inherited class attributes.
14 | *
15 | * @author tlrx
16 | */
17 | @RunWith(ElasticsearchRunner.class)
18 | public abstract class ParentTest {
19 |
20 | @ElasticsearchNode
21 | Node node;
22 |
23 | @ElasticsearchTransportClient
24 | TransportClient transportClient;
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/samples/search/FilterTest.json:
--------------------------------------------------------------------------------
1 | { "index" : { "_index" : "books", "_type" : "book", "_id" : "1" } }
2 | { "title" : "Les Misérables", "tags" : ["french", "literature", "novel"], "year" : "1862", "author" : {"firstname" : "Victor", "lastname" : "Hugo"} }
3 | { "index" : { "_index" : "books", "_type" : "book", "_id" : "2" } }
4 | { "title" : "Le Dernier Jour d'un condamné", "tags" : ["french", "literature"], "year" : "1829", "author" : {"firstname" : "Victor", "lastname" : "Hugo"} }
5 | { "index" : { "_index" : "books", "_type" : "book", "_id" : "3" } }
6 | { "title" : "Quatrevingt-treize", "tags" : ["french", "literature"], "year" : "1874", "author" : {"firstname" : "Victor", "lastname" : "Hugo"} }
7 | { "index" : { "_index" : "books", "_type" : "book", "_id" : "4" } }
8 | { "title" : "Les Orientales", "tags" : ["french", "poetry"], "year" : "1829", "author" : {"firstname" : "Victor", "lastname" : "Hugo"} }
9 | { "index" : { "_index" : "books", "_type" : "book", "_id" : "5" } }
10 | { "title" : "Les Châtiments", "tags" : ["french", "poetry"], "year" : "1853", "author" : {"firstname" : "Victor", "lastname" : "Hugo"} }
11 | { "index" : { "_index" : "books", "_type" : "book", "_id" : "6" } }
12 | { "title" : "Promenades dans Rome", "tags" : ["french", "literature"], "year" : "1829", "author" : {"firstname" : "Henri", "lastname" : "Beyle"} }
13 | { "index" : { "_index" : "books", "_type" : "book", "_id" : "7" } }
14 | { "title" : "Mont de piété", "tags" : ["french", "poetry"], "year" : "1919", "author" : {"firstname" : "André", "lastname" : "Breton"} }
15 |
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/annotations/documents/bulk1.json:
--------------------------------------------------------------------------------
1 | { "index" : { "_index" : "documents", "_type" : "doc1", "_id" : "1" } }
2 | { "title" : "value1" }
3 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "2" } }
4 | { "title" : "value2" }
5 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "3" } }
6 | { "title" : "value3" }
7 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "4" } }
8 | { "title" : "value4" }
9 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "5" } }
10 | { "title" : "value5" }
11 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "6" } }
12 | { "title" : "value6" }
13 |
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/annotations/documents/bulk2.json:
--------------------------------------------------------------------------------
1 | { "index" : { "_index" : "documents", "_type" : "doc1", "_id" : "7" } }
2 | { "title" : "value7" }
3 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "8" } }
4 | { "title" : "value8" }
5 | { "delete" : { "_index" : "documents", "_type" : "doc1", "_id" : "2" } }
6 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "9" } }
7 | { "title" : "value9" }
8 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "10" } }
9 | { "title" : "value10" }
10 | { "delete" : { "_index" : "documents", "_type" : "doc1", "_id" : "5" } }
11 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "11" } }
12 | { "title" : "value11" }
13 | { "delete" : { "_index" : "documents", "_type" : "doc1", "_id" : "6" } }
14 | { "create" : { "_index" : "documents", "_type" : "doc1", "_id" : "12" } }
15 | { "title" : "value12" }
16 |
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/annotations/documents/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "index": {
3 | "number_of_shards": 3,
4 | "number_of_replicas": 7,
5 | "analysis": {
6 | "filter": {
7 | "test_word_delimiter": {
8 | "type": "word_delimiter",
9 | "catenate_words": "true",
10 | "split_on_numerics": "true",
11 | "preserve_original": "true"
12 | }
13 | },
14 | "analyzer": {
15 | "basic_analyzer": {
16 | "tokenizer": "whitespace",
17 | "filter": [
18 | "test_word_delimiter"
19 | ]
20 | }
21 | }
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/annotations/elasticsearch-node4.yml:
--------------------------------------------------------------------------------
1 | #Node name
2 | node.name: node4
3 |
4 | # Cluster name
5 | cluster.name: my-cluster
6 |
7 | # Index settings
8 | index.number_of_shards: 3
9 | index.number_of_replicas: 1
10 |
11 | node.data: false
12 |
13 | # Simple node property to check file loading
14 | node.zone: zone1
15 |
16 |
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/data/products.json:
--------------------------------------------------------------------------------
1 | { "index" : { "_index" : "catalog-2013", "_type" : "product", "_id" : "1" } }
2 | { "field1" : "value1" }
3 | { "delete" : { "_index" : "catalog-2013", "_type" : "product", "_id" : "2" } }
4 | { "create" : { "_index" : "catalog-2013", "_type" : "product", "_id" : "3" } }
5 | { "field1" : "value3" }
6 | { "index" : { "_index" : "catalog-2013", "_type" : "product", "_id" : "4" } }
7 | { "field1" : "value4" }
8 | { "index" : { "_index" : "catalog-2013", "_type" : "product", "_id" : "5" } }
9 | { "field1" : "value5" }
10 |
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/indices/catalog-2011.json:
--------------------------------------------------------------------------------
1 | {
2 | "settings" : {
3 | "number_of_shards" : 1
4 | },
5 | "mappings" : {
6 | "type1" : {
7 | "_source" : { "enabled" : false },
8 | "properties" : {
9 | "field1" : { "type" : "string", "index" : "not_analyzed" }
10 | }
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/mappings/customer.json:
--------------------------------------------------------------------------------
1 | {
2 | "customer" : {
3 | "properties" : {
4 | "firstname" : {"type" : "string", "store" : "yes"} ,
5 | "lastname" : {"type" : "string", "store" : "yes"}
6 | }
7 | }
8 | }
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/mappings/product.json:
--------------------------------------------------------------------------------
1 | {
2 | "product" : {
3 | "properties" : {
4 | "message" : {"type" : "string", "store" : "yes"}
5 | }
6 | }
7 | }
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/settings/catalog.json:
--------------------------------------------------------------------------------
1 | {
2 | "index": {
3 | "number_of_shards": 4,
4 | "number_of_replicas": 1,
5 | "analysis": {
6 | "filter": {
7 | "test_word_delimiter": {
8 | "type": "word_delimiter",
9 | "catenate_words": "true",
10 | "split_on_numerics": "true",
11 | "preserve_original": "true"
12 | }
13 | },
14 | "analyzer": {
15 | "basic_analyzer": {
16 | "tokenizer": "whitespace",
17 | "filter": [
18 | "test_word_delimiter"
19 | ]
20 | }
21 | }
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/src/test/resources/com/github/tlrx/elasticsearch/test/templates/template-1.json:
--------------------------------------------------------------------------------
1 | {
2 | "template" : "t*",
3 | "settings" : {
4 | "number_of_shards" : 7
5 | },
6 | "mappings" : {
7 | "product" : {
8 | "_source" : { "enabled" : false }
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/src/test/resources/config/elasticsearch.yml:
--------------------------------------------------------------------------------
1 | # Simple node property to check file loading
2 | node.zone: zone1
3 |
--------------------------------------------------------------------------------