[PURIFY] remove all trace of x-pack watcher (#21)

This commit removes all trace of Elastic licensed watcher

Signed-off-by: Peter Nied <petern@amazon.com>
This commit is contained in:
Nick Knize 2021-01-30 00:43:19 -06:00 committed by Peter Nied
parent 4aee8e56db
commit 70a07216bb
57 changed files with 7 additions and 5859 deletions

View File

@ -55,6 +55,5 @@ public class RestTestFromSnippetsTaskTests extends GradleUnitTestCase {
public void testIsDocWriteRequest() { public void testIsDocWriteRequest() {
assertTrue((boolean) RestTestsFromSnippetsTask.shouldAddShardFailureCheck("doc-index/_search")); assertTrue((boolean) RestTestsFromSnippetsTask.shouldAddShardFailureCheck("doc-index/_search"));
assertFalse((boolean) RestTestsFromSnippetsTask.shouldAddShardFailureCheck("_cat")); assertFalse((boolean) RestTestsFromSnippetsTask.shouldAddShardFailureCheck("_cat"));
assertFalse((boolean) RestTestsFromSnippetsTask.shouldAddShardFailureCheck("_ml/datafeeds/datafeed-id/_preview"));
} }
} }

View File

@ -260,7 +260,6 @@ public class RestHighLevelClient implements Closeable {
private final IngestClient ingestClient = new IngestClient(this); private final IngestClient ingestClient = new IngestClient(this);
private final SnapshotClient snapshotClient = new SnapshotClient(this); private final SnapshotClient snapshotClient = new SnapshotClient(this);
private final TasksClient tasksClient = new TasksClient(this); private final TasksClient tasksClient = new TasksClient(this);
private final WatcherClient watcherClient = new WatcherClient(this);
private final TransformClient transformClient = new TransformClient(this); private final TransformClient transformClient = new TransformClient(this);
/** /**
@ -352,16 +351,6 @@ public class RestHighLevelClient implements Closeable {
return tasksClient; return tasksClient;
} }
/**
* Provides methods for accessing the Elastic Licensed Watcher APIs that
* are shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api.html">
* Watcher APIs on elastic.co</a> for more information.
*/
public WatcherClient watcher() { return watcherClient; }
/** /**
* Provides methods for accessing the Elastic Licensed Data Frame APIs that * Provides methods for accessing the Elastic Licensed Data Frame APIs that
* are shipped with the Elastic Stack distribution of Elasticsearch. All of * are shipped with the Elastic Stack distribution of Elasticsearch. All of

View File

@ -1,341 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.watcher.DeactivateWatchRequest;
import org.elasticsearch.client.watcher.DeactivateWatchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.client.watcher.ActivateWatchResponse;
import org.elasticsearch.client.watcher.AckWatchRequest;
import org.elasticsearch.client.watcher.AckWatchResponse;
import org.elasticsearch.client.watcher.ExecuteWatchRequest;
import org.elasticsearch.client.watcher.ExecuteWatchResponse;
import org.elasticsearch.client.watcher.GetWatchRequest;
import org.elasticsearch.client.watcher.GetWatchResponse;
import org.elasticsearch.client.watcher.StartWatchServiceRequest;
import org.elasticsearch.client.watcher.StopWatchServiceRequest;
import org.elasticsearch.client.watcher.DeleteWatchRequest;
import org.elasticsearch.client.watcher.DeleteWatchResponse;
import org.elasticsearch.client.watcher.PutWatchRequest;
import org.elasticsearch.client.watcher.PutWatchResponse;
import org.elasticsearch.client.watcher.WatcherStatsRequest;
import org.elasticsearch.client.watcher.WatcherStatsResponse;
import java.io.IOException;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
public final class WatcherClient {
private final RestHighLevelClient restHighLevelClient;
WatcherClient(RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/**
* Start the watch service
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-start.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public AcknowledgedResponse startWatchService(StartWatchServiceRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(
request, WatcherRequestConverters::startWatchService, options, AcknowledgedResponse::fromXContent, emptySet());
}
/**
* Asynchronously start the watch service
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-start.html">
* the docs</a> for more.
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return cancellable that may be used to cancel the request
*/
public Cancellable startWatchServiceAsync(StartWatchServiceRequest request, RequestOptions options,
ActionListener<AcknowledgedResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(
request, WatcherRequestConverters::startWatchService, options, AcknowledgedResponse::fromXContent, listener, emptySet());
}
/**
* Stop the watch service
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-start.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public AcknowledgedResponse stopWatchService(StopWatchServiceRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(
request, WatcherRequestConverters::stopWatchService, options, AcknowledgedResponse::fromXContent, emptySet());
}
/**
* Asynchronously stop the watch service
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-start.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return cancellable that may be used to cancel the request
*/
public Cancellable stopWatchServiceAsync(StopWatchServiceRequest request, RequestOptions options,
ActionListener<AcknowledgedResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(
request, WatcherRequestConverters::stopWatchService, options, AcknowledgedResponse::fromXContent, listener, emptySet());
}
/**
* Put a watch into the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-put-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public PutWatchResponse putWatch(PutWatchRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, WatcherRequestConverters::putWatch, options,
PutWatchResponse::fromXContent, emptySet());
}
/**
* Asynchronously put a watch into the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-put-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable putWatchAsync(PutWatchRequest request, RequestOptions options,
ActionListener<PutWatchResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::putWatch, options,
PutWatchResponse::fromXContent, listener, emptySet());
}
/**
* Gets a watch from the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-get-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public GetWatchResponse getWatch(GetWatchRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, WatcherRequestConverters::getWatch, options,
GetWatchResponse::fromXContent, emptySet());
}
/**
* Asynchronously gets a watch into the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-get-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable getWatchAsync(GetWatchRequest request, RequestOptions options,
ActionListener<GetWatchResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::getWatch, options,
GetWatchResponse::fromXContent, listener, emptySet());
}
/**
* Deactivate an existing watch
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-deactivate-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public DeactivateWatchResponse deactivateWatch(DeactivateWatchRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, WatcherRequestConverters::deactivateWatch, options,
DeactivateWatchResponse::fromXContent, emptySet());
}
/**
* Asynchronously deactivate an existing watch
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-deactivate-watch.html">
* the docs</a> for more.
*
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable deactivateWatchAsync(DeactivateWatchRequest request, RequestOptions options,
ActionListener<DeactivateWatchResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::deactivateWatch, options,
DeactivateWatchResponse::fromXContent, listener, emptySet());
}
/**
* Deletes a watch from the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-delete-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public DeleteWatchResponse deleteWatch(DeleteWatchRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, WatcherRequestConverters::deleteWatch, options,
DeleteWatchResponse::fromXContent, singleton(404));
}
/**
* Asynchronously deletes a watch from the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-delete-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable deleteWatchAsync(DeleteWatchRequest request, RequestOptions options, ActionListener<DeleteWatchResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::deleteWatch, options,
DeleteWatchResponse::fromXContent, listener, singleton(404));
}
/**
* Acknowledges a watch.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-ack-watch.html">
* the docs</a> for more information.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException if there is a problem sending the request or parsing back the response
*/
public AckWatchResponse ackWatch(AckWatchRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, WatcherRequestConverters::ackWatch, options,
AckWatchResponse::fromXContent, emptySet());
}
/**
* Asynchronously acknowledges a watch.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-ack-watch.html">
* the docs</a> for more information.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon completion of the request
* @return cancellable that may be used to cancel the request
*/
public Cancellable ackWatchAsync(AckWatchRequest request, RequestOptions options, ActionListener<AckWatchResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::ackWatch, options,
AckWatchResponse::fromXContent, listener, emptySet());
}
/**
* Activate a watch from the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-activate-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public ActivateWatchResponse activateWatch(ActivateWatchRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, WatcherRequestConverters::activateWatch, options,
ActivateWatchResponse::fromXContent, singleton(404));
}
/**
* Asynchronously activates a watch from the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-activate-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable activateWatchAsync(ActivateWatchRequest request, RequestOptions options,
ActionListener<ActivateWatchResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::activateWatch, options,
ActivateWatchResponse::fromXContent, listener, singleton(404));
}
/**
* Execute a watch on the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException if there is a problem sending the request or parsing the response
*/
public ExecuteWatchResponse executeWatch(ExecuteWatchRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, WatcherRequestConverters::executeWatch, options,
ExecuteWatchResponse::fromXContent, emptySet());
}
/**
* Asynchronously execute a watch on the cluster
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notifed upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable executeWatchAsync(ExecuteWatchRequest request, RequestOptions options,
ActionListener<ExecuteWatchResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::executeWatch, options,
ExecuteWatchResponse::fromXContent, listener, emptySet());
}
/**
* Get the watcher stats
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-stats.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public WatcherStatsResponse watcherStats(WatcherStatsRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, WatcherRequestConverters::watcherStats, options,
WatcherStatsResponse::fromXContent, emptySet());
}
/**
* Asynchronously get the watcher stats
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-stats.html">
* the docs</a> for more.
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable watcherStatsAsync(WatcherStatsRequest request, RequestOptions options,
ActionListener<WatcherStatsResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::watcherStats, options,
WatcherStatsResponse::fromXContent, listener, emptySet());
}
}

View File

@ -1,179 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NByteArrayEntity;
import org.elasticsearch.client.watcher.AckWatchRequest;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.client.watcher.DeactivateWatchRequest;
import org.elasticsearch.client.watcher.DeleteWatchRequest;
import org.elasticsearch.client.watcher.ExecuteWatchRequest;
import org.elasticsearch.client.watcher.GetWatchRequest;
import org.elasticsearch.client.watcher.PutWatchRequest;
import org.elasticsearch.client.watcher.StartWatchServiceRequest;
import org.elasticsearch.client.watcher.StopWatchServiceRequest;
import org.elasticsearch.client.watcher.WatcherStatsRequest;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
final class WatcherRequestConverters {
private WatcherRequestConverters() {}
static Request startWatchService(StartWatchServiceRequest startWatchServiceRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher")
.addPathPartAsIs("_start")
.build();
return new Request(HttpPost.METHOD_NAME, endpoint);
}
static Request stopWatchService(StopWatchServiceRequest stopWatchServiceRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher")
.addPathPartAsIs("_stop")
.build();
return new Request(HttpPost.METHOD_NAME, endpoint);
}
static Request putWatch(PutWatchRequest putWatchRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher", "watch")
.addPathPart(putWatchRequest.getId())
.build();
Request request = new Request(HttpPut.METHOD_NAME, endpoint);
RequestConverters.Params params = new RequestConverters.Params()
.withIfSeqNo(putWatchRequest.ifSeqNo())
.withIfPrimaryTerm(putWatchRequest.ifPrimaryTerm());
if (putWatchRequest.isActive() == false) {
params.putParam("active", "false");
}
request.addParameters(params.asMap());
ContentType contentType = RequestConverters.createContentType(putWatchRequest.xContentType());
BytesReference source = putWatchRequest.getSource();
request.setEntity(new NByteArrayEntity(source.toBytesRef().bytes, 0, source.length(), contentType));
return request;
}
static Request getWatch(GetWatchRequest getWatchRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher", "watch")
.addPathPart(getWatchRequest.getId())
.build();
return new Request(HttpGet.METHOD_NAME, endpoint);
}
static Request deactivateWatch(DeactivateWatchRequest deactivateWatchRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher")
.addPathPartAsIs("watch")
.addPathPart(deactivateWatchRequest.getWatchId())
.addPathPartAsIs("_deactivate")
.build();
return new Request(HttpPut.METHOD_NAME, endpoint);
}
static Request deleteWatch(DeleteWatchRequest deleteWatchRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher", "watch")
.addPathPart(deleteWatchRequest.getId())
.build();
Request request = new Request(HttpDelete.METHOD_NAME, endpoint);
return request;
}
static Request executeWatch(ExecuteWatchRequest executeWatchRequest) throws IOException {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher", "watch")
.addPathPart(executeWatchRequest.getId()) // will ignore if ID is null
.addPathPartAsIs("_execute").build();
Request request = new Request(HttpPost.METHOD_NAME, endpoint);
RequestConverters.Params params = new RequestConverters.Params();
if (executeWatchRequest.isDebug()) {
params.putParam("debug", "true");
}
if (executeWatchRequest.ignoreCondition()) {
params.putParam("ignore_condition", "true");
}
if (executeWatchRequest.recordExecution()) {
params.putParam("record_execution", "true");
}
request.addParameters(params.asMap());
request.setEntity(RequestConverters.createEntity(executeWatchRequest, XContentType.JSON));
return request;
}
public static Request ackWatch(AckWatchRequest ackWatchRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher", "watch")
.addPathPart(ackWatchRequest.getWatchId())
.addPathPartAsIs("_ack")
.addCommaSeparatedPathParts(ackWatchRequest.getActionIds())
.build();
Request request = new Request(HttpPut.METHOD_NAME, endpoint);
return request;
}
static Request activateWatch(ActivateWatchRequest activateWatchRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_watcher", "watch")
.addPathPart(activateWatchRequest.getWatchId())
.addPathPartAsIs("_activate")
.build();
Request request = new Request(HttpPut.METHOD_NAME, endpoint);
return request;
}
static Request watcherStats(WatcherStatsRequest watcherStatsRequest) {
RequestConverters.EndpointBuilder builder = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher", "stats");
String endpoint = builder.build();
Request request = new Request(HttpGet.METHOD_NAME, endpoint);
RequestConverters.Params parameters = new RequestConverters.Params();
StringBuilder metric = new StringBuilder();
if (watcherStatsRequest.includeCurrentWatches()) {
metric.append("current_watches");
}
if (watcherStatsRequest.includeQueuedWatches()) {
if (metric.length() > 0) {
metric.append(",");
}
metric.append("queued_watches");
}
if (metric.length() > 0) {
parameters.putParam("metric", metric.toString());
}
request.addParameters(parameters.asMap());
return request;
}
}

View File

@ -1,95 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.client.ValidationException;
import java.util.Locale;
/**
* A request to explicitly acknowledge a watch.
*/
public class AckWatchRequest implements Validatable {
private final String watchId;
private final String[] actionIds;
public AckWatchRequest(String watchId, String... actionIds) {
validateIds(watchId, actionIds);
this.watchId = watchId;
this.actionIds = actionIds;
}
private void validateIds(String watchId, String... actionIds) {
ValidationException exception = new ValidationException();
if (watchId == null) {
exception.addValidationError("watch id is missing");
} else if (PutWatchRequest.isValidId(watchId) == false) {
exception.addValidationError("watch id contains whitespace");
}
if (actionIds != null) {
for (String actionId : actionIds) {
if (actionId == null) {
exception.addValidationError(String.format(Locale.ROOT, "action id may not be null"));
} else if (PutWatchRequest.isValidId(actionId) == false) {
exception.addValidationError(
String.format(Locale.ROOT, "action id [%s] contains whitespace", actionId));
}
}
}
if (!exception.validationErrors().isEmpty()) {
throw exception;
}
}
/**
* @return The ID of the watch to be acked.
*/
public String getWatchId() {
return watchId;
}
/**
* @return The IDs of the actions to be acked. If omitted,
* all actions for the given watch will be acknowledged.
*/
public String[] getActionIds() {
return actionIds;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ack [").append(watchId).append("]");
if (actionIds.length > 0) {
sb.append("[");
for (int i = 0; i < actionIds.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(actionIds[i]);
}
sb.append("]");
}
return sb.toString();
}
}

View File

@ -1,61 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
/**
* The response from an 'ack watch' request.
*/
public class AckWatchResponse {
private final WatchStatus status;
public AckWatchResponse(WatchStatus status) {
this.status = status;
}
/**
* @return the status of the requested watch. If an action was
* successfully acknowledged, this will be reflected in its status.
*/
public WatchStatus getStatus() {
return status;
}
private static final ParseField STATUS_FIELD = new ParseField("status");
private static final ConstructingObjectParser<AckWatchResponse, Void> PARSER =
new ConstructingObjectParser<>("ack_watch_response", true,
a -> new AckWatchResponse((WatchStatus) a[0]));
static {
PARSER.declareObject(ConstructingObjectParser.constructorArg(),
(parser, context) -> WatchStatus.parse(parser),
STATUS_FIELD);
}
public static AckWatchResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}

View File

@ -1,342 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Locale;
import java.util.Objects;
public class ActionStatus {
private final AckStatus ackStatus;
@Nullable private final Execution lastExecution;
@Nullable private final Execution lastSuccessfulExecution;
@Nullable private final Throttle lastThrottle;
public ActionStatus(AckStatus ackStatus,
@Nullable Execution lastExecution,
@Nullable Execution lastSuccessfulExecution,
@Nullable Throttle lastThrottle) {
this.ackStatus = ackStatus;
this.lastExecution = lastExecution;
this.lastSuccessfulExecution = lastSuccessfulExecution;
this.lastThrottle = lastThrottle;
}
public AckStatus ackStatus() {
return ackStatus;
}
public Execution lastExecution() {
return lastExecution;
}
public Execution lastSuccessfulExecution() {
return lastSuccessfulExecution;
}
public Throttle lastThrottle() {
return lastThrottle;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActionStatus that = (ActionStatus) o;
return Objects.equals(ackStatus, that.ackStatus) &&
Objects.equals(lastExecution, that.lastExecution) &&
Objects.equals(lastSuccessfulExecution, that.lastSuccessfulExecution) &&
Objects.equals(lastThrottle, that.lastThrottle);
}
@Override
public int hashCode() {
return Objects.hash(ackStatus, lastExecution, lastSuccessfulExecution, lastThrottle);
}
public static ActionStatus parse(String actionId, XContentParser parser) throws IOException {
AckStatus ackStatus = null;
Execution lastExecution = null;
Execution lastSuccessfulExecution = null;
Throttle lastThrottle = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Field.ACK_STATUS.match(currentFieldName, parser.getDeprecationHandler())) {
ackStatus = AckStatus.parse(actionId, parser);
} else if (Field.LAST_EXECUTION.match(currentFieldName, parser.getDeprecationHandler())) {
lastExecution = Execution.parse(actionId, parser);
} else if (Field.LAST_SUCCESSFUL_EXECUTION.match(currentFieldName, parser.getDeprecationHandler())) {
lastSuccessfulExecution = Execution.parse(actionId, parser);
} else if (Field.LAST_THROTTLE.match(currentFieldName, parser.getDeprecationHandler())) {
lastThrottle = Throttle.parse(actionId, parser);
} else {
parser.skipChildren();
}
}
if (ackStatus == null) {
throw new ElasticsearchParseException("could not parse action status for [{}]. missing required field [{}]",
actionId, Field.ACK_STATUS.getPreferredName());
}
return new ActionStatus(ackStatus, lastExecution, lastSuccessfulExecution, lastThrottle);
}
public static class AckStatus {
public enum State {
AWAITS_SUCCESSFUL_EXECUTION,
ACKABLE,
ACKED;
}
private final ZonedDateTime timestamp;
private final State state;
public AckStatus(ZonedDateTime timestamp, State state) {
assert timestamp.getOffset() == ZoneOffset.UTC;
this.timestamp = timestamp;
this.state = state;
}
public ZonedDateTime timestamp() {
return timestamp;
}
public State state() {
return state;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AckStatus ackStatus = (AckStatus) o;
return Objects.equals(timestamp, ackStatus.timestamp) && Objects.equals(state, ackStatus.state);
}
@Override
public int hashCode() {
return Objects.hash(timestamp, state);
}
public static AckStatus parse(String actionId, XContentParser parser) throws IOException {
ZonedDateTime timestamp = null;
State state = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) {
timestamp = WatchStatusDateParser.parseDate(parser.text());
} else if (Field.ACK_STATUS_STATE.match(currentFieldName, parser.getDeprecationHandler())) {
state = State.valueOf(parser.text().toUpperCase(Locale.ROOT));
} else {
parser.skipChildren();
}
}
if (timestamp == null) {
throw new ElasticsearchParseException("could not parse action status for [{}]. missing required field [{}.{}]",
actionId, Field.ACK_STATUS.getPreferredName(), Field.TIMESTAMP.getPreferredName());
}
if (state == null) {
throw new ElasticsearchParseException("could not parse action status for [{}]. missing required field [{}.{}]",
actionId, Field.ACK_STATUS.getPreferredName(), Field.ACK_STATUS_STATE.getPreferredName());
}
return new AckStatus(timestamp, state);
}
}
public static class Execution {
public static Execution successful(ZonedDateTime timestamp) {
return new Execution(timestamp, true, null);
}
public static Execution failure(ZonedDateTime timestamp, String reason) {
return new Execution(timestamp, false, reason);
}
private final ZonedDateTime timestamp;
private final boolean successful;
private final String reason;
private Execution(ZonedDateTime timestamp, boolean successful, String reason) {
this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC);
this.successful = successful;
this.reason = reason;
}
public ZonedDateTime timestamp() {
return timestamp;
}
public boolean successful() {
return successful;
}
public String reason() {
return reason;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Execution execution = (Execution) o;
return Objects.equals(successful, execution.successful) &&
Objects.equals(timestamp, execution.timestamp) &&
Objects.equals(reason, execution.reason);
}
@Override
public int hashCode() {
return Objects.hash(timestamp, successful, reason);
}
public static Execution parse(String actionId, XContentParser parser) throws IOException {
ZonedDateTime timestamp = null;
Boolean successful = null;
String reason = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) {
timestamp = WatchStatusDateParser.parseDate(parser.text());
} else if (Field.EXECUTION_SUCCESSFUL.match(currentFieldName, parser.getDeprecationHandler())) {
successful = parser.booleanValue();
} else if (Field.REASON.match(currentFieldName, parser.getDeprecationHandler())) {
reason = parser.text();
} else {
parser.skipChildren();
}
}
if (timestamp == null) {
throw new ElasticsearchParseException("could not parse action status for [{}]. missing required field [{}.{}]",
actionId, Field.LAST_EXECUTION.getPreferredName(), Field.TIMESTAMP.getPreferredName());
}
if (successful == null) {
throw new ElasticsearchParseException("could not parse action status for [{}]. missing required field [{}.{}]",
actionId, Field.LAST_EXECUTION.getPreferredName(), Field.EXECUTION_SUCCESSFUL.getPreferredName());
}
if (successful) {
return successful(timestamp);
}
if (reason == null) {
throw new ElasticsearchParseException("could not parse action status for [{}]. missing required field for unsuccessful" +
" execution [{}.{}]", actionId, Field.LAST_EXECUTION.getPreferredName(), Field.REASON.getPreferredName());
}
return failure(timestamp, reason);
}
}
public static class Throttle {
private final ZonedDateTime timestamp;
private final String reason;
public Throttle(ZonedDateTime timestamp, String reason) {
this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC);
this.reason = reason;
}
public ZonedDateTime timestamp() {
return timestamp;
}
public String reason() {
return reason;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Throttle throttle = (Throttle) o;
return Objects.equals(timestamp, throttle.timestamp) && Objects.equals(reason, throttle.reason);
}
@Override
public int hashCode() {
return Objects.hash(timestamp, reason);
}
public static Throttle parse(String actionId, XContentParser parser) throws IOException {
ZonedDateTime timestamp = null;
String reason = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) {
timestamp = WatchStatusDateParser.parseDate(parser.text());
} else if (Field.REASON.match(currentFieldName, parser.getDeprecationHandler())) {
reason = parser.text();
} else {
parser.skipChildren();
}
}
if (timestamp == null) {
throw new ElasticsearchParseException("could not parse action status for [{}]. missing required field [{}.{}]",
actionId, Field.LAST_THROTTLE.getPreferredName(), Field.TIMESTAMP.getPreferredName());
}
if (reason == null) {
throw new ElasticsearchParseException("could not parse action status for [{}]. missing required field [{}.{}]",
actionId, Field.LAST_THROTTLE.getPreferredName(), Field.REASON.getPreferredName());
}
return new Throttle(timestamp, reason);
}
}
private interface Field {
ParseField ACK_STATUS = new ParseField("ack");
ParseField ACK_STATUS_STATE = new ParseField("state");
ParseField LAST_EXECUTION = new ParseField("last_execution");
ParseField LAST_SUCCESSFUL_EXECUTION = new ParseField("last_successful_execution");
ParseField EXECUTION_SUCCESSFUL = new ParseField("successful");
ParseField LAST_THROTTLE = new ParseField("last_throttle");
ParseField TIMESTAMP = new ParseField("timestamp");
ParseField REASON = new ParseField("reason");
}
}

View File

@ -1,60 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
import java.util.Objects;
/**
* A request to explicitly activate a watch.
*/
public final class ActivateWatchRequest implements Validatable {
private final String watchId;
public ActivateWatchRequest(String watchId) {
this.watchId = Objects.requireNonNull(watchId, "Watch identifier is required");
if (PutWatchRequest.isValidId(this.watchId) == false) {
throw new IllegalArgumentException("Watch identifier contains whitespace");
}
}
/**
* @return The ID of the watch to be activated.
*/
public String getWatchId() {
return watchId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActivateWatchRequest that = (ActivateWatchRequest) o;
return Objects.equals(watchId, that.watchId);
}
@Override
public int hashCode() {
int result = Objects.hash(watchId);
return result;
}
}

View File

@ -1,71 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
/**
* Response from an 'activate watch' request.
*/
public final class ActivateWatchResponse {
private static final ParseField STATUS_FIELD = new ParseField("status");
private static final ConstructingObjectParser<ActivateWatchResponse, Void> PARSER =
new ConstructingObjectParser<>("activate_watch_response", true,
a -> new ActivateWatchResponse((WatchStatus) a[0]));
static {
PARSER.declareObject(ConstructingObjectParser.constructorArg(),
(parser, context) -> WatchStatus.parse(parser),
STATUS_FIELD);
}
private final WatchStatus status;
public ActivateWatchResponse(WatchStatus status) {
this.status = status;
}
public WatchStatus getStatus() {
return status;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActivateWatchResponse that = (ActivateWatchResponse) o;
return Objects.equals(status, that.status);
}
@Override
public int hashCode() {
return Objects.hash(status);
}
public static ActivateWatchResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}

View File

@ -1,42 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.client.watcher.PutWatchRequest;
import java.util.Objects;
public class DeactivateWatchRequest implements Validatable {
private final String watchId;
public DeactivateWatchRequest(String watchId) {
Objects.requireNonNull(watchId, "watch id is missing");
if (PutWatchRequest.isValidId(watchId) == false) {
throw new IllegalArgumentException("watch id contains whitespace");
}
this.watchId = watchId;
}
public String getWatchId() {
return watchId;
}
}

View File

@ -1,65 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
public class DeactivateWatchResponse {
private WatchStatus status;
private static final ParseField STATUS_FIELD = new ParseField("status");
private static final ConstructingObjectParser<DeactivateWatchResponse, Void> PARSER
= new ConstructingObjectParser<>("x_pack_deactivate_watch_response", true,
(fields) -> new DeactivateWatchResponse((WatchStatus) fields[0]));
static {
PARSER.declareObject(ConstructingObjectParser.constructorArg(),
(parser, context) -> WatchStatus.parse(parser),
STATUS_FIELD);
}
public static DeactivateWatchResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
public DeactivateWatchResponse(WatchStatus status) {
this.status = status;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeactivateWatchResponse that = (DeactivateWatchResponse) o;
return Objects.equals(status, that.status);
}
@Override
public int hashCode() {
return Objects.hash(status);
}
public WatchStatus getStatus() {
return status;
}
}

View File

@ -1,51 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
import java.util.Objects;
/**
* A delete watch request to delete an watch by name (id)
*/
public class DeleteWatchRequest implements Validatable {
private final String id;
public DeleteWatchRequest(String id) {
Objects.requireNonNull(id, "watch id is missing");
if (PutWatchRequest.isValidId(id) == false) {
throw new IllegalArgumentException("watch id contains whitespace");
}
this.id = id;
}
/**
* @return The name of the watch to be deleted
*/
public String getId() {
return id;
}
@Override
public String toString() {
return "delete [" + id + "]";
}
}

View File

@ -1,93 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
public class DeleteWatchResponse {
private static final ObjectParser<DeleteWatchResponse, Void> PARSER
= new ObjectParser<>("x_pack_delete_watch_response", true, DeleteWatchResponse::new);
static {
PARSER.declareString(DeleteWatchResponse::setId, new ParseField("_id"));
PARSER.declareLong(DeleteWatchResponse::setVersion, new ParseField("_version"));
PARSER.declareBoolean(DeleteWatchResponse::setFound, new ParseField("found"));
}
private String id;
private long version;
private boolean found;
public DeleteWatchResponse() {
}
public DeleteWatchResponse(String id, long version, boolean found) {
this.id = id;
this.version = version;
this.found = found;
}
public String getId() {
return id;
}
public long getVersion() {
return version;
}
public boolean isFound() {
return found;
}
private void setId(String id) {
this.id = id;
}
private void setVersion(long version) {
this.version = version;
}
private void setFound(boolean found) {
this.found = found;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeleteWatchResponse that = (DeleteWatchResponse) o;
return Objects.equals(id, that.id) && Objects.equals(version, that.version) && Objects.equals(found, that.found);
}
@Override
public int hashCode() {
return Objects.hash(id, version, found);
}
public static DeleteWatchResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}

View File

@ -1,175 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* An execute watch request to execute a watch by id or inline
*/
public class ExecuteWatchRequest implements Validatable, ToXContentObject {
public enum ActionExecutionMode {
SIMULATE, FORCE_SIMULATE, EXECUTE, FORCE_EXECUTE, SKIP
}
private final String id;
private final BytesReference watchContent;
private boolean ignoreCondition = false;
private boolean recordExecution = false;
private boolean debug = false;
@Nullable
private BytesReference triggerData = null;
@Nullable
private BytesReference alternativeInput = null;
private Map<String, ActionExecutionMode> actionModes = new HashMap<>();
/**
* Execute an existing watch on the cluster
*
* @param id the id of the watch to execute
*/
public static ExecuteWatchRequest byId(String id) {
return new ExecuteWatchRequest(Objects.requireNonNull(id, "Watch id cannot be null"), null);
}
/**
* Execute an inline watch
* @param watchContent the JSON definition of the watch
*/
public static ExecuteWatchRequest inline(String watchContent) {
return new ExecuteWatchRequest(null, Objects.requireNonNull(watchContent, "Watch content cannot be null"));
}
private ExecuteWatchRequest(String id, String watchContent) {
this.id = id;
this.watchContent = watchContent == null ? null : new BytesArray(watchContent);
}
public String getId() {
return this.id;
}
/**
* @param ignoreCondition set if the condition for this execution be ignored
*/
public void setIgnoreCondition(boolean ignoreCondition) {
this.ignoreCondition = ignoreCondition;
}
public boolean ignoreCondition() {
return ignoreCondition;
}
/**
* @param recordExecution Sets if this execution be recorded in the history index
*/
public void setRecordExecution(boolean recordExecution) {
if (watchContent != null && recordExecution) {
throw new IllegalArgumentException("The execution of an inline watch cannot be recorded");
}
this.recordExecution = recordExecution;
}
public boolean recordExecution() {
return recordExecution;
}
/**
* @param alternativeInput Sets the alternative input
*/
public void setAlternativeInput(String alternativeInput) {
this.alternativeInput = new BytesArray(alternativeInput);
}
/**
* @param data A JSON string representing the data that should be associated with the trigger event.
*/
public void setTriggerData(String data) {
this.triggerData = new BytesArray(data);
}
/**
* Sets the action execution mode for the give action (identified by its id).
*
* @param actionId the action id.
* @param actionMode the execution mode of the action.
*/
public void setActionMode(String actionId, ActionExecutionMode actionMode) {
Objects.requireNonNull(actionId, "actionId cannot be null");
actionModes.put(actionId, actionMode);
}
public Map<String, ActionExecutionMode> getActionModes() {
return this.actionModes;
}
/**
* @param debug indicates whether the watch should execute in debug mode. In debug mode the
* returned watch record will hold the execution {@code vars}
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
public boolean isDebug() {
return debug;
}
@Override
public String toString() {
return "execute[" + id + "]";
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (triggerData != null) {
builder.rawField("trigger_data", triggerData.streamInput(), XContentType.JSON);
}
if (alternativeInput != null) {
builder.rawField("alternative_input", alternativeInput.streamInput(), XContentType.JSON);
}
if (actionModes.size() > 0) {
builder.field("action_modes", actionModes);
}
if (watchContent != null) {
builder.rawField("watch", watchContent.streamInput(), XContentType.JSON);
}
builder.endObject();
return builder;
}
}

View File

@ -1,106 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.XContentUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
public class ExecuteWatchResponse {
public static final ParseField ID_FIELD = new ParseField("_id");
public static final ParseField WATCH_FIELD = new ParseField("watch_record");
private String recordId;
private BytesReference contentSource;
private Map<String, Object> data;
public ExecuteWatchResponse() {
}
public ExecuteWatchResponse(String recordId, BytesReference contentSource) {
this.recordId = recordId;
this.contentSource = contentSource;
}
/**
* @return The id of the watch record holding the watch execution result.
*/
public String getRecordId() {
return recordId;
}
/**
* @return The watch record source
*/
public BytesReference getRecord() {
return contentSource;
}
/**
* Returns the watch record as a map
*
* Use {@link org.elasticsearch.common.xcontent.ObjectPath} to navigate through the data
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getRecordAsMap() {
if (data == null) {
// EMPTY is safe here because we never use namedObject
try (InputStream stream = contentSource.streamInput();
XContentParser parser = XContentType.JSON.xContent().createParser(NamedXContentRegistry.EMPTY, null, stream)) {
data = (Map<String, Object>) XContentUtils.readValue(parser, parser.nextToken());
} catch (IOException ex) {
throw new ElasticsearchException("failed to read value", ex);
}
}
return data;
}
private static final ConstructingObjectParser<ExecuteWatchResponse, Void> PARSER
= new ConstructingObjectParser<>("x_pack_execute_watch_response", true,
(fields) -> new ExecuteWatchResponse((String)fields[0], (BytesReference) fields[1]));
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), ID_FIELD);
PARSER.declareObject(ConstructingObjectParser.constructorArg(), (p, c) -> readBytesReference(p), WATCH_FIELD);
}
public static ExecuteWatchResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
private static BytesReference readBytesReference(XContentParser parser) throws IOException {
try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
builder.copyCurrentStructure(parser);
return BytesReference.bytes(builder);
}
}
}

View File

@ -1,50 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
public enum ExecutionPhase {
// awaiting execution of the watch
AWAITS_EXECUTION(false),
// initial phase, watch execution has started, but the input is not yet processed
STARTED(false),
// input is being executed
INPUT(false),
// condition phase is being executed
CONDITION(false),
// transform phase (optional, depends if a global transform was configured in the watch)
WATCH_TRANSFORM(false),
// actions phase, all actions, including specific action transforms
ACTIONS(false),
// missing watch, failed execution of input/condition/transform,
ABORTED(true),
// successful run
FINISHED(true);
private final boolean sealed;
ExecutionPhase(boolean sealed) {
this.sealed = sealed;
}
public boolean sealed() {
return sealed;
}
}

View File

@ -1,68 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import java.util.Locale;
public enum ExecutionState {
// the condition of the watch was not met
EXECUTION_NOT_NEEDED,
// Execution has been throttled due to time-based throttling - this might only affect a single action though
THROTTLED,
// Execution has been throttled due to ack-based throttling/muting of an action - this might only affect a single action though
ACKNOWLEDGED,
// regular execution
EXECUTED,
// an error in the condition or the execution of the input
FAILED,
// a rejection due to a filled up threadpool
THREADPOOL_REJECTION,
// the execution was scheduled, but in between the watch was deleted
NOT_EXECUTED_WATCH_MISSING,
// even though the execution was scheduled, it was not executed, because the watch was already queued in the thread pool
NOT_EXECUTED_ALREADY_QUEUED,
// this can happen when a watch was executed, but not completely finished (the triggered watch entry was not deleted), and then
// watcher is restarted (manually or due to host switch) - the triggered watch will be executed but the history entry already
// exists
EXECUTED_MULTIPLE_TIMES;
public String id() {
return name().toLowerCase(Locale.ROOT);
}
public static ExecutionState resolve(String id) {
return valueOf(id.toUpperCase(Locale.ROOT));
}
@Override
public String toString() {
return id();
}
}

View File

@ -1,54 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.client.ValidationException;
/**
* The request to get the watch by name (id)
*/
public final class GetWatchRequest implements Validatable {
private final String id;
public GetWatchRequest(String watchId) {
validateId(watchId);
this.id = watchId;
}
private void validateId(String id) {
ValidationException exception = new ValidationException();
if (id == null) {
exception.addValidationError("watch id is missing");
} else if (PutWatchRequest.isValidId(id) == false) {
exception.addValidationError("watch id contains whitespace");
}
if (exception.validationErrors().isEmpty() == false) {
throw exception;
}
}
/**
* @return The name of the watch to retrieve
*/
public String getId() {
return id;
}
}

View File

@ -1,169 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
public class GetWatchResponse {
private final String id;
private final long version;
private final long seqNo;
private final long primaryTerm;
private final WatchStatus status;
private final BytesReference source;
private final XContentType xContentType;
/**
* Ctor for missing watch
*/
public GetWatchResponse(String id) {
this(id, Versions.NOT_FOUND, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, null, null, null);
}
public GetWatchResponse(String id, long version, long seqNo, long primaryTerm, WatchStatus status,
BytesReference source, XContentType xContentType) {
this.id = id;
this.version = version;
this.status = status;
this.source = source;
this.xContentType = xContentType;
this.seqNo = seqNo;
this.primaryTerm = primaryTerm;
}
public String getId() {
return id;
}
public long getVersion() {
return version;
}
public long getSeqNo() {
return seqNo;
}
public long getPrimaryTerm() {
return primaryTerm;
}
public boolean isFound() {
return version != Versions.NOT_FOUND;
}
public WatchStatus getStatus() {
return status;
}
/**
* Returns the {@link XContentType} of the source
*/
public XContentType getContentType() {
return xContentType;
}
/**
* Returns the serialized watch
*/
public BytesReference getSource() {
return source;
}
/**
* Returns the source as a map
*/
public Map<String, Object> getSourceAsMap() {
return source == null ? null : XContentHelper.convertToMap(source, false, getContentType()).v2();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GetWatchResponse that = (GetWatchResponse) o;
return version == that.version &&
Objects.equals(id, that.id) &&
Objects.equals(status, that.status) &&
Objects.equals(xContentType, that.xContentType) &&
Objects.equals(source, that.source);
}
@Override
public int hashCode() {
return Objects.hash(id, status, source, version);
}
private static final ParseField ID_FIELD = new ParseField("_id");
private static final ParseField FOUND_FIELD = new ParseField("found");
private static final ParseField VERSION_FIELD = new ParseField("_version");
private static final ParseField SEQ_NO_FIELD = new ParseField("_seq_no");
private static final ParseField PRIMARY_TERM_FIELD = new ParseField("_primary_term");
private static final ParseField STATUS_FIELD = new ParseField("status");
private static final ParseField WATCH_FIELD = new ParseField("watch");
private static final ConstructingObjectParser<GetWatchResponse, Void> PARSER =
new ConstructingObjectParser<>("get_watch_response", true,
a -> {
boolean isFound = (boolean) a[1];
if (isFound) {
XContentBuilder builder = (XContentBuilder) a[6];
BytesReference source = BytesReference.bytes(builder);
return new GetWatchResponse((String) a[0], (long) a[2], (long) a[3], (long) a[4], (WatchStatus) a[5],
source, builder.contentType());
} else {
return new GetWatchResponse((String) a[0]);
}
});
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), ID_FIELD);
PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), FOUND_FIELD);
PARSER.declareLong(ConstructingObjectParser.optionalConstructorArg(), VERSION_FIELD);
PARSER.declareLong(ConstructingObjectParser.optionalConstructorArg(), SEQ_NO_FIELD);
PARSER.declareLong(ConstructingObjectParser.optionalConstructorArg(), PRIMARY_TERM_FIELD);
PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(),
(parser, context) -> WatchStatus.parse(parser), STATUS_FIELD);
PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(),
(parser, context) -> {
try (XContentBuilder builder = XContentBuilder.builder(parser.contentType().xContent())) {
builder.copyCurrentStructure(parser);
return builder;
}
}, WATCH_FIELD);
}
public static GetWatchResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}

