All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lordofthejars.nosqlunit.elasticsearch.ElasticsearchOperation Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
package com.lordofthejars.nosqlunit.elasticsearch;

import java.io.InputStream;

import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.deletebyquery.DeleteByQueryRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;

import com.lordofthejars.nosqlunit.core.AbstractCustomizableDatabaseOperation;
import com.lordofthejars.nosqlunit.core.NoSqlAssertionError;

public class ElasticsearchOperation extends
		AbstractCustomizableDatabaseOperation {

	private Client client;

	public ElasticsearchOperation(Client client) {
		this.client = client;
		setInsertionStrategy(new DefaultElasticsearchInsertionStrategy());
		setComparisonStrategy(new DefaultElasticsearchComparisonStrategy());
	}

	@Override
	public void insert(InputStream dataScript) {
		insertData(dataScript);
	}

	private void insertData(InputStream dataScript) {
		try {
			executeInsertion(new ElasticsearchConnectionCallback() {

				@Override
				public Client nodeClient() {
					return client;
				}
			}, dataScript);
		} catch (Throwable e) {
			throw new IllegalArgumentException(e);
		}
	}

	@Override
	public void deleteAll() {
		clearDocuments();
	}

	private void clearDocuments() {

		if (isAnyIndexPresent()) {

			DeleteByQueryRequestBuilder deleteByQueryRequestBuilder = new DeleteByQueryRequestBuilder(client);
			deleteByQueryRequestBuilder.setQuery(QueryBuilders.matchAllQuery());
			deleteByQueryRequestBuilder.execute().actionGet();

			refreshNode();
		}

	}

	private boolean isAnyIndexPresent() {
		CountResponse numberOfElements = client.prepareCount().execute().actionGet();
		return numberOfElements.getCount() > 0;
	}

	private void refreshNode() {
		client.admin().indices().prepareRefresh().execute().actionGet();
	}

	@Override
	public boolean databaseIs(InputStream expectedData) {
		try {
			return executeComparison(new ElasticsearchConnectionCallback() {

				@Override
				public Client nodeClient() {
					return client;
				}
			}, expectedData);
		} catch (NoSqlAssertionError e) {
			throw e;
		} catch (Throwable e) {
			throw new IllegalStateException(e);
		}
	}

	@Override
	public Client connectionManager() {
		return client;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy