Skip to content

Commit

Permalink
Check github actions (#2)
Browse files Browse the repository at this point in the history
* Add elasticsearch-rule module

Co-authored-by: safarnejad <safarnejad@inside.sahab.ir>
  • Loading branch information
safarnejad and safarnejad authored Apr 14, 2020
1 parent 22d6a46 commit 1763ca6
Show file tree
Hide file tree
Showing 6 changed files with 334 additions and 7 deletions.
17 changes: 11 additions & 6 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@
# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
Expand All @@ -21,3 +15,14 @@

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

#Intellij IDEA
.idea/
*.iml

#VSCode project files
.vscode
**/.factorypath

# Maven target directory
target/
47 changes: 46 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,47 @@
# elasticsearch-rule
# Elasticsearch Rule
A JUnit rule for starting an elasticsearch server on the local machine.

## Sample Usage

```java
private static final String ELASTICSEARCH_CLUSTER_NAME = "elasticsearch";

@ClassRule
public static final ElasticsearchRule elasticsearchRule = new ElasticsearchRule(ELASTICSEARCH_CLUSTER_NAME);

private static TransportClient transportClient;

@BeforeClass
public static void setUpClass() {
transportClient = elasticsearchRule.getTransportClient();
}

@Test
public void testClient() {
String indexName = "twitter";
CreateIndexResponse createIndexResponse = transportClient.admin().indices().prepareCreate(indexName).get();
Assert.assertTrue(createIndexResponse.isAcknowledged());
}
```
It is also possible to get the network address of the Elasticsearch server and construct the TransportClient:
```java
@BeforeClass
public static void setUpClass() {
String address = elasticsearchRule.getAddress();
String elasticsearchHost = address.split(":")[0];
int elasticsearchPort = Integer.parseInt(address.split(":")[1]);
InetAddress elasticsearchInetAddress;
try {
elasticsearchInetAddress = InetAddress.getByName(elasticsearchHost);
} catch (UnknownHostException e) {
throw new AssertionError("Cannot get the elasticsearch server address " + elasticsearchHost + ".", e);
}
Settings settings = Settings.builder().put("cluster.name", ELASTICSEARCH_CLUSTER_NAME).build();
transportClient = new PreBuiltTransportClient(settings);
transportClient.addTransportAddress(new TransportAddress(elasticsearchInetAddress, elasticsearchPort));
}
```

## Add it to your project
You can refer to this library by either of java build systems (Maven, Gradle, SBT or Leiningen) using snippets from this jitpack link:
[![](https://jitpack.io/v/sahabpardaz/elasticsearch-rule.svg)](https://jitpack.io/#sahabpardaz/elasticsearch-rule)
90 changes: 90 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>ir.sahab</groupId>
<artifactId>elasticsearch-rule</artifactId>
<version>1.0.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<elasticsearch.version>6.2.4</elasticsearch.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch-cli</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<goal>compile</goal>
<showWarnings>true</showWarnings>
<failOnWarning>true</failOnWarning>
<compilerArgs>
<arg>-Xlint:all</arg>
<arg>-proc:none</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
94 changes: 94 additions & 0 deletions src/main/java/ir/sahab/elasticsearchrule/ElasticsearchRule.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package ir.sahab.elasticsearchrule;

import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.reindex.ReindexPlugin;
import org.elasticsearch.node.InternalSettingsPreparer;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeValidationException;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.transport.Netty4Plugin;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.rules.ExternalResource;

/**
* A JUnit rule for starting an elasticsearch server on the local machine.
*/
public class ElasticsearchRule extends ExternalResource {

private TransportClient transportClient;
private TransportAddress transportAddress;
private String clusterName;
private Node server;

public ElasticsearchRule(String clusterName) {
this.clusterName = clusterName;
}

@Override
protected void before() throws IOException, NodeValidationException, ExecutionException, InterruptedException {
// Set up a setting for Elasticsearch server node.
Settings.Builder builder = Settings.builder();
builder.put(NetworkModule.TRANSPORT_TYPE_KEY, Netty4Plugin.NETTY_TRANSPORT_NAME);
builder.put("node.id.seed", 0L);
builder.put("node.name", "node" + new Random().nextInt(10000));
builder.put(Environment.PATH_DATA_SETTING.getKey(), Files.createTempDirectory("elastic.data"));
builder.put(Environment.PATH_HOME_SETTING.getKey(), Files.createTempDirectory("elastic.home"));
builder.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), clusterName);
builder.put("discovery.type", "single-node");
Settings settings = builder.build();

// Create the Elasticsearch server node and running it.
// Netty4Plugin is necessary for making a TransportClient.
// ReindexPlugin is necessary for making "delete by query" available.
server = new TestNode(settings, Arrays.asList(Netty4Plugin.class, ReindexPlugin.class));
server.start();
server.client().admin().cluster().prepareHealth().setWaitForYellowStatus().execute().get();

// Create a transport client ready to be used in tests.
transportAddress = server.injector().getInstance(TransportService.class).boundAddress().publishAddress();
transportClient = new PreBuiltTransportClient(server.settings());
transportClient.addTransportAddress(transportAddress);
}

@Override
protected void after() {
transportClient.close();
try {
server.close();
} catch (IOException e) {
throw new AssertionError("Cannot close the server.");
}
}

/**
* A wrapper class for class org.elasticsearch.node.Node to make its constructor public.
*/
public static class TestNode extends Node {
public TestNode(Settings preparedSettings, Collection<Class<? extends Plugin>> classpathPlugins) {
super(InternalSettingsPreparer.prepareEnvironment(preparedSettings, Terminal.DEFAULT,
Collections.emptyMap(), null), classpathPlugins);
}
}

public TransportClient getTransportClient() {
return transportClient;
}

public String getAddress() {
return transportAddress.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package ir.sahab.elasticsearchrule;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

public class ElasticsearchRuleTest {

private static final String ELASTICSEARCH_CLUSTER_NAME = "elasticsearch";

@ClassRule
public static final ElasticsearchRule elasticsearchRule = new ElasticsearchRule(ELASTICSEARCH_CLUSTER_NAME);

private static TransportClient transportClient;

@BeforeClass
public static void setUpClass() {
transportClient = elasticsearchRule.getTransportClient();
}

@Test
public void testClient() {
String indexName = "twitter";
CreateIndexResponse createIndexResponse = transportClient.admin().indices().prepareCreate(indexName).get();
Assert.assertTrue(createIndexResponse.isAcknowledged());
transportClient.admin().cluster().prepareHealth().setWaitForYellowStatus().get();
String json = "{"
+ " \"user\":\"kimchy\","
+ " \"postDate\":\"2013-01-30\","
+ " \"message\":\"trying out Elasticsearch\""
+ "}";
IndexResponse response = transportClient.prepareIndex("twitter", "tweet")
.setSource(json, XContentType.JSON)
.get();
Assert.assertEquals(RestStatus.CREATED, response.status());
transportClient.admin().indices().prepareRefresh(indexName).get();

SearchResponse searchResponse = transportClient.prepareSearch(indexName)
.setQuery(QueryBuilders.matchQuery("user", "kimchy"))
.get();
Assert.assertEquals(1, searchResponse.getHits().getHits().length);
String postDate = (String) searchResponse.getHits().getAt(0).getSourceAsMap().get("message");
Assert.assertEquals("trying out Elasticsearch", postDate);
}

@Test
public void testAddress() {
String address = elasticsearchRule.getAddress();
String elasticsearchHost = address.split(":")[0];
int elasticsearchPort = Integer.parseInt(address.split(":")[1]);
InetAddress elasticsearchInetAddress;
try {
elasticsearchInetAddress = InetAddress.getByName(elasticsearchHost);
} catch (UnknownHostException e) {
throw new AssertionError("Cannot get the elasticsearch server address " + elasticsearchHost + ".", e);
}
Settings settings = Settings.builder().put("cluster.name", ELASTICSEARCH_CLUSTER_NAME).build();
TransportClient internalTransportClient = new PreBuiltTransportClient(settings);
internalTransportClient.addTransportAddress(new TransportAddress(elasticsearchInetAddress, elasticsearchPort));
String indexName = "twitter2";
CreateIndexResponse createIndexResponse = internalTransportClient.admin().indices().prepareCreate(indexName).get();
Assert.assertTrue(createIndexResponse.isAcknowledged());
internalTransportClient.close();
}
}
14 changes: 14 additions & 0 deletions src/test/resources/log4j2.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level ELASTICSEARCH_RULE [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug" additivity="false">
<AppenderRef ref="console" />
</Root>
</Loggers>
</Configuration>

0 comments on commit 1763ca6

Please sign in to comment.