View File

@ -1,148 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.seqno.SequenceNumbers;
import java.util.Objects;
import java.util.regex.Pattern;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
/**
* This request class contains the data needed to create a watch along with the name of the watch.
* The name of the watch will become the ID of the indexed document.
*/
public final class PutWatchRequest implements Validatable {
private static final Pattern NO_WS_PATTERN = Pattern.compile("\\S+");
private final String id;
private final BytesReference source;
private final XContentType xContentType;
private boolean active = true;
private long ifSeqNo = SequenceNumbers.UNASSIGNED_SEQ_NO;
private long ifPrimaryTerm = UNASSIGNED_PRIMARY_TERM;
public PutWatchRequest(String id, BytesReference source, XContentType xContentType) {
Objects.requireNonNull(id, "watch id is missing");
if (isValidId(id) == false) {
throw new IllegalArgumentException("watch id contains whitespace");
}
Objects.requireNonNull(source, "watch source is missing");
Objects.requireNonNull(xContentType, "request body is missing");
this.id = id;
this.source = source;
this.xContentType = xContentType;
}
/**
* @return The name that will be the ID of the indexed document
*/
public String getId() {
return id;
}
/**
* @return The source of the watch
*/
public BytesReference getSource() {
return source;
}
/**
* @return The initial active state of the watch (defaults to {@code true}, e.g. "active")
*/
public boolean isActive() {
return active;
}
/**
* Sets the initial active state of the watch
*/
public void setActive(boolean active) {
this.active = active;
}
/**
* Get the content type for the source
*/
public XContentType xContentType() {
return xContentType;
}
/**
* only performs this put request if the watch's last modification was assigned the given
* sequence number. Must be used in combination with {@link #setIfPrimaryTerm(long)}
*
* If the watch's last modification was assigned a different sequence number a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public PutWatchRequest setIfSeqNo(long seqNo) {
if (seqNo < 0 && seqNo != UNASSIGNED_SEQ_NO) {
throw new IllegalArgumentException("sequence numbers must be non negative. got [" + seqNo + "].");
}
ifSeqNo = seqNo;
return this;
}
/**
* only performs this put request if the watch's last modification was assigned the given
* primary term. Must be used in combination with {@link #setIfSeqNo(long)}
*
* If the watch last modification was assigned a different term a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public PutWatchRequest setIfPrimaryTerm(long term) {
if (term < 0) {
throw new IllegalArgumentException("primary term must be non negative. got [" + term + "]");
}
ifPrimaryTerm = term;
return this;
}
/**
* If set, only perform this put watch request if the watch's last modification was assigned this sequence number.
* If the watch last last modification was assigned a different sequence number a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public long ifSeqNo() {
return ifSeqNo;
}
/**
* If set, only perform this put watch request if the watch's last modification was assigned this primary term.
*
* If the watch's last modification was assigned a different term a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public long ifPrimaryTerm() {
return ifPrimaryTerm;
}
public static boolean isValidId(String id) {
return Strings.isEmpty(id) == false && NO_WS_PATTERN.matcher(id).matches();
}
}

View File

@ -1,120 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.seqno.SequenceNumbers;
import java.io.IOException;
import java.util.Objects;
public class PutWatchResponse {
private static final ObjectParser<PutWatchResponse, Void> PARSER
= new ObjectParser<>("x_pack_put_watch_response", true, PutWatchResponse::new);
static {
PARSER.declareString(PutWatchResponse::setId, new ParseField("_id"));
PARSER.declareLong(PutWatchResponse::setSeqNo, new ParseField("_seq_no"));
PARSER.declareLong(PutWatchResponse::setPrimaryTerm, new ParseField("_primary_term"));
PARSER.declareLong(PutWatchResponse::setVersion, new ParseField("_version"));
PARSER.declareBoolean(PutWatchResponse::setCreated, new ParseField("created"));
}
private String id;
private long version;
private long seqNo = SequenceNumbers.UNASSIGNED_SEQ_NO;
private long primaryTerm = SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
private boolean created;
public PutWatchResponse() {
}
public PutWatchResponse(String id, long version, long seqNo, long primaryTerm, boolean created) {
this.id = id;
this.version = version;
this.seqNo = seqNo;
this.primaryTerm = primaryTerm;
this.created = created;
}
private void setId(String id) {
this.id = id;
}
private void setVersion(long version) {
this.version = version;
}
private void setSeqNo(long seqNo) {
this.seqNo = seqNo;
}
private void setPrimaryTerm(long primaryTerm) {
this.primaryTerm = primaryTerm;
}
private void setCreated(boolean created) {
this.created = created;
}
public String getId() {
return id;
}
public long getVersion() {
return version;
}
public long getSeqNo() {
return seqNo;
}
public long getPrimaryTerm() {
return primaryTerm;
}
public boolean isCreated() {
return created;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PutWatchResponse that = (PutWatchResponse) o;
return Objects.equals(id, that.id) && Objects.equals(version, that.version)
&& Objects.equals(seqNo, that.seqNo)
&& Objects.equals(primaryTerm, that.primaryTerm) && Objects.equals(created, that.created);
}
@Override
public int hashCode() {
return Objects.hash(id, version, seqNo, primaryTerm, created);
}
public static PutWatchResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}

View File

@ -1,91 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.joda.time.DateTime;
import java.util.Objects;
public class QueuedWatch {
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<QueuedWatch, Void> PARSER =
new ConstructingObjectParser<>("watcher_stats_node", true, (args, c) -> new QueuedWatch(
(String) args[0],
(String) args[1],
DateTime.parse((String) args[2]),
DateTime.parse((String) args[3])
));
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watch_id"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watch_record_id"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("triggered_time"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("execution_time"));
}
private final String watchId;
private final String watchRecordId;
private final DateTime triggeredTime;
private final DateTime executionTime;
public QueuedWatch(String watchId, String watchRecordId, DateTime triggeredTime, DateTime executionTime) {
this.watchId = watchId;
this.watchRecordId = watchRecordId;
this.triggeredTime = triggeredTime;
this.executionTime = executionTime;
}
public String getWatchId() {
return watchId;
}
public String getWatchRecordId() {
return watchRecordId;
}
public DateTime getTriggeredTime() {
return triggeredTime;
}
public DateTime getExecutionTime() {
return executionTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
QueuedWatch that = (QueuedWatch) o;
return Objects.equals(watchId, that.watchId) &&
Objects.equals(watchRecordId, that.watchRecordId) &&
Objects.equals(triggeredTime, that.triggeredTime) &&
Objects.equals(executionTime, that.executionTime);
}
@Override
public int hashCode() {
return Objects.hash(watchId, watchRecordId, triggeredTime, executionTime);
}
}

View File

@ -1,26 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
public class StartWatchServiceRequest implements Validatable {
}

View File

@ -1,26 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
public class StopWatchServiceRequest implements Validatable {
}

View File

@ -1,123 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.joda.time.DateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
public class WatchExecutionSnapshot {
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<WatchExecutionSnapshot, Void> PARSER =
new ConstructingObjectParser<>("watcher_stats_node", true, (args, c) -> new WatchExecutionSnapshot(
(String) args[0],
(String) args[1],
DateTime.parse((String) args[2]),
DateTime.parse((String) args[3]),
ExecutionPhase.valueOf(((String) args[4]).toUpperCase(Locale.ROOT)),
args[5] == null ? null : ((List<String>) args[5]).toArray(new String[0]),
args[6] == null ? null : ((List<String>) args[6]).toArray(new String[0])
));
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watch_id"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watch_record_id"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("triggered_time"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("execution_time"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("execution_phase"));
PARSER.declareStringArray(ConstructingObjectParser.optionalConstructorArg(), new ParseField("executed_actions"));
PARSER.declareStringArray(ConstructingObjectParser.optionalConstructorArg(), new ParseField("stack_trace"));
}
private final String watchId;
private final String watchRecordId;
private final DateTime triggeredTime;
private final DateTime executionTime;
private final ExecutionPhase phase;
private final String[] executedActions;
private final String[] executionStackTrace;
public WatchExecutionSnapshot(String watchId, String watchRecordId, DateTime triggeredTime, DateTime executionTime,
ExecutionPhase phase, String[] executedActions, String[] executionStackTrace) {
this.watchId = watchId;
this.watchRecordId = watchRecordId;
this.triggeredTime = triggeredTime;
this.executionTime = executionTime;
this.phase = phase;
this.executedActions = executedActions;
this.executionStackTrace = executionStackTrace;
}
public String getWatchId() {
return watchId;
}
public String getWatchRecordId() {
return watchRecordId;
}
public DateTime getTriggeredTime() {
return triggeredTime;
}
public DateTime getExecutionTime() {
return executionTime;
}
public ExecutionPhase getPhase() {
return phase;
}
public String[] getExecutedActions() {
return executedActions;
}
public String[] getExecutionStackTrace() {
return executionStackTrace;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WatchExecutionSnapshot that = (WatchExecutionSnapshot) o;
return Objects.equals(watchId, that.watchId) &&
Objects.equals(watchRecordId, that.watchRecordId) &&
Objects.equals(triggeredTime, that.triggeredTime) &&
Objects.equals(executionTime, that.executionTime) &&
phase == that.phase &&
Arrays.equals(executedActions, that.executedActions) &&
Arrays.equals(executionStackTrace, that.executionStackTrace);
}
@Override
public int hashCode() {
int result = Objects.hash(watchId, watchRecordId, triggeredTime, executionTime, phase);
result = 31 * result + Arrays.hashCode(executedActions);
result = 31 * result + Arrays.hashCode(executionStackTrace);
return result;
}
}

View File

@ -1,255 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.client.watcher.WatchStatusDateParser.parseDate;
import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;
public class WatchStatus {
private final State state;
private final ExecutionState executionState;
private final ZonedDateTime lastChecked;
private final ZonedDateTime lastMetCondition;
private final long version;
private final Map<String, ActionStatus> actions;
@Nullable private Map<String, String> headers;
public WatchStatus(long version,
State state,
ExecutionState executionState,
ZonedDateTime lastChecked,
ZonedDateTime lastMetCondition,
Map<String, ActionStatus> actions,
Map<String, String> headers) {
this.version = version;
this.lastChecked = lastChecked;
this.lastMetCondition = lastMetCondition;
this.actions = actions;
this.state = state;
this.executionState = executionState;
this.headers = headers;
}
public State state() {
return state;
}
public boolean checked() {
return lastChecked != null;
}
public ZonedDateTime lastChecked() {
return lastChecked;
}
public ZonedDateTime lastMetCondition() {
return lastMetCondition;
}
public ActionStatus actionStatus(String actionId) {
return actions.get(actionId);
}
public Map<String, ActionStatus> getActions() {
return actions;
}
public long version() {
return version;
}
public ExecutionState getExecutionState() {
return executionState;
}
public Map<String, String> getHeaders() {
return headers;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WatchStatus that = (WatchStatus) o;
return Objects.equals(lastChecked, that.lastChecked) &&
Objects.equals(lastMetCondition, that.lastMetCondition) &&
Objects.equals(version, that.version) &&
Objects.equals(executionState, that.executionState) &&
Objects.equals(actions, that.actions) &&
Objects.equals(headers, that.headers);
}
@Override
public int hashCode() {
return Objects.hash(lastChecked, lastMetCondition, actions, version, executionState);
}
public static WatchStatus parse(XContentParser parser) throws IOException {
State state = null;
ExecutionState executionState = null;
ZonedDateTime lastChecked = null;
ZonedDateTime lastMetCondition = null;
Map<String, ActionStatus> actions = null;
Map<String, String> headers = Collections.emptyMap();
long version = -1;
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser);
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Field.STATE.match(currentFieldName, parser.getDeprecationHandler())) {
try {
state = State.parse(parser);
} catch (ElasticsearchParseException e) {
throw new ElasticsearchParseException("could not parse watch status. failed to parse field [{}]",
e, currentFieldName);
}
} else if (Field.VERSION.match(currentFieldName, parser.getDeprecationHandler())) {
if (token.isValue()) {
version = parser.longValue();
} else {
throw new ElasticsearchParseException("could not parse watch status. expecting field [{}] to hold a long " +
"value, found [{}] instead", currentFieldName, token);
}
} else if (Field.LAST_CHECKED.match(currentFieldName, parser.getDeprecationHandler())) {
if (token.isValue()) {
lastChecked = parseDate(currentFieldName, parser);
} else {
throw new ElasticsearchParseException("could not parse watch status. expecting field [{}] to hold a date " +
"value, found [{}] instead", currentFieldName, token);
}
} else if (Field.LAST_MET_CONDITION.match(currentFieldName, parser.getDeprecationHandler())) {
if (token.isValue()) {
lastMetCondition = parseDate(currentFieldName, parser);
} else {
throw new ElasticsearchParseException("could not parse watch status. expecting field [{}] to hold a date " +
"value, found [{}] instead", currentFieldName, token);
}
} else if (Field.EXECUTION_STATE.match(currentFieldName, parser.getDeprecationHandler())) {
if (token.isValue()) {
executionState = ExecutionState.resolve(parser.text());
} else {
throw new ElasticsearchParseException("could not parse watch status. expecting field [{}] to hold a string " +
"value, found [{}] instead", currentFieldName, token);
}
} else if (Field.ACTIONS.match(currentFieldName, parser.getDeprecationHandler())) {
actions = new HashMap<>();
if (token == XContentParser.Token.START_OBJECT) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
ActionStatus actionStatus = ActionStatus.parse(currentFieldName, parser);
actions.put(currentFieldName, actionStatus);
}
}
} else {
throw new ElasticsearchParseException("could not parse watch status. expecting field [{}] to be an object, " +
"found [{}] instead", currentFieldName, token);
}
} else if (Field.HEADERS.match(currentFieldName, parser.getDeprecationHandler())) {
if (token == XContentParser.Token.START_OBJECT) {
headers = parser.mapStrings();
}
} else {
parser.skipChildren();
}
}
actions = actions == null ? emptyMap() : unmodifiableMap(actions);
return new WatchStatus(version, state, executionState, lastChecked, lastMetCondition, actions, headers);
}
public static class State {
private final boolean active;
private final ZonedDateTime timestamp;
public State(boolean active, ZonedDateTime timestamp) {
this.active = active;
this.timestamp = timestamp;
}
public boolean isActive() {
return active;
}
public ZonedDateTime getTimestamp() {
return timestamp;
}
public static State parse(XContentParser parser) throws IOException {
if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException("expected an object but found [{}] instead", parser.currentToken());
}
boolean active = true;
ZonedDateTime timestamp = ZonedDateTime.now(ZoneOffset.UTC);
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Field.ACTIVE.match(currentFieldName, parser.getDeprecationHandler())) {
active = parser.booleanValue();
} else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) {
timestamp = parseDate(currentFieldName, parser);
} else {
parser.skipChildren();
}
}
return new State(active, timestamp);
}
}
public interface Field {
ParseField STATE = new ParseField("state");
ParseField ACTIVE = new ParseField("active");
ParseField TIMESTAMP = new ParseField("timestamp");
ParseField LAST_CHECKED = new ParseField("last_checked");
ParseField LAST_MET_CONDITION = new ParseField("last_met_condition");
ParseField ACTIONS = new ParseField("actions");
ParseField VERSION = new ParseField("version");
ParseField EXECUTION_STATE = new ParseField("execution_state");
ParseField HEADERS = new ParseField("headers");
}
}

View File

@ -1,60 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.time.DateFormatter;
import org.elasticsearch.common.time.DateFormatters;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.DateFieldMapper;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public final class WatchStatusDateParser {
private static final DateFormatter FORMATTER = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER;
private WatchStatusDateParser() {
// Prevent instantiation.
}
public static ZonedDateTime parseDate(String fieldName, XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
if (token == XContentParser.Token.VALUE_NUMBER) {
return Instant.ofEpochMilli(parser.longValue()).atZone(ZoneOffset.UTC);
}
if (token == XContentParser.Token.VALUE_STRING) {
ZonedDateTime dateTime = parseDate(parser.text());
return dateTime.withZoneSameInstant(ZoneOffset.UTC);
}
if (token == XContentParser.Token.VALUE_NULL) {
return null;
}
throw new ElasticsearchParseException("could not parse date/time. expected date field [{}] " +
"to be either a number or a string but found [{}] instead", fieldName, token);
}
public static ZonedDateTime parseDate(String text) {
return DateFormatters.from(FORMATTER.parse(text));
}
}

View File

@ -1,54 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import java.util.Objects;
public class WatcherMetadata {
private final boolean manuallyStopped;
public WatcherMetadata(boolean manuallyStopped) {
this.manuallyStopped = manuallyStopped;
}
public boolean manuallyStopped() {
return manuallyStopped;
}
@Override
public String toString() {
return "manuallyStopped["+ manuallyStopped +"]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WatcherMetadata action = (WatcherMetadata) o;
return manuallyStopped == action.manuallyStopped;
}
@Override
public int hashCode() {
return Objects.hash(manuallyStopped);
}
}

View File

@ -1,54 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
public enum WatcherState {
/**
* The watcher plugin is not running and not functional.
*/
STOPPED(0),
/**
* The watcher plugin is performing the necessary operations to get into a started state.
*/
STARTING(1),
/**
* The watcher plugin is running and completely functional.
*/
STARTED(2),
/**
* The watcher plugin is shutting down and not functional.
*/
STOPPING(3);
private final byte id;
WatcherState(int id) {
this.id = (byte) id;
}
public byte getId() {
return id;
}
}

