diff --git a/src/main/java/org/elasticsearch/alerts/Payload.java b/src/main/java/org/elasticsearch/alerts/Payload.java index 2c2916b497c..a0c4d227f69 100644 --- a/src/main/java/org/elasticsearch/alerts/Payload.java +++ b/src/main/java/org/elasticsearch/alerts/Payload.java @@ -67,19 +67,16 @@ public interface Payload extends ToXContent { } } - static class ActionResponse extends Simple { - - public ActionResponse(org.elasticsearch.action.ActionResponse response) { - super(responseToData(response)); - } - } - static class XContent extends Simple { public XContent(XContentParser parser) { super(mapOrdered(parser)); } + public XContent(ToXContent response) { + super(responseToData(response)); + } + private static Map mapOrdered(XContentParser parser) { try { return parser.mapOrdered(); diff --git a/src/main/java/org/elasticsearch/alerts/input/search/SearchInput.java b/src/main/java/org/elasticsearch/alerts/input/search/SearchInput.java index 21ef858e5e3..e3dd16baece 100644 --- a/src/main/java/org/elasticsearch/alerts/input/search/SearchInput.java +++ b/src/main/java/org/elasticsearch/alerts/input/search/SearchInput.java @@ -83,7 +83,7 @@ public class SearchInput extends Input { } - return new Result(TYPE, new Payload.ActionResponse(response), request); + return new Result(TYPE, new Payload.XContent(response), request); } @Override diff --git a/src/main/java/org/elasticsearch/alerts/support/AlertUtils.java b/src/main/java/org/elasticsearch/alerts/support/AlertUtils.java index 6f0b1d8b55b..65e7fe6df84 100644 --- a/src/main/java/org/elasticsearch/alerts/support/AlertUtils.java +++ b/src/main/java/org/elasticsearch/alerts/support/AlertUtils.java @@ -6,7 +6,6 @@ package org.elasticsearch.alerts.support; import org.elasticsearch.ElasticsearchIllegalArgumentException; -import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.support.IndicesOptions; @@ -37,7 +36,7 @@ public final class AlertUtils { private AlertUtils() { } - public static Map responseToData(ActionResponse response) { + public static Map responseToData(ToXContent response) { try { XContentBuilder builder = jsonBuilder().startObject().value(response).endObject(); return XContentHelper.convertToMap(builder.bytes(), false).v2(); @@ -101,11 +100,15 @@ public final class AlertUtils { break; case "open": expandOpen = true; + expandClosed = false; break; case "closed": + expandOpen = false; expandClosed = true; break; case "none": + expandOpen = false; + expandClosed = false; break; default: throw new ElasticsearchIllegalArgumentException("Unexpected value [" + parser.text() + "]"); diff --git a/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java b/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java index a4cf3166d0b..8ceb0e9ac4d 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java +++ b/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java @@ -64,7 +64,7 @@ public class SearchTransform extends Transform { public Result apply(ExecutionContext ctx, Payload payload) throws IOException { SearchRequest req = createRequest(request, ctx, payload); SearchResponse resp = client.search(req).actionGet(); - return new Result(TYPE, new Payload.ActionResponse(resp)); + return new Result(TYPE, new Payload.XContent(resp)); } @Override diff --git a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionSearchTests.java b/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionSearchTests.java index e04cb5eb6b3..08fa54a5f78 100644 --- a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionSearchTests.java +++ b/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionSearchTests.java @@ -78,7 +78,7 @@ public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests { ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5")); - ExecutionContext ctx = mockExecutionContext("_name", new Payload.ActionResponse(response)); + ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertFalse(condition.execute(ctx).met()); client().prepareIndex("my-index", "my-type").setTimestamp("2005-01-01T00:40").setSource("{}").get(); @@ -88,7 +88,7 @@ public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests { .addAggregation(AggregationBuilders.dateHistogram("rate").field("_timestamp").interval(DateHistogram.Interval.HOUR).order(Histogram.Order.COUNT_DESC)) .get(); - ctx = mockExecutionContext("_name", new Payload.ActionResponse(response)); + ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertThat(condition.execute(ctx).met(), is(true)); } @@ -102,10 +102,10 @@ public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests { InternalSearchResponse internalSearchResponse = new InternalSearchResponse(new InternalSearchHits(new InternalSearchHit[]{hit}, 1l, 1f), null, null, null, false, null); SearchResponse response = new SearchResponse(internalSearchResponse, "", 3, 3, 500l, new ShardSearchFailure[0]); - ExecutionContext ctx = mockExecutionContext("_alert_name", new Payload.ActionResponse(response)); + ExecutionContext ctx = mockExecutionContext("_alert_name", new Payload.XContent(response)); assertThat(condition.execute(ctx).met(), is(true)); hit.score(2f); - when(ctx.payload()).thenReturn(new Payload.ActionResponse(response)); + when(ctx.payload()).thenReturn(new Payload.XContent(response)); assertThat(condition.execute(ctx).met(), is(false)); } diff --git a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java b/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java index 6471ccee649..25a90a6d89a 100644 --- a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java +++ b/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.alerts.condition.script; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.ShardSearchFailure; -import org.elasticsearch.alerts.Alert; import org.elasticsearch.alerts.AlertsSettingsException; import org.elasticsearch.alerts.ExecutionContext; import org.elasticsearch.alerts.Payload; @@ -15,7 +14,6 @@ import org.elasticsearch.alerts.condition.ConditionException; import org.elasticsearch.alerts.support.Script; import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.collect.ImmutableMap; -import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -39,7 +37,6 @@ import java.util.Set; import static org.elasticsearch.alerts.test.AlertsTestUtils.mockExecutionContext; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.mockito.Mockito.*; /** */ @@ -63,7 +60,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("ctx.payload.hits.total > 1")); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); - ExecutionContext ctx = mockExecutionContext("_name", new Payload.ActionResponse(response)); + ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertFalse(condition.execute(ctx).met()); } @@ -73,7 +70,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase { Script script = new Script("ctx.payload.hits.total > threshold", ScriptService.ScriptType.INLINE, ScriptService.DEFAULT_LANG, ImmutableMap.of("threshold", 1)); ScriptCondition condition = new ScriptCondition(logger, scriptService, script); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); - ExecutionContext ctx = mockExecutionContext("_name", new Payload.ActionResponse(response)); + ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertFalse(condition.execute(ctx).met()); } @@ -87,7 +84,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase { ScriptCondition condition = conditionParser.parse(parser); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); - ExecutionContext ctx = mockExecutionContext("_name", new Payload.ActionResponse(response)); + ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertFalse(condition.execute(ctx).met()); @@ -97,7 +94,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase { parser.nextToken(); condition = conditionParser.parse(parser); - ctx = mockExecutionContext("_name", new Payload.ActionResponse(response)); + ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertTrue(condition.execute(ctx).met()); } diff --git a/src/test/java/org/elasticsearch/alerts/support/AlertUtilsTests.java b/src/test/java/org/elasticsearch/alerts/support/AlertUtilsTests.java index 3c8ff7e03b3..1b5349a7668 100644 --- a/src/test/java/org/elasticsearch/alerts/support/AlertUtilsTests.java +++ b/src/test/java/org/elasticsearch/alerts/support/AlertUtilsTests.java @@ -5,24 +5,35 @@ */ package org.elasticsearch.alerts.support; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchType; +import org.elasticsearch.action.support.IndicesOptions; +import org.elasticsearch.alerts.input.search.SearchInput; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.xcontent.*; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.script.ScriptService; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.test.ElasticsearchTestCase; import org.junit.Test; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; import java.util.Map; import static org.elasticsearch.alerts.support.AlertUtils.flattenModel; import static org.elasticsearch.alerts.support.AlertsDateUtils.formatDate; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; +import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.hamcrest.Matchers.*; /** * */ -public class AlertUtilsTests { +public class AlertUtilsTests extends ElasticsearchTestCase { @Test public void testFlattenModel() throws Exception { @@ -46,4 +57,70 @@ public class AlertUtilsTests { assertThat(result, hasEntry("c.1", "1000")); assertThat(result, hasEntry("d", formatDate(now))); } + + @Test + public void testResponseToData() throws Exception { + final Map expected = new HashMap<>(); + expected.put("key1", "val"); + expected.put("key2", 1); + expected.put("key3", 1.4); + expected.put("key4", Arrays.asList("a", "b", "c")); + Map otherMap = new HashMap<>(); + otherMap.putAll(expected); + expected.put("key5", otherMap); + ToXContent content = new ToXContent() { + @Override + public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { + for (Map.Entry entry : expected.entrySet()) { + builder.field(entry.getKey()); + builder.value(entry.getValue()); + } + return builder; + } + }; + Map result = AlertUtils.responseToData(content); + assertThat(result, equalTo(expected)); + } + + @Test + public void testSerializeSearchRequest() throws Exception { + String[] randomIndices = generateRandomStringArray(5, 5); + SearchRequest expectedRequest = new SearchRequest(randomIndices); + expectedRequest.indicesOptions(IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), AlertUtils.DEFAULT_INDICES_OPTIONS)); + expectedRequest.searchType(randomFrom(SearchType.values())); + + SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()).size(11); + XContentBuilder searchSourceJsonBuilder = jsonBuilder(); + searchSourceBuilder.toXContent(searchSourceJsonBuilder, ToXContent.EMPTY_PARAMS); + String expectedSource = searchSourceJsonBuilder.string(); + expectedRequest.source(expectedSource); + + if (randomBoolean()) { + expectedRequest.templateName(randomAsciiOfLengthBetween(1, 5)); + expectedRequest.templateType(randomFrom(ScriptService.ScriptType.values())); + if (randomBoolean()) { + Map params = new HashMap<>(); + int maxParams = randomIntBetween(1, 10); + for (int i = 0; i < maxParams; i++) { + params.put(randomAsciiOfLengthBetween(1, 5), randomAsciiOfLengthBetween(1, 5)); + } + expectedRequest.templateParams(params); + } + } + + XContentBuilder builder = jsonBuilder(); + builder = AlertUtils.writeSearchRequest(expectedRequest, builder, ToXContent.EMPTY_PARAMS); + XContentParser parser = XContentHelper.createParser(builder.bytes()); + assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); + SearchRequest result = AlertUtils.readSearchRequest(parser, SearchInput.DEFAULT_SEARCH_TYPE); + + assertThat(result.indices(), arrayContainingInAnyOrder(expectedRequest.indices())); + assertThat(result.indicesOptions(), equalTo(expectedRequest.indicesOptions())); + assertThat(result.searchType(), equalTo(expectedRequest.searchType())); + assertThat(result.source().toUtf8(), equalTo(expectedSource)); + assertThat(result.templateName(), equalTo(expectedRequest.templateName())); + assertThat(result.templateType(), equalTo(expectedRequest.templateType())); + assertThat(result.templateParams(), equalTo(expectedRequest.templateParams())); + } + } diff --git a/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java b/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java index 9ef7b32f069..1f671ee88b5 100644 --- a/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java +++ b/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java @@ -60,7 +60,7 @@ public class SearchTransformTests extends AbstractAlertsSingleNodeTests { assertThat(result.type(), is(SearchTransform.TYPE)); SearchResponse response = client().search(request).get(); - Payload expectedPayload = new Payload.ActionResponse(response); + Payload expectedPayload = new Payload.XContent(response); // we need to remove the "took" field from teh response as this is the only field // that most likely be different between the two... we don't really care about this @@ -121,7 +121,7 @@ public class SearchTransformTests extends AbstractAlertsSingleNodeTests { SearchResponse response = client().prepareSearch("idx").setQuery( filteredQuery(matchAllQuery(), termFilter("value", "val_3"))) .get(); - Payload expectedPayload = new Payload.ActionResponse(response); + Payload expectedPayload = new Payload.XContent(response); // we need to remove the "took" field from teh response as this is the only field // that most likely be different between the two... we don't really care about this