View File

@ -1,53 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.Validatable;
/**
* A request to explicitly acknowledge a watch.
*/
public class WatcherStatsRequest implements Validatable {
private final boolean includeCurrentWatches;
private final boolean includeQueuedWatches;
public WatcherStatsRequest( ) {
this(true, true);
}
public WatcherStatsRequest(boolean includeCurrentWatches, boolean includeQueuedWatches) {
this.includeCurrentWatches = includeCurrentWatches;
this.includeQueuedWatches = includeQueuedWatches;
}
public boolean includeCurrentWatches() {
return includeCurrentWatches;
}
public boolean includeQueuedWatches() {
return includeQueuedWatches;
}
@Override
public String toString() {
return "stats [current=" + includeCurrentWatches + ", " + "queued=" + includeQueuedWatches + "]";
}
}

View File

@ -1,229 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.NodesResponseHeader;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
/**
* The response from an 'ack watch' request.
*/
public class WatcherStatsResponse {
private final List<Node> nodes;
private final NodesResponseHeader header;
private final String clusterName;
private final WatcherMetadata watcherMetadata;
public WatcherStatsResponse(NodesResponseHeader header, String clusterName, WatcherMetadata watcherMetadata, List<Node> nodes) {
this.nodes = nodes;
this.header = header;
this.clusterName = clusterName;
this.watcherMetadata = watcherMetadata;
}
/**
* @return the status of the requested watch. If an action was
* successfully acknowledged, this will be reflected in its status.
*/
public WatcherMetadata getWatcherMetadata() {
return watcherMetadata;
}
/**
* returns a list of nodes that returned stats
*/
public List<Node> getNodes() {
return nodes;
}
/**
* Gets information about the number of total, successful and failed nodes the request was run on.
* Also includes exceptions if relevant.
*/
public NodesResponseHeader getHeader() {
return header;
}
/**
* Get the cluster name associated with all of the nodes.
*
* @return Never {@code null}.
*/
public String getClusterName() {
return clusterName;
}
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<WatcherStatsResponse, Void> PARSER =
new ConstructingObjectParser<>("watcher_stats_response", true,
a -> new WatcherStatsResponse((NodesResponseHeader) a[0], (String) a[1], new WatcherMetadata((boolean) a[2]),
(List<Node>) a[3]));
static {
PARSER.declareObject(ConstructingObjectParser.constructorArg(), NodesResponseHeader::fromXContent, new ParseField("_nodes"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("cluster_name"));
PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), new ParseField("manually_stopped"));
PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), (p, c) -> Node.PARSER.apply(p, null),
new ParseField("stats"));
}
public static WatcherStatsResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WatcherStatsResponse that = (WatcherStatsResponse) o;
return Objects.equals(nodes, that.nodes) &&
Objects.equals(header, that.header) &&
Objects.equals(clusterName, that.clusterName) &&
Objects.equals(watcherMetadata, that.watcherMetadata);
}
@Override
public int hashCode() {
return Objects.hash(nodes, header, clusterName, watcherMetadata);
}
public static class Node {
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<Node, Void> PARSER =
new ConstructingObjectParser<>("watcher_stats_node", true, (args, c) -> new Node(
(String) args[0],
WatcherState.valueOf(((String) args[1]).toUpperCase(Locale.ROOT)),
(long) args[2],
((Tuple<Long, Long>) args[3]).v1(),
((Tuple<Long, Long>) args[3]).v2(),
(List<WatchExecutionSnapshot>) args[4],
(List<QueuedWatch>) args[5],
(Map<String, Object>) args[6]
));
private static final ConstructingObjectParser<Tuple<Long, Long>, Void> THREAD_POOL_PARSER =
new ConstructingObjectParser<>("execution_thread_pool", true, (args, id) -> new Tuple<>((Long) args[0], (Long) args[1]));
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("node_id"));
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watcher_state"));
PARSER.declareLong(ConstructingObjectParser.constructorArg(), new ParseField("watch_count"));
PARSER.declareObject(ConstructingObjectParser.constructorArg(), THREAD_POOL_PARSER::apply,
new ParseField("execution_thread_pool"));
PARSER.declareObjectArray(ConstructingObjectParser.optionalConstructorArg(), WatchExecutionSnapshot.PARSER,
new ParseField("current_watches"));
PARSER.declareObjectArray(ConstructingObjectParser.optionalConstructorArg(), QueuedWatch.PARSER,
new ParseField("queued_watches"));
PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.map(), new ParseField("stats"));
THREAD_POOL_PARSER.declareLong(ConstructingObjectParser.constructorArg(), new ParseField("queue_size"));
THREAD_POOL_PARSER.declareLong(ConstructingObjectParser.constructorArg(), new ParseField("max_size"));
}
private final String nodeId;
private WatcherState watcherState;
private long watchesCount;
private long threadPoolQueueSize;
private long threadPoolMaxSize;
private List<WatchExecutionSnapshot> snapshots;
private List<QueuedWatch> queuedWatches;
private Map<String, Object> stats;
public Node(String nodeId, WatcherState watcherState, long watchesCount, long threadPoolQueueSize, long threadPoolMaxSize,
List<WatchExecutionSnapshot> snapshots, List<QueuedWatch> queuedWatches, Map<String, Object> stats) {
this.nodeId = nodeId;
this.watcherState = watcherState;
this.watchesCount = watchesCount;
this.threadPoolQueueSize = threadPoolQueueSize;
this.threadPoolMaxSize = threadPoolMaxSize;
this.snapshots = snapshots;
this.queuedWatches = queuedWatches;
this.stats = stats;
}
public String getNodeId() {
return nodeId;
}
public long getWatchesCount() {
return watchesCount;
}
public WatcherState getWatcherState() {
return watcherState;
}
public long getThreadPoolQueueSize() {
return threadPoolQueueSize;
}
public long getThreadPoolMaxSize() {
return threadPoolMaxSize;
}
public List<WatchExecutionSnapshot> getSnapshots() {
return snapshots;
}
public List<QueuedWatch> getQueuedWatches() {
return queuedWatches;
}
public Map<String, Object> getStats() {
return stats;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return watchesCount == node.watchesCount &&
threadPoolQueueSize == node.threadPoolQueueSize &&
threadPoolMaxSize == node.threadPoolMaxSize &&
Objects.equals(nodeId, node.nodeId) &&
watcherState == node.watcherState &&
Objects.equals(snapshots, node.snapshots) &&
Objects.equals(queuedWatches, node.queuedWatches) &&
Objects.equals(stats, node.stats);
}
@Override
public int hashCode() {
return Objects.hash(nodeId, watcherState, watchesCount, threadPoolQueueSize, threadPoolMaxSize, snapshots, queuedWatches,
stats);
}
}
}

View File

@ -1,24 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Request and Response objects for the default distribution's Watcher
* APIs.
*/
package org.elasticsearch.client.watcher;

View File

@ -1,234 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.watcher.AckWatchRequest;
import org.elasticsearch.client.watcher.AckWatchResponse;
import org.elasticsearch.client.watcher.ActionStatus;
import org.elasticsearch.client.watcher.ActionStatus.AckStatus;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.client.watcher.ActivateWatchResponse;
import org.elasticsearch.client.watcher.DeactivateWatchRequest;
import org.elasticsearch.client.watcher.DeactivateWatchResponse;
import org.elasticsearch.client.watcher.DeleteWatchRequest;
import org.elasticsearch.client.watcher.DeleteWatchResponse;
import org.elasticsearch.client.watcher.ExecuteWatchRequest;
import org.elasticsearch.client.watcher.ExecuteWatchResponse;
import org.elasticsearch.client.watcher.PutWatchRequest;
import org.elasticsearch.client.watcher.PutWatchResponse;
import org.elasticsearch.client.watcher.StartWatchServiceRequest;
import org.elasticsearch.client.watcher.StopWatchServiceRequest;
import org.elasticsearch.client.watcher.WatcherState;
import org.elasticsearch.client.watcher.WatcherStatsRequest;
import org.elasticsearch.client.watcher.WatcherStatsResponse;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ObjectPath;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import java.util.Map;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.not;
public class WatcherIT extends ESRestHighLevelClientTestCase {
public void testStartWatchService() throws Exception {
AcknowledgedResponse response =
highLevelClient().watcher().startWatchService(new StartWatchServiceRequest(), RequestOptions.DEFAULT);
assertTrue(response.isAcknowledged());
WatcherStatsResponse stats = highLevelClient().watcher().watcherStats(new WatcherStatsRequest(), RequestOptions.DEFAULT);
assertFalse(stats.getWatcherMetadata().manuallyStopped());
assertThat(stats.getNodes(), not(empty()));
for(WatcherStatsResponse.Node node : stats.getNodes()) {
assertEquals(WatcherState.STARTED, node.getWatcherState());
}
}
public void testStopWatchService() throws Exception {
AcknowledgedResponse response =
highLevelClient().watcher().stopWatchService(new StopWatchServiceRequest(), RequestOptions.DEFAULT);
assertTrue(response.isAcknowledged());
WatcherStatsResponse stats = highLevelClient().watcher().watcherStats(new WatcherStatsRequest(), RequestOptions.DEFAULT);
assertTrue(stats.getWatcherMetadata().manuallyStopped());
}
public void testPutWatch() throws Exception {
String watchId = randomAlphaOfLength(10);
PutWatchResponse putWatchResponse = createWatch(watchId);
assertThat(putWatchResponse.isCreated(), is(true));
assertThat(putWatchResponse.getId(), is(watchId));
assertThat(putWatchResponse.getVersion(), is(1L));
}
private static final String WATCH_JSON = "{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"none\": {} },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}";
private PutWatchResponse createWatch(String watchId) throws Exception {
BytesReference bytesReference = new BytesArray(WATCH_JSON);
PutWatchRequest putWatchRequest = new PutWatchRequest(watchId, bytesReference, XContentType.JSON);
return highLevelClient().watcher().putWatch(putWatchRequest, RequestOptions.DEFAULT);
}
public void testDeactivateWatch() throws Exception {
// Deactivate a watch that exists
String watchId = randomAlphaOfLength(10);
createWatch(watchId);
DeactivateWatchResponse response = highLevelClient().watcher().deactivateWatch(
new DeactivateWatchRequest(watchId), RequestOptions.DEFAULT);
assertThat(response.getStatus().state().isActive(), is(false));
}
public void testDeactivateWatch404() throws Exception {
// Deactivate a watch that does not exist
String watchId = randomAlphaOfLength(10);
ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class,
() -> highLevelClient().watcher().deactivateWatch(new DeactivateWatchRequest(watchId), RequestOptions.DEFAULT));
assertEquals(RestStatus.NOT_FOUND, exception.status());
}
public void testDeleteWatch() throws Exception {
// delete watch that exists
{
String watchId = randomAlphaOfLength(10);
createWatch(watchId);
DeleteWatchResponse deleteWatchResponse = highLevelClient().watcher().deleteWatch(new DeleteWatchRequest(watchId),
RequestOptions.DEFAULT);
assertThat(deleteWatchResponse.getId(), is(watchId));
assertThat(deleteWatchResponse.getVersion(), is(2L));
assertThat(deleteWatchResponse.isFound(), is(true));
}
// delete watch that does not exist
{
String watchId = randomAlphaOfLength(10);
DeleteWatchResponse deleteWatchResponse = highLevelClient().watcher().deleteWatch(new DeleteWatchRequest(watchId),
RequestOptions.DEFAULT);
assertThat(deleteWatchResponse.getId(), is(watchId));
assertThat(deleteWatchResponse.getVersion(), is(1L));
assertThat(deleteWatchResponse.isFound(), is(false));
}
}
public void testAckWatch() throws Exception {
String watchId = randomAlphaOfLength(10);
String actionId = "logme";
PutWatchResponse putWatchResponse = createWatch(watchId);
assertThat(putWatchResponse.isCreated(), is(true));
AckWatchResponse response = highLevelClient().watcher().ackWatch(
new AckWatchRequest(watchId, actionId), RequestOptions.DEFAULT);
ActionStatus actionStatus = response.getStatus().actionStatus(actionId);
assertEquals(AckStatus.State.AWAITS_SUCCESSFUL_EXECUTION, actionStatus.ackStatus().state());
// TODO: use the high-level REST client here once it supports 'execute watch'.
Request executeWatchRequest = new Request("POST", "_watcher/watch/" + watchId + "/_execute");
executeWatchRequest.setJsonEntity("{ \"record_execution\": true }");
Response executeResponse = client().performRequest(executeWatchRequest);
assertEquals(RestStatus.OK.getStatus(), executeResponse.getStatusLine().getStatusCode());
response = highLevelClient().watcher().ackWatch(
new AckWatchRequest(watchId, actionId), RequestOptions.DEFAULT);
actionStatus = response.getStatus().actionStatus(actionId);
assertEquals(AckStatus.State.ACKED, actionStatus.ackStatus().state());
ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class,
() -> highLevelClient().watcher().ackWatch(
new AckWatchRequest("nonexistent"), RequestOptions.DEFAULT));
assertEquals(RestStatus.NOT_FOUND, exception.status());
}
public void testActivateWatchThatExists() throws Exception {
String watchId = randomAlphaOfLength(10);
createWatch(watchId);
ActivateWatchResponse activateWatchResponse1 = highLevelClient().watcher().activateWatch(new ActivateWatchRequest(watchId),
RequestOptions.DEFAULT);
assertThat(activateWatchResponse1.getStatus().state().isActive(), is(true));
ActivateWatchResponse activateWatchResponse2 = highLevelClient().watcher().activateWatch(new ActivateWatchRequest(watchId),
RequestOptions.DEFAULT);
assertThat(activateWatchResponse2.getStatus().state().isActive(), is(true));
assertThat(activateWatchResponse1.getStatus().state().getTimestamp(),
lessThan(activateWatchResponse2.getStatus().state().getTimestamp()));
}
public void testActivateWatchThatDoesNotExist() throws Exception {
String watchId = randomAlphaOfLength(10);
// exception when activating a not existing watcher
ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () ->
highLevelClient().watcher().activateWatch(new ActivateWatchRequest(watchId), RequestOptions.DEFAULT));
assertEquals(RestStatus.NOT_FOUND, exception.status());
}
public void testExecuteWatchById() throws Exception {
String watchId = randomAlphaOfLength(10);
createWatch(watchId);
ExecuteWatchResponse response = highLevelClient().watcher()
.executeWatch(ExecuteWatchRequest.byId(watchId), RequestOptions.DEFAULT);
assertThat(response.getRecordId(), containsString(watchId));
Map<String, Object> source = response.getRecordAsMap();
assertThat(ObjectPath.eval("trigger_event.type", source), is("manual"));
}
public void testExecuteWatchThatDoesNotExist() throws Exception {
String watchId = randomAlphaOfLength(10);
// exception when activating a not existing watcher
ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () ->
highLevelClient().watcher().executeWatch(ExecuteWatchRequest.byId(watchId), RequestOptions.DEFAULT));
assertEquals(RestStatus.NOT_FOUND, exception.status());
}
public void testExecuteInlineWatch() throws Exception {
ExecuteWatchResponse response = highLevelClient().watcher()
.executeWatch(ExecuteWatchRequest.inline(WATCH_JSON), RequestOptions.DEFAULT);
assertThat(response.getRecordId(), containsString("_inlined_"));
Map<String, Object> source = response.getRecordAsMap();
assertThat(ObjectPath.eval("trigger_event.type", source), is("manual"));
}
public void testWatcherStatsMetrics() throws Exception {
boolean includeCurrent = randomBoolean();
boolean includeQueued = randomBoolean();
WatcherStatsRequest request = new WatcherStatsRequest(includeCurrent, includeQueued);
WatcherStatsResponse stats = highLevelClient().watcher().watcherStats(request, RequestOptions.DEFAULT);
assertThat(stats.getNodes(), not(empty()));
assertEquals(includeCurrent, stats.getNodes().get(0).getSnapshots() != null);
assertEquals(includeQueued, stats.getNodes().get(0).getQueuedWatches() != null);
}
}

View File

@ -1,328 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.watcher.AckWatchRequest;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.client.watcher.DeactivateWatchRequest;
import org.elasticsearch.client.watcher.DeleteWatchRequest;
import org.elasticsearch.client.watcher.ExecuteWatchRequest;
import org.elasticsearch.client.watcher.GetWatchRequest;
import org.elasticsearch.client.watcher.PutWatchRequest;
import org.elasticsearch.client.watcher.StartWatchServiceRequest;
import org.elasticsearch.client.watcher.StopWatchServiceRequest;
import org.elasticsearch.client.watcher.WatcherStatsRequest;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
public class WatcherRequestConvertersTests extends ESTestCase {
private static String toString(HttpEntity entity) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
return baos.toString(StandardCharsets.UTF_8.name());
}
public void testStartWatchService() {
Request request = WatcherRequestConverters.startWatchService(new StartWatchServiceRequest());
assertEquals(HttpPost.METHOD_NAME, request.getMethod());
assertEquals("/_watcher/_start", request.getEndpoint());
}
public void testStopWatchService() {
Request request = WatcherRequestConverters.stopWatchService(new StopWatchServiceRequest());
assertEquals(HttpPost.METHOD_NAME, request.getMethod());
assertEquals("/_watcher/_stop", request.getEndpoint());
}
public void testPutWatch() throws Exception {
String watchId = randomAlphaOfLength(10);
String body = randomAlphaOfLength(20);
PutWatchRequest putWatchRequest = new PutWatchRequest(watchId, new BytesArray(body), XContentType.JSON);
Map<String, String> expectedParams = new HashMap<>();
if (randomBoolean()) {
putWatchRequest.setActive(false);
expectedParams.put("active", "false");
}
if (randomBoolean()) {
long seqNo = randomNonNegativeLong();
long ifPrimaryTerm = randomLongBetween(1, 200);
putWatchRequest.setIfSeqNo(seqNo);
putWatchRequest.setIfPrimaryTerm(ifPrimaryTerm);
expectedParams.put("if_seq_no", String.valueOf(seqNo));
expectedParams.put("if_primary_term", String.valueOf(ifPrimaryTerm));
}
Request request = WatcherRequestConverters.putWatch(putWatchRequest);
assertEquals(HttpPut.METHOD_NAME, request.getMethod());
assertEquals("/_watcher/watch/" + watchId, request.getEndpoint());
assertEquals(expectedParams, request.getParameters());
assertThat(request.getEntity().getContentType().getValue(), is(XContentType.JSON.mediaTypeWithoutParameters()));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
request.getEntity().writeTo(bos);
assertThat(bos.toString("UTF-8"), is(body));
}
public void testGetWatch() throws Exception {
String watchId = randomAlphaOfLength(10);
GetWatchRequest getWatchRequest = new GetWatchRequest(watchId);
Request request = WatcherRequestConverters.getWatch(getWatchRequest);
assertEquals(HttpGet.METHOD_NAME, request.getMethod());
assertEquals("/_watcher/watch/" + watchId, request.getEndpoint());
assertThat(request.getEntity(), nullValue());
}
public void testDeactivateWatch() {
String watchId = randomAlphaOfLength(10);
DeactivateWatchRequest deactivateWatchRequest = new DeactivateWatchRequest(watchId);
Request request = WatcherRequestConverters.deactivateWatch(deactivateWatchRequest);
assertEquals(HttpPut.METHOD_NAME, request.getMethod());
assertEquals("/_watcher/watch/" + watchId + "/_deactivate", request.getEndpoint());
}
public void testDeleteWatch() {
String watchId = randomAlphaOfLength(10);
DeleteWatchRequest deleteWatchRequest = new DeleteWatchRequest(watchId);
Request request = WatcherRequestConverters.deleteWatch(deleteWatchRequest);
assertEquals(HttpDelete.METHOD_NAME, request.getMethod());
assertEquals("/_watcher/watch/" + watchId, request.getEndpoint());
assertThat(request.getEntity(), nullValue());
}
public void testAckWatch() {
String watchId = randomAlphaOfLength(10);
String[] actionIds = generateRandomStringArray(5, 10, false, true);
AckWatchRequest ackWatchRequest = new AckWatchRequest(watchId, actionIds);
Request request = WatcherRequestConverters.ackWatch(ackWatchRequest);
assertEquals(HttpPut.METHOD_NAME, request.getMethod());
StringJoiner expectedEndpoint = new StringJoiner("/", "/", "")
.add("_watcher").add("watch").add(watchId).add("_ack");
if (ackWatchRequest.getActionIds().length > 0) {
String actionsParam = String.join(",", ackWatchRequest.getActionIds());
expectedEndpoint.add(actionsParam);
}
assertEquals(expectedEndpoint.toString(), request.getEndpoint());
assertThat(request.getEntity(), nullValue());
}
public void testActivateWatchRequestConversion() {
String watchId = randomAlphaOfLength(10);
ActivateWatchRequest activateWatchRequest = new ActivateWatchRequest(watchId);
Request request = WatcherRequestConverters.activateWatch(activateWatchRequest);
assertEquals(HttpPut.METHOD_NAME, request.getMethod());
assertEquals("/_watcher/watch/" + watchId + "/_activate", request.getEndpoint());
assertThat(request.getEntity(), nullValue());
}
public void testWatcherStatsRequest() {
boolean includeCurrent = randomBoolean();
boolean includeQueued = randomBoolean();
WatcherStatsRequest watcherStatsRequest = new WatcherStatsRequest(includeCurrent, includeQueued);
Request request = WatcherRequestConverters.watcherStats(watcherStatsRequest);
assertThat(request.getEndpoint(), equalTo("/_watcher/stats"));
assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME));
if (includeCurrent || includeQueued) {
assertThat(request.getParameters(), hasKey("metric"));
Set<String> metric = Strings.tokenizeByCommaToSet(request.getParameters().get("metric"));
assertThat(metric, hasSize((includeCurrent?1:0) + (includeQueued?1:0)));
Set<String> expectedMetric = new HashSet<>();
if (includeCurrent) {
expectedMetric.add("current_watches");
}
if (includeQueued) {
expectedMetric.add("queued_watches");
}
assertThat(metric, equalTo(expectedMetric));
} else {
assertThat(request.getParameters(), not(hasKey("metric")));
}
assertThat(request.getEntity(), nullValue());
}
public void testExecuteWatchByIdRequest() throws IOException {
boolean ignoreCondition = randomBoolean();
boolean recordExecution = randomBoolean();
boolean debug = randomBoolean();
ExecuteWatchRequest request = ExecuteWatchRequest.byId("my_id");
request.setIgnoreCondition(ignoreCondition);
request.setRecordExecution(recordExecution);
request.setDebug(debug);
boolean setActionMode = randomBoolean();
if (setActionMode) {
request.setActionMode("action1", ExecuteWatchRequest.ActionExecutionMode.SIMULATE);
}
boolean useTriggerData = randomBoolean();
String triggerData = "{ \"entry1\" : \"blah\", \"entry2\" : \"blah\" }";
if (useTriggerData) {
request.setTriggerData(triggerData);
}
boolean useAlternativeInput = randomBoolean();
String alternativeInput = "{ \"foo\" : \"bar\" }";
if (useAlternativeInput) {
request.setAlternativeInput(alternativeInput);
}
Request req = WatcherRequestConverters.executeWatch(request);
assertThat(req.getEndpoint(), equalTo("/_watcher/watch/my_id/_execute"));
assertThat(req.getMethod(), equalTo(HttpPost.METHOD_NAME));
if (ignoreCondition) {
assertThat(req.getParameters(), hasKey("ignore_condition"));
assertThat(req.getParameters().get("ignore_condition"), is("true"));
}
if (recordExecution) {
assertThat(req.getParameters(), hasKey("record_execution"));
assertThat(req.getParameters().get("record_execution"), is("true"));
}
if (debug) {
assertThat(req.getParameters(), hasKey("debug"));
assertThat(req.getParameters().get("debug"), is("true"));
}
String body = toString(req.getEntity());
if (setActionMode) {
assertThat(body, containsString("\"action_modes\":{\"action1\":\"SIMULATE\"}"));
}
else {
assertThat(body, not(containsString("action_modes")));
}
if (useTriggerData) {
assertThat(body, containsString("\"trigger_data\":" + triggerData));
}
else {
assertThat(body, not(containsString("trigger_data")));
}
if (useAlternativeInput) {
assertThat(body, containsString("\"alternative_input\":" + alternativeInput));
}
else {
assertThat(body, not(containsString("alternative_input")));
}
assertThat(body, not(containsString("\"watch\":")));
}
private static final String WATCH_JSON = "{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"none\": {} },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}";
public void testExecuteInlineWatchRequest() throws IOException {
boolean ignoreCondition = randomBoolean();
ExecuteWatchRequest request = ExecuteWatchRequest.inline(WATCH_JSON);
request.setIgnoreCondition(ignoreCondition);
expectThrows(IllegalArgumentException.class, () -> {
request.setRecordExecution(true);
});
boolean setActionMode = randomBoolean();
if (setActionMode) {
request.setActionMode("action1", ExecuteWatchRequest.ActionExecutionMode.SIMULATE);
}
boolean useTriggerData = randomBoolean();
String triggerData = "{ \"entry1\" : \"blah\", \"entry2\" : \"blah\" }";
if (useTriggerData) {
request.setTriggerData(triggerData);
}
boolean useAlternativeInput = randomBoolean();
String alternativeInput = "{ \"foo\" : \"bar\" }";
if (useAlternativeInput) {
request.setAlternativeInput(alternativeInput);
}
Request req = WatcherRequestConverters.executeWatch(request);
assertThat(req.getEndpoint(), equalTo("/_watcher/watch/_execute"));
assertThat(req.getMethod(), equalTo(HttpPost.METHOD_NAME));
if (ignoreCondition) {
assertThat(req.getParameters(), hasKey("ignore_condition"));
assertThat(req.getParameters().get("ignore_condition"), is("true"));
}
String body = toString(req.getEntity());
if (setActionMode) {
assertThat(body, containsString("\"action_modes\":{\"action1\":\"SIMULATE\"}"));
}
else {
assertThat(body, not(containsString("action_modes")));
}
if (useTriggerData) {
assertThat(body, containsString("\"trigger_data\":" + triggerData));
}
else {
assertThat(body, not(containsString("trigger_data")));
}
if (useAlternativeInput) {
assertThat(body, containsString("\"alternative_input\":" + alternativeInput));
}
else {
assertThat(body, not(containsString("alternative_input")));
}
assertThat(body, containsString("\"watch\":" + WATCH_JSON));
}
}

View File

@ -1,615 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.documentation;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.LatchedActionListener;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.ESRestHighLevelClientTestCase;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.client.watcher.ActivateWatchResponse;
import org.elasticsearch.client.watcher.AckWatchRequest;
import org.elasticsearch.client.watcher.AckWatchResponse;
import org.elasticsearch.client.watcher.ActionStatus;
import org.elasticsearch.client.watcher.ActionStatus.AckStatus;
import org.elasticsearch.client.watcher.DeactivateWatchRequest;
import org.elasticsearch.client.watcher.DeactivateWatchResponse;
import org.elasticsearch.client.watcher.ExecuteWatchRequest;
import org.elasticsearch.client.watcher.ExecuteWatchResponse;
import org.elasticsearch.client.watcher.GetWatchRequest;
import org.elasticsearch.client.watcher.GetWatchResponse;
import org.elasticsearch.client.watcher.StartWatchServiceRequest;
import org.elasticsearch.client.watcher.StopWatchServiceRequest;
import org.elasticsearch.client.watcher.WatchStatus;
import org.elasticsearch.client.watcher.WatcherStatsRequest;
import org.elasticsearch.client.watcher.WatcherStatsResponse;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ObjectPath;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.client.watcher.DeleteWatchRequest;
import org.elasticsearch.client.watcher.DeleteWatchResponse;
import org.elasticsearch.client.watcher.PutWatchRequest;
import org.elasticsearch.client.watcher.PutWatchResponse;
import org.elasticsearch.rest.RestStatus;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.is;
public class WatcherDocumentationIT extends ESRestHighLevelClientTestCase {
public void testStartStopWatchService() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::start-watch-service-request
StartWatchServiceRequest request = new StartWatchServiceRequest();
//end::start-watch-service-request
//tag::start-watch-service-execute
AcknowledgedResponse response = client.watcher().startWatchService(request, RequestOptions.DEFAULT);
//end::start-watch-service-execute
//tag::start-watch-service-response
boolean isAcknowledged = response.isAcknowledged(); // <1>
//end::start-watch-service-response
}
{
//tag::stop-watch-service-request
StopWatchServiceRequest request = new StopWatchServiceRequest();
//end::stop-watch-service-request
//tag::stop-watch-service-execute
AcknowledgedResponse response = client.watcher().stopWatchService(request, RequestOptions.DEFAULT);
//end::stop-watch-service-execute
//tag::stop-watch-service-response
boolean isAcknowledged = response.isAcknowledged(); // <1>
//end::stop-watch-service-response
}
{
StartWatchServiceRequest request = new StartWatchServiceRequest();
// tag::start-watch-service-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::start-watch-service-execute-listener
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::start-watch-service-execute-async
client.watcher().startWatchServiceAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::start-watch-service-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
{
StopWatchServiceRequest request = new StopWatchServiceRequest();
// tag::stop-watch-service-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::stop-watch-service-execute-listener
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::stop-watch-service-execute-async
client.watcher().stopWatchServiceAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::stop-watch-service-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testWatcher() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::x-pack-put-watch-execute
// you can also use the WatchSourceBuilder from org.elasticsearch.plugin:x-pack-core to create a watch programmatically
BytesReference watch = new BytesArray("{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"simple\": { \"foo\" : \"bar\" } },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}");
PutWatchRequest request = new PutWatchRequest("my_watch_id", watch, XContentType.JSON);
request.setActive(false); // <1>
PutWatchResponse response = client.watcher().putWatch(request, RequestOptions.DEFAULT);
//end::x-pack-put-watch-execute
//tag::x-pack-put-watch-response
String watchId = response.getId(); // <1>
boolean isCreated = response.isCreated(); // <2>
long version = response.getVersion(); // <3>
//end::x-pack-put-watch-response
}
{
BytesReference watch = new BytesArray("{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"simple\": { \"foo\" : \"bar\" } },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}");
PutWatchRequest request = new PutWatchRequest("my_other_watch_id", watch, XContentType.JSON);
// tag::x-pack-put-watch-execute-listener
ActionListener<PutWatchResponse> listener = new ActionListener<PutWatchResponse>() {
@Override
public void onResponse(PutWatchResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::x-pack-put-watch-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::x-pack-put-watch-execute-async
client.watcher().putWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::x-pack-put-watch-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
{
// tag::x-pack-execute-watch-by-id
ExecuteWatchRequest request = ExecuteWatchRequest.byId("my_watch_id");
request.setAlternativeInput("{ \"foo\" : \"bar\" }"); // <1>
request.setActionMode("action1", ExecuteWatchRequest.ActionExecutionMode.SIMULATE); // <2>
request.setRecordExecution(true); // <3>
request.setIgnoreCondition(true); // <4>
request.setTriggerData("{\"triggered_time\":\"now\"}"); // <5>
request.setDebug(true); // <6>
ExecuteWatchResponse response = client.watcher().executeWatch(request, RequestOptions.DEFAULT);
// end::x-pack-execute-watch-by-id
// tag::x-pack-execute-watch-by-id-response
String id = response.getRecordId(); // <1>
Map<String, Object> watch = response.getRecordAsMap(); // <2>
String watch_id = ObjectPath.eval("watch_record.watch_id", watch); // <3>
// end::x-pack-execute-watch-by-id-response
}
{
ExecuteWatchRequest request = ExecuteWatchRequest.byId("my_watch_id");
// tag::x-pack-execute-watch-by-id-execute-listener
ActionListener<ExecuteWatchResponse> listener = new ActionListener<ExecuteWatchResponse>() {
@Override
public void onResponse(ExecuteWatchResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::x-pack-execute-watch-by-id-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::x-pack-execute-watch-by-id-execute-async
client.watcher().executeWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::x-pack-execute-watch-by-id-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
{
//tag::get-watch-request
GetWatchRequest request = new GetWatchRequest("my_watch_id");
//end::get-watch-request
//tag::get-watch-execute
GetWatchResponse response = client.watcher().getWatch(request, RequestOptions.DEFAULT);
//end::get-watch-execute
//tag::get-watch-response
String watchId = response.getId(); // <1>
boolean found = response.isFound(); // <2>
long version = response.getVersion(); // <3>
WatchStatus status = response.getStatus(); // <4>
BytesReference source = response.getSource(); // <5>
//end::get-watch-response
}
{
GetWatchRequest request = new GetWatchRequest("my_other_watch_id");
// tag::get-watch-execute-listener
ActionListener<GetWatchResponse> listener = new ActionListener<GetWatchResponse>() {
@Override
public void onResponse(GetWatchResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-watch-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-watch-execute-async
client.watcher().getWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-watch-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
{
//tag::x-pack-delete-watch-execute
DeleteWatchRequest request = new DeleteWatchRequest("my_watch_id");
DeleteWatchResponse response = client.watcher().deleteWatch(request, RequestOptions.DEFAULT);
//end::x-pack-delete-watch-execute
//tag::x-pack-delete-watch-response
String watchId = response.getId(); // <1>
boolean found = response.isFound(); // <2>
long version = response.getVersion(); // <3>
//end::x-pack-delete-watch-response
}
{
DeleteWatchRequest request = new DeleteWatchRequest("my_other_watch_id");
// tag::x-pack-delete-watch-execute-listener
ActionListener<DeleteWatchResponse> listener = new ActionListener<DeleteWatchResponse>() {
@Override
public void onResponse(DeleteWatchResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::x-pack-delete-watch-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::x-pack-delete-watch-execute-async
client.watcher().deleteWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::x-pack-delete-watch-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testExecuteInlineWatch() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::x-pack-execute-watch-inline
String watchJson = "{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"none\": {} },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}";
ExecuteWatchRequest request = ExecuteWatchRequest.inline(watchJson);
request.setAlternativeInput("{ \"foo\" : \"bar\" }"); // <1>
request.setActionMode("action1", ExecuteWatchRequest.ActionExecutionMode.SIMULATE); // <2>
request.setIgnoreCondition(true); // <3>
request.setTriggerData("{\"triggered_time\":\"now\"}"); // <4>
request.setDebug(true); // <5>
ExecuteWatchResponse response = client.watcher().executeWatch(request, RequestOptions.DEFAULT);
// end::x-pack-execute-watch-inline
// tag::x-pack-execute-watch-inline-response
String id = response.getRecordId(); // <1>
Map<String, Object> watch = response.getRecordAsMap(); // <2>
String watch_id = ObjectPath.eval("watch_record.watch_id", watch); // <3>
// end::x-pack-execute-watch-inline-response
}
{
String watchJson = "{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"none\": {} },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}";
ExecuteWatchRequest request = ExecuteWatchRequest.inline(watchJson);
// tag::x-pack-execute-watch-inline-execute-listener
ActionListener<ExecuteWatchResponse> listener = new ActionListener<ExecuteWatchResponse>() {
@Override
public void onResponse(ExecuteWatchResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::x-pack-execute-watch-inline-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::x-pack-execute-watch-inline-execute-async
client.watcher().executeWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::x-pack-execute-watch-inline-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testAckWatch() throws Exception {
RestHighLevelClient client = highLevelClient();
{
BytesReference watch = new BytesArray("{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"simple\": { \"foo\" : \"bar\" } },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}");
PutWatchRequest putWatchRequest = new PutWatchRequest("my_watch_id", watch, XContentType.JSON);
client.watcher().putWatch(putWatchRequest, RequestOptions.DEFAULT);
// TODO: use the high-level REST client here once it supports 'execute watch'.
Request executeWatchRequest = new Request("POST", "_watcher/watch/my_watch_id/_execute");
executeWatchRequest.setJsonEntity("{ \"record_execution\": true }");
Response executeResponse = client().performRequest(executeWatchRequest);
assertEquals(RestStatus.OK.getStatus(), executeResponse.getStatusLine().getStatusCode());
}
{
//tag::ack-watch-request
AckWatchRequest request = new AckWatchRequest("my_watch_id", // <1>
"logme", "emailme"); // <2>
//end::ack-watch-request
//tag::ack-watch-execute
AckWatchResponse response = client.watcher().ackWatch(request, RequestOptions.DEFAULT);
//end::ack-watch-execute
//tag::ack-watch-response
WatchStatus watchStatus = response.getStatus();
ActionStatus actionStatus = watchStatus.actionStatus("logme"); // <1>
AckStatus.State ackState = actionStatus.ackStatus().state(); // <2>
//end::ack-watch-response
assertEquals(AckStatus.State.ACKED, ackState);
}
{
AckWatchRequest request = new AckWatchRequest("my_watch_id");
// tag::ack-watch-execute-listener
ActionListener<AckWatchResponse> listener = new ActionListener<AckWatchResponse>() {
@Override
public void onResponse(AckWatchResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::ack-watch-execute-listener
// For testing, replace the empty listener by a blocking listener.
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::ack-watch-execute-async
client.watcher().ackWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::ack-watch-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeactivateWatch() throws Exception {
RestHighLevelClient client = highLevelClient();
{
BytesReference watch = new BytesArray("{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"simple\": { \"foo\" : \"bar\" } },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}");
PutWatchRequest putWatchRequest = new PutWatchRequest("my_watch_id", watch, XContentType.JSON);
client.watcher().putWatch(putWatchRequest, RequestOptions.DEFAULT);
}
{
//tag::deactivate-watch-execute
DeactivateWatchRequest request = new DeactivateWatchRequest("my_watch_id");
DeactivateWatchResponse response = client.watcher().deactivateWatch(request, RequestOptions.DEFAULT);
//end::deactivate-watch-execute
assertThat(response.getStatus().state().isActive(), is(false));
}
{
DeactivateWatchRequest request = new DeactivateWatchRequest("my_watch_id");
// tag::deactivate-watch-execute-listener
ActionListener<DeactivateWatchResponse> listener = new ActionListener<DeactivateWatchResponse>() {
@Override
public void onResponse(DeactivateWatchResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::deactivate-watch-execute-listener
// For testing, replace the empty listener by a blocking listener.
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::deactivate-watch-execute-async
client.watcher().deactivateWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::deactivate-watch-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testActivateWatch() throws Exception {
RestHighLevelClient client = highLevelClient();
{
BytesReference watch = new BytesArray("{ \n" +
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
" \"input\": { \"simple\": { \"foo\" : \"bar\" } },\n" +
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
"}");
PutWatchRequest request = new PutWatchRequest("my_watch_id", watch, XContentType.JSON);
request.setActive(false); // <1>
PutWatchResponse response = client.watcher().putWatch(request, RequestOptions.DEFAULT);
}
{
//tag::activate-watch-request
ActivateWatchRequest request = new ActivateWatchRequest("my_watch_id");
ActivateWatchResponse response = client.watcher().activateWatch(request, RequestOptions.DEFAULT);
//end::activate-watch-request
//tag::activate-watch-response
WatchStatus watchStatus = response.getStatus(); // <1>
//end::activate-watch-response
assertTrue(watchStatus.state().isActive());
}
{
ActivateWatchRequest request = new ActivateWatchRequest("my_watch_id");
//tag::activate-watch-request-listener
ActionListener<ActivateWatchResponse> listener = new ActionListener<ActivateWatchResponse>() {
@Override
public void onResponse(ActivateWatchResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::activate-watch-request-listener
//Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::activate-watch-request-async
client.watcher().activateWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
//end::activate-watch-request-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testWatcherStats() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::watcher-stats-request
WatcherStatsRequest request = new WatcherStatsRequest(true, true);
//end::watcher-stats-request
//tag::watcher-stats-execute
WatcherStatsResponse response = client.watcher().watcherStats(request, RequestOptions.DEFAULT);
//end::watcher-stats-execute
//tag::watcher-stats-response
List<WatcherStatsResponse.Node> nodes = response.getNodes(); // <1>
//end::watcher-stats-response
}
{
WatcherStatsRequest request = new WatcherStatsRequest();
// tag::watcher-stats-execute-listener
ActionListener<WatcherStatsResponse> listener = new ActionListener<WatcherStatsResponse>() {
@Override
public void onResponse(WatcherStatsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::watcher-stats-execute-listener
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::watcher-stats-execute-async
client.watcher().watcherStatsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::watcher-stats-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
}

View File

@ -28,7 +28,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.test.AbstractXContentTestCase; import org.elasticsearch.test.AbstractXContentTestCase;
import org.elasticsearch.xpack.core.watcher.watch.Payload.XContent;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
@ -104,7 +103,7 @@ public class SettingsConfigTests extends AbstractXContentTestCase<SettingsConfig
private Map<String, Object> xContentToMap(ToXContent xcontent) throws IOException { private Map<String, Object> xContentToMap(ToXContent xcontent) throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder(); XContentBuilder builder = XContentFactory.jsonBuilder();
xcontent.toXContent(builder, XContent.EMPTY_PARAMS); xcontent.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentParser parser = XContentType.JSON.xContent() XContentParser parser = XContentType.JSON.xContent()
.createParser(xContentRegistry(), LoggingDeprecationHandler.INSTANCE, BytesReference.bytes(builder).streamInput()); .createParser(xContentRegistry(), LoggingDeprecationHandler.INSTANCE, BytesReference.bytes(builder).streamInput());
return parser.map(); return parser.map();

View File

@ -1,105 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParseException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.XContentTestUtils;
import java.io.IOException;
import java.util.function.Predicate;
/**
* Basic unit tests for {@link AckWatchResponse}.
*
* Note that we only sanity check watch status parsing here, as there
* are dedicated tests for it in {@link WatchStatusTests}.
*/
public class AckWatchResponseTests extends ESTestCase {
public void testBasicParsing() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject()
.startObject("status")
.field("version", 42)
.field("execution_state", ExecutionState.ACKNOWLEDGED)
.endObject()
.endObject();
BytesReference bytes = BytesReference.bytes(builder);
AckWatchResponse response = parse(builder.contentType(), bytes);
WatchStatus status = response.getStatus();
assertNotNull(status);
assertEquals(42, status.version());
assertEquals(ExecutionState.ACKNOWLEDGED, status.getExecutionState());
}
public void testParsingWithMissingStatus() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject().endObject();
BytesReference bytes = BytesReference.bytes(builder);
expectThrows(IllegalArgumentException.class, () -> parse(builder.contentType(), bytes));
}
public void testParsingWithNullStatus() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject()
.nullField("status")
.endObject();
BytesReference bytes = BytesReference.bytes(builder);
expectThrows(XContentParseException.class, () -> parse(builder.contentType(), bytes));
}
public void testParsingWithUnknownKeys() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject()
.startObject("status")
.field("version", 42)
.field("execution_state", ExecutionState.ACKNOWLEDGED)
.endObject()
.endObject();
BytesReference bytes = BytesReference.bytes(builder);
Predicate<String> excludeFilter = field -> field.equals("status.actions");
BytesReference bytesWithRandomFields = XContentTestUtils.insertRandomFields(
builder.contentType(), bytes, excludeFilter, random());
AckWatchResponse response = parse(builder.contentType(), bytesWithRandomFields);
WatchStatus status = response.getStatus();
assertNotNull(status);
assertEquals(42, status.version());
assertEquals(ExecutionState.ACKNOWLEDGED, status.getExecutionState());
}
private AckWatchResponse parse(XContentType contentType, BytesReference bytes) throws IOException {
XContentParser parser = XContentFactory.xContent(contentType)
.createParser(NamedXContentRegistry.EMPTY, null, bytes.streamInput());
parser.nextToken();
return AckWatchResponse.fromXContent(parser);
}
}

View File

@ -1,113 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParseException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.XContentTestUtils;
import java.io.IOException;
import java.util.function.Predicate;
/**
* Basic unit tests for {@link ActivateWatchResponse}.
*
* Note that we only sanity check watch status parsing here, as there
* are dedicated tests for it in {@link WatchStatusTests}.
*/
public class ActivateWatchResponseTests extends ESTestCase {
public void testBasicParsing() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject()
.startObject("status")
.field("version", 42)
.field("execution_state", ExecutionState.ACKNOWLEDGED)
.startObject("state")
.field("active", false)
.endObject()
.endObject()
.endObject();
BytesReference bytes = BytesReference.bytes(builder);
ActivateWatchResponse response = parse(builder.contentType(), bytes);
WatchStatus status = response.getStatus();
assertNotNull(status);
assertEquals(42, status.version());
assertEquals(ExecutionState.ACKNOWLEDGED, status.getExecutionState());
assertFalse(status.state().isActive());
}
public void testParsingWithMissingStatus() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject().endObject();
BytesReference bytes = BytesReference.bytes(builder);
expectThrows(IllegalArgumentException.class, () -> parse(builder.contentType(), bytes));
}
public void testParsingWithNullStatus() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject()
.nullField("status")
.endObject();
BytesReference bytes = BytesReference.bytes(builder);
expectThrows(XContentParseException.class, () -> parse(builder.contentType(), bytes));
}
public void testParsingWithUnknownKeys() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject()
.startObject("status")
.field("version", 42)
.field("execution_state", ExecutionState.ACKNOWLEDGED)
.startObject("state")
.field("active", true)
.endObject()
.endObject()
.endObject();
BytesReference bytes = BytesReference.bytes(builder);
Predicate<String> excludeFilter = field -> field.equals("status.actions");
BytesReference bytesWithRandomFields = XContentTestUtils.insertRandomFields(
builder.contentType(), bytes, excludeFilter, random());
ActivateWatchResponse response = parse(builder.contentType(), bytesWithRandomFields);
WatchStatus status = response.getStatus();
assertNotNull(status);
assertEquals(42, status.version());
assertEquals(ExecutionState.ACKNOWLEDGED, status.getExecutionState());
assertTrue(status.state().isActive());
}
private ActivateWatchResponse parse(XContentType contentType, BytesReference bytes) throws IOException {
XContentParser parser = XContentFactory.xContent(contentType)
.createParser(NamedXContentRegistry.EMPTY, null, bytes.streamInput());
parser.nextToken();
return ActivateWatchResponse.fromXContent(parser);
}
}

View File

@ -1,41 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.test.ESTestCase;
import static org.hamcrest.Matchers.is;
public class DeactivateWatchRequestTests extends ESTestCase {
public void testNullId() {
NullPointerException actual = expectThrows(NullPointerException.class, () -> new DeactivateWatchRequest(null));
assertNotNull(actual);
assertThat(actual.getMessage(), is("watch id is missing"));
}
public void testInvalidId() {
IllegalArgumentException actual = expectThrows(IllegalArgumentException.class,
() -> new DeactivateWatchRequest("Watch id has spaces"));
assertNotNull(actual);
assertThat(actual.getMessage(), is("watch id contains whitespace"));
}
}

View File

@ -1,58 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
public class DeactivateWatchResponseTests extends ESTestCase {
public void testBasicParsing() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
int version = randomInt();
ExecutionState executionState = randomFrom(ExecutionState.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject()
.startObject("status")
.field("version", version)
.field("execution_state", executionState)
.endObject()
.endObject();
BytesReference bytes = BytesReference.bytes(builder);
DeactivateWatchResponse response = parse(contentType, bytes);
WatchStatus status = response.getStatus();
assertNotNull(status);
assertEquals(version, status.version());
assertEquals(executionState, status.getExecutionState());
}
private DeactivateWatchResponse parse(XContentType contentType, BytesReference bytes) throws IOException {
XContentParser parser = XContentFactory.xContent(contentType)
.createParser(NamedXContentRegistry.EMPTY, null, bytes.streamInput());
parser.nextToken();
return DeactivateWatchResponse.fromXContent(parser);
}
}

View File

@ -1,54 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;
public class DeleteWatchResponseTests extends ESTestCase {
public void testFromXContent() throws IOException {
xContentTester(this::createParser,
DeleteWatchResponseTests::createTestInstance,
DeleteWatchResponseTests::toXContent,
DeleteWatchResponse::fromXContent)
.supportsUnknownFields(true)
.assertToXContentEquivalence(false)
.test();
}
private static XContentBuilder toXContent(DeleteWatchResponse response, XContentBuilder builder) throws IOException {
return builder.startObject()
.field("_id", response.getId())
.field("_version", response.getVersion())
.field("found", response.isFound())
.endObject();
}
private static DeleteWatchResponse createTestInstance() {
String id = randomAlphaOfLength(10);
long version = randomLongBetween(1, 10);
boolean found = randomBoolean();
return new DeleteWatchResponse(id, version, found);
}
}

View File

@ -1,209 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.client.AbstractResponseTestCase;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xpack.core.watcher.actions.ActionStatus;
import org.elasticsearch.xpack.core.watcher.execution.ExecutionState;
import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.core.watcher.transport.actions.get.GetWatchResponse;
import org.elasticsearch.xpack.core.watcher.watch.WatchStatus;
import java.io.IOException;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class GetWatchResponseTests extends AbstractResponseTestCase<GetWatchResponse, org.elasticsearch.client.watcher.GetWatchResponse> {
@Override
protected GetWatchResponse createServerTestInstance(XContentType xContentType) {
String id = randomAlphaOfLength(10);
if (LuceneTestCase.rarely()) {
return new GetWatchResponse(id);
}
long version = randomLongBetween(0, 10);
long seqNo = randomNonNegativeLong();
long primaryTerm = randomLongBetween(1, 2000);
WatchStatus status = randomWatchStatus();
BytesReference source = simpleWatch();
return new GetWatchResponse(id, version, seqNo, primaryTerm, status, new XContentSource(source, XContentType.JSON));
}
@Override
protected org.elasticsearch.client.watcher.GetWatchResponse doParseToClientInstance(XContentParser parser) throws IOException {
return org.elasticsearch.client.watcher.GetWatchResponse.fromXContent(parser);
}
@Override
protected void assertInstances(GetWatchResponse serverTestInstance, org.elasticsearch.client.watcher.GetWatchResponse clientInstance) {
assertThat(clientInstance.getId(), equalTo(serverTestInstance.getId()));
assertThat(clientInstance.getSeqNo(), equalTo(serverTestInstance.getSeqNo()));
assertThat(clientInstance.getPrimaryTerm(), equalTo(serverTestInstance.getPrimaryTerm()));
assertThat(clientInstance.getVersion(), equalTo(serverTestInstance.getVersion()));
if (serverTestInstance.getStatus() != null) {
assertThat(convertWatchStatus(clientInstance.getStatus()), equalTo(serverTestInstance.getStatus()));
} else {
assertThat(clientInstance.getStatus(), nullValue());
}
if (serverTestInstance.getSource() != null) {
assertThat(clientInstance.getSourceAsMap(), equalTo(serverTestInstance.getSource().getAsMap()));
} else {
assertThat(clientInstance.getSource(), nullValue());
}
}
@Override
protected ToXContent.Params getParams() {
return new ToXContent.MapParams(Collections.singletonMap("hide_headers", "false"));
}
private static BytesReference simpleWatch() {
try {
XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent());
builder.startObject()
.startObject("trigger")
.startObject("schedule")
.field("interval", "10h")
.endObject()
.endObject()
.startObject("input")
.startObject("none").endObject()
.endObject()
.startObject("actions")
.startObject("logme")
.field("text", "{{ctx.payload}}")
.endObject()
.endObject().endObject();
return BytesReference.bytes(builder);
} catch (IOException e) {
throw new AssertionError(e);
}
}
private static WatchStatus randomWatchStatus() {
long version = randomLongBetween(-1, Long.MAX_VALUE);
WatchStatus.State state = new WatchStatus.State(randomBoolean(), nowWithMillisResolution());
ExecutionState executionState = randomFrom(ExecutionState.values());
ZonedDateTime lastChecked = LuceneTestCase.rarely() ? null : nowWithMillisResolution();
ZonedDateTime lastMetCondition = LuceneTestCase.rarely() ? null : nowWithMillisResolution();
int size = randomIntBetween(0, 5);
Map<String, ActionStatus> actionMap = new HashMap<>();
for (int i = 0; i < size; i++) {
ActionStatus.AckStatus ack = new ActionStatus.AckStatus(
nowWithMillisResolution(),
randomFrom(ActionStatus.AckStatus.State.values())
);
ActionStatus actionStatus = new ActionStatus(
ack,
randomBoolean() ? null : randomExecution(),
randomBoolean() ? null : randomExecution(),
randomBoolean() ? null : randomThrottle()
);
actionMap.put(randomAlphaOfLength(10), actionStatus);
}
Map<String, String> headers = new HashMap<>();
int headerSize = randomIntBetween(0, 5);
for (int i = 0; i < headerSize; i++) {
headers.put(randomAlphaOfLengthBetween(5, 10), randomAlphaOfLengthBetween(1, 10));
}
return new WatchStatus(version, state, executionState, lastChecked, lastMetCondition, actionMap, headers);
}
private static ActionStatus.Throttle randomThrottle() {
return new ActionStatus.Throttle(nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
}
private static ActionStatus.Execution randomExecution() {
if (randomBoolean()) {
return null;
} else if (randomBoolean()) {
return ActionStatus.Execution.failure(nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
} else {
return ActionStatus.Execution.successful(nowWithMillisResolution());
}
}
private static WatchStatus convertWatchStatus(org.elasticsearch.client.watcher.WatchStatus status) {
final Map<String, ActionStatus> actions = new HashMap<>();
for (Map.Entry<String, org.elasticsearch.client.watcher.ActionStatus> entry : status.getActions().entrySet()) {
actions.put(entry.getKey(), convertActionStatus(entry.getValue()));
}
return new WatchStatus(status.version(),
convertWatchStatusState(status.state()),
status.getExecutionState() == null ? null : convertWatchStatus(status.getExecutionState()),
status.lastChecked(), status.lastMetCondition(), actions, status.getHeaders()
);
}
private static ActionStatus convertActionStatus(org.elasticsearch.client.watcher.ActionStatus actionStatus) {
return new ActionStatus(convertAckStatus(actionStatus.ackStatus()),
actionStatus.lastExecution() == null ? null : convertActionStatusExecution(actionStatus.lastExecution()),
actionStatus.lastSuccessfulExecution() == null ? null : convertActionStatusExecution(actionStatus.lastSuccessfulExecution()),
actionStatus.lastThrottle() == null ? null : convertActionStatusThrottle(actionStatus.lastThrottle())
);
}
private static ActionStatus.AckStatus convertAckStatus(org.elasticsearch.client.watcher.ActionStatus.AckStatus ackStatus) {
return new ActionStatus.AckStatus(ackStatus.timestamp(), convertAckStatusState(ackStatus.state()));
}
private static ActionStatus.AckStatus.State convertAckStatusState(
org.elasticsearch.client.watcher.ActionStatus.AckStatus.State state) {
return ActionStatus.AckStatus.State.valueOf(state.name());
}
private static WatchStatus.State convertWatchStatusState(org.elasticsearch.client.watcher.WatchStatus.State state) {
return new WatchStatus.State(state.isActive(), state.getTimestamp());
}
private static ExecutionState convertWatchStatus(org.elasticsearch.client.watcher.ExecutionState executionState) {
return ExecutionState.valueOf(executionState.name());
}
private static ActionStatus.Execution convertActionStatusExecution(
org.elasticsearch.client.watcher.ActionStatus.Execution execution) {
if (execution.successful()) {
return ActionStatus.Execution.successful(execution.timestamp());
} else {
return ActionStatus.Execution.failure(execution.timestamp(), execution.reason());
}
}
private static ActionStatus.Throttle convertActionStatusThrottle(org.elasticsearch.client.watcher.ActionStatus.Throttle throttle) {
return new ActionStatus.Throttle(throttle.timestamp(), throttle.reason());
}
private static ZonedDateTime nowWithMillisResolution() {
return Instant.ofEpochMilli(Clock.systemUTC().millis()).atZone(ZoneOffset.UTC);
}
}

View File

@ -1,58 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;
public class PutWatchResponseTests extends ESTestCase {
public void testFromXContent() throws IOException {
xContentTester(this::createParser,
PutWatchResponseTests::createTestInstance,
PutWatchResponseTests::toXContent,
PutWatchResponse::fromXContent)
.supportsUnknownFields(true)
.assertToXContentEquivalence(false)
.test();
}
private static XContentBuilder toXContent(PutWatchResponse response, XContentBuilder builder) throws IOException {
return builder.startObject()
.field("_id", response.getId())
.field("_version", response.getVersion())
.field("_seq_no", response.getSeqNo())
.field("_primary_term", response.getPrimaryTerm())
.field("created", response.isCreated())
.endObject();
}
private static PutWatchResponse createTestInstance() {
String id = randomAlphaOfLength(10);
long seqNo = randomNonNegativeLong();
long primaryTerm = randomLongBetween(1, 200);
long version = randomLongBetween(1, 10);
boolean created = randomBoolean();
return new PutWatchResponse(id, version, seqNo, primaryTerm, created);
}
}

View File

@ -1,59 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.action.admin.cluster.repositories.verify.VerifyRepositoryResponse;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;
public class VerifyRepositoryResponseTests extends ESTestCase {
public void testFromXContent() throws IOException {
xContentTester(this::createParser,
VerifyRepositoryResponseTests::createTestInstance,
VerifyRepositoryResponseTests::toXContent,
VerifyRepositoryResponse::fromXContent)
.supportsUnknownFields(true)
.shuffleFieldsExceptions(new String[] {"nodes"}) // do not mix up the order of nodes, it will cause the tests to fail
.randomFieldsExcludeFilter((f) -> f.equals("nodes")) // everything in nodes needs to be a particular parseable object
.assertToXContentEquivalence(false)
.test();
}
private static VerifyRepositoryResponse createTestInstance() {
List<VerifyRepositoryResponse.NodeView> nodes = new ArrayList<>();
for (int i = 0; i < randomIntBetween(0, 2); i++) {
nodes.add(new VerifyRepositoryResponse.NodeView(randomAlphaOfLength(5), randomAlphaOfLength(5)));
}
return new VerifyRepositoryResponse(nodes);
}
private static XContentBuilder toXContent(VerifyRepositoryResponse response, XContentBuilder builder) throws IOException {
return response.toXContent(builder, ToXContent.EMPTY_PARAMS);
}
}

View File

@ -1,100 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.ValidationException;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import java.util.Optional;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
public class WatchRequestValidationTests extends ESTestCase {
public void testAcknowledgeWatchInvalidWatchId() {
ValidationException e = expectThrows(ValidationException.class,
() -> new AckWatchRequest("id with whitespaces"));
assertThat(e.validationErrors(), hasItem("watch id contains whitespace"));
}
public void testAcknowledgeWatchInvalidActionId() {
ValidationException e = expectThrows(ValidationException.class,
() -> new AckWatchRequest("_id", "action id with whitespaces"));
assertThat(e.validationErrors(), hasItem("action id [action id with whitespaces] contains whitespace"));
}
public void testAcknowledgeWatchNullActionArray() {
// need this to prevent some compilation errors, i.e. in 1.8.0_91
String[] nullArray = null;
Optional<ValidationException> e = new AckWatchRequest("_id", nullArray).validate();
assertFalse(e.isPresent());
}
public void testAcknowledgeWatchNullActionId() {
ValidationException e = expectThrows(ValidationException.class,
() -> new AckWatchRequest("_id", new String[] {null}));
assertThat(e.validationErrors(), hasItem("action id may not be null"));
}
public void testDeleteWatchInvalidWatchId() {
final IllegalArgumentException exception = expectThrows(IllegalArgumentException.class,
() -> new DeleteWatchRequest("id with whitespaces"));
assertThat(exception.getMessage(), is("watch id contains whitespace"));
}
public void testDeleteWatchNullId() {
final NullPointerException exception = expectThrows(NullPointerException.class,
() -> new DeleteWatchRequest(null));
assertThat(exception.getMessage(), is("watch id is missing"));
}
public void testPutWatchInvalidWatchId() {
final IllegalArgumentException exception = expectThrows(IllegalArgumentException.class,
() -> new PutWatchRequest("id with whitespaces", BytesArray.EMPTY, XContentType.JSON));
assertThat(exception.getMessage(), is("watch id contains whitespace"));
}
public void testPutWatchNullId() {
final NullPointerException exception = expectThrows(NullPointerException.class,
() -> new PutWatchRequest(null, BytesArray.EMPTY, XContentType.JSON));
assertThat(exception.getMessage(), is("watch id is missing"));
}
public void testPutWatchSourceNull() {
final NullPointerException exception = expectThrows(NullPointerException.class,
() -> new PutWatchRequest("foo", null, XContentType.JSON));
assertThat(exception.getMessage(), is("watch source is missing"));
}
public void testPutWatchContentNull() {
final NullPointerException exception = expectThrows(NullPointerException.class,
() -> new PutWatchRequest("foo", BytesArray.EMPTY, null));
assertThat(exception.getMessage(), is("request body is missing"));
}
public void testGetWatchInvalidWatchId() {
ValidationException e = expectThrows(ValidationException.class,
() -> new GetWatchRequest("id with whitespaces"));
assertThat(e.validationErrors(), hasItem("watch id contains whitespace"));
}
}

View File

@ -1,175 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.XContentTestUtils;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.function.Predicate;
public class WatchStatusTests extends ESTestCase {
public void testBasicParsing() throws IOException {
int expectedVersion = randomIntBetween(0, 100);
ExecutionState expectedExecutionState = randomFrom(ExecutionState.values());
boolean expectedActive = randomBoolean();
ActionStatus.AckStatus.State expectedAckState = randomFrom(ActionStatus.AckStatus.State.values());
XContentBuilder builder = createTestXContent(expectedVersion, expectedExecutionState,
expectedActive, expectedAckState);
BytesReference bytes = BytesReference.bytes(builder);
WatchStatus watchStatus = parse(builder.contentType(), bytes);
assertEquals(expectedVersion, watchStatus.version());
assertEquals(expectedExecutionState, watchStatus.getExecutionState());
assertEquals(Instant.ofEpochMilli(1432663467763L).atZone(ZoneOffset.UTC), watchStatus.lastChecked());
assertEquals(ZonedDateTime.parse("2015-05-26T18:04:27.763Z"), watchStatus.lastMetCondition());
WatchStatus.State watchState = watchStatus.state();
assertEquals(expectedActive, watchState.isActive());
assertEquals(ZonedDateTime.parse("2015-05-26T18:04:27.723Z"), watchState.getTimestamp());
ActionStatus actionStatus = watchStatus.actionStatus("test_index");
assertNotNull(actionStatus);
ActionStatus.AckStatus ackStatus = actionStatus.ackStatus();
assertEquals(ZonedDateTime.parse("2015-05-26T18:04:27.763Z"), ackStatus.timestamp());
assertEquals(expectedAckState, ackStatus.state());
ActionStatus.Execution lastExecution = actionStatus.lastExecution();
assertEquals(ZonedDateTime.parse("2015-05-25T18:04:27.733Z"), lastExecution.timestamp());
assertFalse(lastExecution.successful());
assertEquals("failed to send email", lastExecution.reason());
ActionStatus.Execution lastSuccessfulExecution = actionStatus.lastSuccessfulExecution();
assertEquals(ZonedDateTime.parse("2015-05-25T18:04:27.773Z"), lastSuccessfulExecution.timestamp());
assertTrue(lastSuccessfulExecution.successful());
assertNull(lastSuccessfulExecution.reason());
ActionStatus.Throttle lastThrottle = actionStatus.lastThrottle();
assertEquals(ZonedDateTime.parse("2015-04-25T18:05:23.445Z"), lastThrottle.timestamp());
assertEquals("throttling interval is set to [5 seconds] ...", lastThrottle.reason());
}
public void testParsingWithUnknownKeys() throws IOException {
int expectedVersion = randomIntBetween(0, 100);
ExecutionState expectedExecutionState = randomFrom(ExecutionState.values());
boolean expectedActive = randomBoolean();
ActionStatus.AckStatus.State expectedAckState = randomFrom(ActionStatus.AckStatus.State.values());
XContentBuilder builder = createTestXContent(expectedVersion, expectedExecutionState,
expectedActive, expectedAckState);
BytesReference bytes = BytesReference.bytes(builder);
Predicate<String> excludeFilter = field -> field.equals("actions");
BytesReference bytesWithRandomFields = XContentTestUtils.insertRandomFields(
builder.contentType(), bytes, excludeFilter, random());
WatchStatus watchStatus = parse(builder.contentType(), bytesWithRandomFields);
assertEquals(expectedVersion, watchStatus.version());
assertEquals(expectedExecutionState, watchStatus.getExecutionState());
}
public void testOptionalFieldsParsing() throws IOException {
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(contentType).startObject()
.field("version", 42)
.startObject("actions")
.startObject("test_index")
.startObject("ack")
.field("timestamp", "2015-05-26T18:04:27.763Z")
.field("state", "ackable")
.endObject()
.startObject("last_execution")
.field("timestamp", "2015-05-25T18:04:27.733Z")
.field("successful", false)
.field("reason", "failed to send email")
.endObject()
.endObject()
.endObject()
.endObject();
BytesReference bytes = BytesReference.bytes(builder);
WatchStatus watchStatus = parse(builder.contentType(), bytes);
assertEquals(42, watchStatus.version());
assertNull(watchStatus.getExecutionState());
assertFalse(watchStatus.checked());
}
private XContentBuilder createTestXContent(int version,
ExecutionState executionState,
boolean active,
ActionStatus.AckStatus.State ackState) throws IOException {
XContentType contentType = randomFrom(XContentType.values());
return XContentFactory.contentBuilder(contentType).startObject()
.field("version", version)
.field("execution_state", executionState)
.field("last_checked", 1432663467763L)
.field("last_met_condition", "2015-05-26T18:04:27.763Z")
.startObject("state")
.field("active", active)
.field("timestamp", "2015-05-26T18:04:27.723Z")
.endObject()
.startObject("actions")
.startObject("test_index")
.startObject("ack")
.field("timestamp", "2015-05-26T18:04:27.763Z")
.field("state", ackState)
.endObject()
.startObject("last_execution")
.field("timestamp", "2015-05-25T18:04:27.733Z")
.field("successful", false)
.field("reason", "failed to send email")
.endObject()
.startObject("last_successful_execution")
.field("timestamp", "2015-05-25T18:04:27.773Z")
.field("successful", true)
.endObject()
.startObject("last_throttle")
.field("timestamp", "2015-04-25T18:05:23.445Z")
.field("reason", "throttling interval is set to [5 seconds] ...")
.endObject()
.endObject()
.endObject()
.endObject();
}
private WatchStatus parse(XContentType contentType, BytesReference bytes) throws IOException {
XContentParser parser = XContentFactory.xContent(contentType)
.createParser(NamedXContentRegistry.EMPTY, null, bytes.streamInput());
parser.nextToken();
return WatchStatus.parse(parser);
}
}

View File

@ -1,188 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher;
import org.elasticsearch.client.NodesResponseHeader;
import org.elasticsearch.client.NodesResponseHeaderTestUtils;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.test.ESTestCase;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;
public class WatcherStatsResponseTests extends ESTestCase {
public void testFromXContent() throws IOException {
xContentTester(
this::createParser,
this::createTestInstance,
this::toXContent,
WatcherStatsResponse::fromXContent)
.supportsUnknownFields(true)
.randomFieldsExcludeFilter(field -> field.endsWith("stats"))
.test();
}
private void toXContent(WatcherStatsResponse response, XContentBuilder builder) throws IOException {
builder.startObject();
NodesResponseHeaderTestUtils.toXContent(response.getHeader(), response.getClusterName(), builder);
toXContent(response.getWatcherMetadata(), builder);
builder.startArray("stats");
for (WatcherStatsResponse.Node node : response.getNodes()) {
toXContent(node, builder);
}
builder.endArray();
builder.endObject();
}
private void toXContent(WatcherMetadata metadata, XContentBuilder builder) throws IOException {
builder.field("manually_stopped", metadata.manuallyStopped());
}
private void toXContent(WatcherStatsResponse.Node node, XContentBuilder builder) throws IOException {
builder.startObject();
builder.field("node_id", node.getNodeId());
builder.field("watcher_state", node.getWatcherState().toString().toLowerCase(Locale.ROOT));
builder.field("watch_count", node.getWatchesCount());
builder.startObject("execution_thread_pool");
builder.field("queue_size", node.getThreadPoolQueueSize());
builder.field("max_size", node.getThreadPoolMaxSize());
builder.endObject();
if (node.getSnapshots() != null) {
builder.startArray("current_watches");
for (WatchExecutionSnapshot snapshot : node.getSnapshots()) {
toXContent(snapshot, builder);
}
builder.endArray();
}
if (node.getQueuedWatches() != null) {
builder.startArray("queued_watches");
for (QueuedWatch queuedWatch : node.getQueuedWatches()) {
toXContent(queuedWatch, builder);
}
builder.endArray();
}
if (node.getStats() != null) {
builder.field("stats", node.getStats());
}
builder.endObject();
}
private void toXContent(WatchExecutionSnapshot snapshot, XContentBuilder builder) throws IOException {
builder.startObject();
builder.field("watch_id", snapshot.getWatchId());
builder.field("watch_record_id", snapshot.getWatchRecordId());
builder.timeField("triggered_time", snapshot.getTriggeredTime());
builder.timeField("execution_time", snapshot.getExecutionTime());
builder.field("execution_phase", snapshot.getPhase());
if (snapshot.getExecutedActions() != null) {
builder.startArray("executed_actions");
for (String executedAction : snapshot.getExecutedActions()) {
builder.value(executedAction);
}
builder.endArray();
}
if (snapshot.getExecutionStackTrace() != null) {
builder.startArray("stack_trace");
for (String element : snapshot.getExecutionStackTrace()) {
builder.value(element);
}
builder.endArray();
}
builder.endObject();
}
private void toXContent(QueuedWatch queuedWatch, XContentBuilder builder) throws IOException {
builder.startObject();
builder.field("watch_id", queuedWatch.getWatchId());
builder.field("watch_record_id", queuedWatch.getWatchRecordId());
builder.timeField("triggered_time", queuedWatch.getTriggeredTime());
builder.timeField("execution_time", queuedWatch.getExecutionTime());
builder.endObject();
}
protected WatcherStatsResponse createTestInstance() {
int nodeCount = randomInt(10);
List<WatcherStatsResponse.Node> nodes = new ArrayList<>(nodeCount);
for (int i = 0; i < nodeCount; i++) {
List<WatchExecutionSnapshot> snapshots = null;
if (randomBoolean()) {
int snapshotCount = randomInt(10);
snapshots = new ArrayList<>(snapshotCount);
for (int j = 0; j < snapshotCount; j++) {
String[] actions = null;
if (randomBoolean()) {
actions = new String[randomInt(10)];
for (int k = 0; k < actions.length; k++) {
actions[k] = randomAlphaOfLength(10);
}
}
String[] stackTrace = null;
if (randomBoolean()) {
stackTrace = new String[randomInt(10)];
for (int k = 0; k < stackTrace.length; k++) {
stackTrace[k] = randomAlphaOfLength(10);
}
}
snapshots.add(new WatchExecutionSnapshot(randomAlphaOfLength(10), randomAlphaOfLength(10),
new DateTime(randomInt(), DateTimeZone.UTC), new DateTime(randomInt(), DateTimeZone.UTC),
randomFrom(ExecutionPhase.values()), actions, stackTrace));
}
}
List<QueuedWatch> queuedWatches = null;
if(randomBoolean()) {
int queuedWatchCount = randomInt(10);
queuedWatches = new ArrayList<>(queuedWatchCount);
for (int j=0; j<queuedWatchCount; j++) {
queuedWatches.add(new QueuedWatch(randomAlphaOfLength(10), randomAlphaOfLength(10),
new DateTime(randomInt(), DateTimeZone.UTC), new DateTime(randomInt(), DateTimeZone.UTC)));
}
}
Map<String, Object> stats = null;
if (randomBoolean()) {
int statsCount = randomInt(10);
stats = new HashMap<>(statsCount);
for (int j=0; j<statsCount; j++) {
stats.put(randomAlphaOfLength(10), randomNonNegativeLong());
}
}
nodes.add(new WatcherStatsResponse.Node(randomAlphaOfLength(10), randomFrom(WatcherState.values()), randomNonNegativeLong(),
randomNonNegativeLong(), randomNonNegativeLong(), snapshots, queuedWatches, stats));
}
NodesResponseHeader nodesResponseHeader = new NodesResponseHeader(randomInt(10), randomInt(10),
randomInt(10), Collections.emptyList());
WatcherMetadata watcherMetadata = new WatcherMetadata(randomBoolean());
return new WatcherStatsResponse(nodesResponseHeader, randomAlphaOfLength(10), watcherMetadata, nodes);
}
}

View File

@ -1,53 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher.hlrc;
import org.elasticsearch.client.AbstractResponseTestCase;
import org.elasticsearch.client.watcher.DeleteWatchResponse;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
public class DeleteWatchResponseTests extends AbstractResponseTestCase<
org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse, DeleteWatchResponse> {
@Override
protected org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse createServerTestInstance(XContentType xContentType) {
String id = randomAlphaOfLength(10);
long version = randomLongBetween(1, 10);
boolean found = randomBoolean();
return new org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse(id, version, found);
}
@Override
protected DeleteWatchResponse doParseToClientInstance(XContentParser parser) throws IOException {
return DeleteWatchResponse.fromXContent(parser);
}
@Override
protected void assertInstances(org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse serverTestInstance,
DeleteWatchResponse clientInstance) {
assertThat(clientInstance.getId(), equalTo(serverTestInstance.getId()));
assertThat(clientInstance.getVersion(), equalTo(serverTestInstance.getVersion()));
assertThat(clientInstance.isFound(), equalTo(serverTestInstance.isFound()));
}
}

View File

@ -1,71 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher.hlrc;
import org.elasticsearch.client.AbstractResponseTestCase;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchResponse;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
public class ExecuteWatchResponseTests extends AbstractResponseTestCase<
ExecuteWatchResponse, org.elasticsearch.client.watcher.ExecuteWatchResponse> {
@Override
protected ExecuteWatchResponse createServerTestInstance(XContentType xContentType) {
String id = "my_watch_0-2015-06-02T23:17:55.124Z";
try {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
builder.field("watch_id", "my_watch");
builder.field("node", "my_node");
builder.startArray("messages");
builder.endArray();
builder.startObject("trigger_event");
builder.field("type", "manual");
builder.endObject();
builder.field("state", "executed");
builder.endObject();
BytesReference bytes = BytesReference.bytes(builder);
return new ExecuteWatchResponse(id, bytes, XContentType.JSON);
}
catch (IOException e) {
throw new AssertionError(e);
}
}
@Override
protected org.elasticsearch.client.watcher.ExecuteWatchResponse doParseToClientInstance(XContentParser parser) throws IOException {
return org.elasticsearch.client.watcher.ExecuteWatchResponse.fromXContent(parser);
}
@Override
protected void assertInstances(ExecuteWatchResponse serverTestInstance,
org.elasticsearch.client.watcher.ExecuteWatchResponse clientInstance) {
assertThat(clientInstance.getRecordId(), equalTo(serverTestInstance.getRecordId()));
assertThat(clientInstance.getRecordAsMap(), equalTo(serverTestInstance.getRecordSource().getAsMap()));
}
}

View File

@ -1,57 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.watcher.hlrc;
import org.elasticsearch.client.AbstractResponseTestCase;
import org.elasticsearch.client.watcher.PutWatchResponse;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
public class PutWatchResponseTests extends AbstractResponseTestCase<
org.elasticsearch.protocol.xpack.watcher.PutWatchResponse, PutWatchResponse> {
@Override
protected org.elasticsearch.protocol.xpack.watcher.PutWatchResponse createServerTestInstance(XContentType xContentType) {
String id = randomAlphaOfLength(10);
long seqNo = randomNonNegativeLong();
long primaryTerm = randomLongBetween(1, 20);
long version = randomLongBetween(1, 10);
boolean created = randomBoolean();
return new org.elasticsearch.protocol.xpack.watcher.PutWatchResponse(id, version, seqNo, primaryTerm, created);
}
@Override
protected PutWatchResponse doParseToClientInstance(XContentParser parser) throws IOException {
return PutWatchResponse.fromXContent(parser);
}
@Override
protected void assertInstances(org.elasticsearch.protocol.xpack.watcher.PutWatchResponse serverTestInstance,
PutWatchResponse clientInstance) {
assertThat(clientInstance.getId(), equalTo(serverTestInstance.getId()));
assertThat(clientInstance.getSeqNo(), equalTo(serverTestInstance.getSeqNo()));
assertThat(clientInstance.getPrimaryTerm(), equalTo(serverTestInstance.getPrimaryTerm()));
assertThat(clientInstance.getVersion(), equalTo(serverTestInstance.getVersion()));
assertThat(clientInstance.isCreated(), equalTo(serverTestInstance.isCreated()));
}
}

View File

@ -135,7 +135,6 @@ def projectPathsToExclude = [
':x-pack:plugin:transform', ':x-pack:plugin:transform',
':x-pack:plugin:vectors', ':x-pack:plugin:vectors',
':x-pack:plugin:voting-only-node', ':x-pack:plugin:voting-only-node',
':x-pack:plugin:watcher',
':x-pack:plugin:wildcard', ':x-pack:plugin:wildcard',
':x-pack:qa', ':x-pack:qa',
':x-pack:qa:security-example-spi-extension', ':x-pack:qa:security-example-spi-extension',

View File

@ -26,7 +26,6 @@ testClusters {
if (System.getProperty('run.distribution', 'default') == 'default') { if (System.getProperty('run.distribution', 'default') == 'default') {
String licenseType = System.getProperty("run.license_type", "basic") String licenseType = System.getProperty("run.license_type", "basic")
if (licenseType == 'trial') { if (licenseType == 'trial') {
setting 'xpack.watcher.enabled', 'true'
setting 'xpack.license.self_generated.type', 'trial' setting 'xpack.license.self_generated.type', 'trial'
} else if (licenseType != 'basic') { } else if (licenseType != 'basic') {
throw new IllegalArgumentException("Unsupported self-generated license type: [" + licenseType + "[basic] or [trial].") throw new IllegalArgumentException("Unsupported self-generated license type: [" + licenseType + "[basic] or [trial].")

View File

@ -212,8 +212,7 @@ public class Archives {
"elasticsearch-syskeygen", "elasticsearch-syskeygen",
"elasticsearch-users", "elasticsearch-users",
"x-pack-env", "x-pack-env",
"x-pack-security-env", "x-pack-security-env"
"x-pack-watcher-env"
).forEach(executable -> { ).forEach(executable -> {
assertThat(es.bin(executable), file(File, owner, owner, p755)); assertThat(es.bin(executable), file(File, owner, owner, p755));

View File

@ -539,8 +539,7 @@ public class Docker {
"elasticsearch-syskeygen", "elasticsearch-syskeygen",
"elasticsearch-users", "elasticsearch-users",
"x-pack-env", "x-pack-env",
"x-pack-security-env", "x-pack-security-env"
"x-pack-watcher-env"
).forEach(executable -> assertPermissionsAndOwnership(es.bin(executable), p755)); ).forEach(executable -> assertPermissionsAndOwnership(es.bin(executable), p755));
Stream.of("role_mapping.yml", "roles.yml", "users", "users_roles") Stream.of("role_mapping.yml", "roles.yml", "users", "users_roles")

View File

@ -240,8 +240,7 @@ public class Packages {
"elasticsearch-syskeygen", "elasticsearch-syskeygen",
"elasticsearch-users", "elasticsearch-users",
"x-pack-env", "x-pack-env",
"x-pack-security-env", "x-pack-security-env"
"x-pack-watcher-env"
).forEach(executable -> assertThat(es.bin(executable), file(File, "root", "root", p755))); ).forEach(executable -> assertThat(es.bin(executable), file(File, "root", "root", p755)));
Stream.of("users", "users_roles", "roles.yml", "role_mapping.yml", "log4j2.properties") Stream.of("users", "users_roles", "roles.yml", "role_mapping.yml", "log4j2.properties")

View File

@ -1834,15 +1834,7 @@ public class IndexNameExpressionResolverTests extends ESTestCase {
SearchRequest request = new SearchRequest(randomFrom("*", "_all")); SearchRequest request = new SearchRequest(randomFrom("*", "_all"));
List<String> indexNames = resolveConcreteIndexNameList(state, request); List<String> indexNames = resolveConcreteIndexNameList(state, request);
assertThat(indexNames, containsInAnyOrder("some-other-index", ".ml-stuff", ".ml-meta", ".watches")); assertThat(indexNames, containsInAnyOrder("some-other-index", ".ml-stuff", ".ml-meta"));
}
public void testWildcardSystemIndexResolutionMultipleMatchesAllowed() {
ClusterState state = systemIndexTestClusterState();
SearchRequest request = new SearchRequest(".w*");
List<String> indexNames = resolveConcreteIndexNameList(state, request);
assertThat(indexNames, containsInAnyOrder(".watches"));
} }
public void testWildcardSystemIndexResolutionSingleMatchAllowed() { public void testWildcardSystemIndexResolutionSingleMatchAllowed() {
@ -1867,8 +1859,8 @@ public class IndexNameExpressionResolverTests extends ESTestCase {
SearchRequest request = new SearchRequest(randomFrom("*", "_all")); SearchRequest request = new SearchRequest(randomFrom("*", "_all"));
List<String> indexNames = resolveConcreteIndexNameList(state, request); List<String> indexNames = resolveConcreteIndexNameList(state, request);
assertThat(indexNames, containsInAnyOrder("some-other-index", ".ml-stuff", ".ml-meta", ".watches")); assertThat(indexNames, containsInAnyOrder("some-other-index", ".ml-stuff", ".ml-meta"));
assertWarnings("this request accesses system indices: [.ml-meta, .ml-stuff, .watches], but in a future major version, " + assertWarnings("this request accesses system indices: [.ml-meta, .ml-stuff], but in a future major version, " +
"direct access to system indices will be prevented by default"); "direct access to system indices will be prevented by default");
} }
@ -1885,18 +1877,6 @@ public class IndexNameExpressionResolverTests extends ESTestCase {
} }
public void testWildcardSystemIndexReslutionSingleMatchDeprecated() {
threadContext.putHeader(SYSTEM_INDEX_ACCESS_CONTROL_HEADER_KEY, Boolean.FALSE.toString());
ClusterState state = systemIndexTestClusterState();
SearchRequest request = new SearchRequest(".w*");
List<String> indexNames = resolveConcreteIndexNameList(state, request);
assertThat(indexNames, containsInAnyOrder(".watches"));
assertWarnings("this request accesses system indices: [.watches], but in a future major version, direct access " +
"to system indices will be prevented by default");
}
public void testWildcardSystemIndexResolutionMultipleMatchesDeprecated() { public void testWildcardSystemIndexResolutionMultipleMatchesDeprecated() {
threadContext.putHeader(SYSTEM_INDEX_ACCESS_CONTROL_HEADER_KEY, Boolean.FALSE.toString()); threadContext.putHeader(SYSTEM_INDEX_ACCESS_CONTROL_HEADER_KEY, Boolean.FALSE.toString());
ClusterState state = systemIndexTestClusterState(); ClusterState state = systemIndexTestClusterState();
@ -2152,7 +2132,6 @@ public class IndexNameExpressionResolverTests extends ESTestCase {
Settings settings = Settings.builder().build(); Settings settings = Settings.builder().build();
Metadata.Builder mdBuilder = Metadata.builder() Metadata.Builder mdBuilder = Metadata.builder()
.put(indexBuilder(".ml-meta", settings).state(State.OPEN).system(true)) .put(indexBuilder(".ml-meta", settings).state(State.OPEN).system(true))
.put(indexBuilder(".watches", settings).state(State.OPEN).system(true))
.put(indexBuilder(".ml-stuff", settings).state(State.OPEN).system(true)) .put(indexBuilder(".ml-stuff", settings).state(State.OPEN).system(true))
.put(indexBuilder("some-other-index").state(State.OPEN)); .put(indexBuilder("some-other-index").state(State.OPEN));
return ClusterState.builder(new ClusterName("_name")).metadata(mdBuilder).build(); return ClusterState.builder(new ClusterName("_name")).metadata(mdBuilder).build();

View File

@ -1163,20 +1163,10 @@ public abstract class ESRestTestCase extends ESTestCase {
if (name.startsWith(".monitoring-")) { if (name.startsWith(".monitoring-")) {
return true; return true;
} }
if (name.startsWith(".watch") || name.startsWith(".triggered_watches")) {
return true;
}
if (name.startsWith(".data-frame-")) {
return true;
}
if (name.startsWith(".ml-")) {
return true;
}
if (name.startsWith(".transform-")) { if (name.startsWith(".transform-")) {
return true; return true;
} }
switch (name) { switch (name) {
case ".watches":
case "logstash-index-template": case "logstash-index-template":
case ".logstash-management": case ".logstash-management":
case "security_audit_log": case "security_audit_log":