Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
package org.elasticsearch.client;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.client.watcher.ActivateWatchResponse;
import org.elasticsearch.protocol.xpack.watcher.DeleteWatchRequest;
import org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse;
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
Expand Down Expand Up @@ -91,4 +93,31 @@ public void deleteWatchAsync(DeleteWatchRequest request, RequestOptions options,
restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::deleteWatch, options,
DeleteWatchResponse::fromXContent, listener, singleton(404));
}

/**
* 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
*/
public void activateWatchAsync(ActivateWatchRequest request, RequestOptions options, ActionListener<ActivateWatchResponse> listener) {
restHighLevelClient.performRequestAsyncAndParseEntity(request, WatcherRequestConverters::activateWatch, options,
ActivateWatchResponse::fromXContent, listener, singleton(404));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.protocol.xpack.watcher.DeleteWatchRequest;
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
Expand Down Expand Up @@ -59,4 +60,17 @@ static Request deleteWatch(DeleteWatchRequest deleteWatchRequest) {
Request request = new Request(HttpDelete.METHOD_NAME, endpoint);
return request;
}

static Request activateWatch(ActivateWatchRequest activateWatchRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_xpack")
.addPathPartAsIs("watcher")
.addPathPartAsIs("watch")
.addPathPartAsIs(activateWatchRequest.getWatchId())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.addPathPart(activateWatchRequest...)
.addPathPartAsIs("_activate")

Looks like you swapped the two of them.

.addPathPart("_activate")
.build();

Request request = new Request(HttpPut.METHOD_NAME, endpoint);
return request;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* 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 org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;

import java.io.Closeable;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

/**
* A request to explicitly activate a watch.
*/
public final class ActivateWatchRequest implements Validatable, Closeable, ToXContentObject {

private final String watchId;

public ActivateWatchRequest(String watchId) {
this.watchId = Objects.requireNonNull(watchId, "Watch identifier is required");
}

/**
* @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;
}

@Override
public void close() {
}

@Override
public Optional<ValidationException> validate() {

ValidationException exception = new ValidationException();

if (watchId == null) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should just put these in the constructor (the null check already is) and throw from there instead of here and just not override it

exception.addValidationError("watch id is missing");
} else if (PutWatchRequest.isValidId(watchId) == false) {
exception.addValidationError("watch id contains whitespace");
}
return !exception.validationErrors().isEmpty()
? Optional.of(exception)
: Optional.empty();
}

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Node needed and it really doesnt even do anything, so we can remove it and ToXContent interface

return builder;
}

@Override
public String toString() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need to override toString here? seems relatively harmless, but wasn't sure if it's necessary.

StringBuilder sb = new StringBuilder("activate [").append(watchId).append("]");
return sb.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* 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 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);
}


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

extra space

private static final ParseField STATUS_FIELD = new ParseField("status");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is typically on teh top of these classes.

private static ConstructingObjectParser<ActivateWatchResponse, Void> PARSER =
new ConstructingObjectParser<>("activate_watch_response", true,
a -> new ActivateWatchResponse((WatchStatus) a[0]));

static {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this too is on top

PARSER.declareObject(ConstructingObjectParser.constructorArg(),
(parser, context) -> WatchStatus.parse(parser),
STATUS_FIELD);
}

public static ActivateWatchResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,20 @@
*/
package org.elasticsearch.client;

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.client.watcher.ActivateWatchResponse;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.protocol.xpack.watcher.DeleteWatchRequest;
import org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse;
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse;
import org.elasticsearch.rest.RestStatus;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;

public class WatcherIT extends ESRestHighLevelClientTestCase {

Expand Down Expand Up @@ -72,4 +77,31 @@ public void testDeleteWatch() throws Exception {
}
}

public void testActivateWatch() throws Exception {
// Activate watch that exists
{
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()));

}

// Activate watch that does not exist
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd split this into a separate test case, testActivateWatchThatExists and testActivateWatchThatDoesNotExist

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

{
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());
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.protocol.xpack.watcher.DeleteWatchRequest;
Expand Down Expand Up @@ -75,4 +76,14 @@ public void testDeleteWatch() {
assertEquals("/_xpack/watcher/watch/" + watchId, request.getEndpoint());
assertThat(request.getEntity(), nullValue());
}

public void testActivateWatch() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think testActivateWatchRequestConversion is a clearer name.

String watchId = randomAlphaOfLength(10);
ActivateWatchRequest activateWatchRequest = new ActivateWatchRequest(watchId);

Request request = WatcherRequestConverters.activateWatch(activateWatchRequest);
assertEquals(HttpPut.METHOD_NAME, request.getMethod());
assertEquals("/_xpack/watcher/watch/" + watchId + "/_activate", request.getEndpoint());
assertThat(request.getEntity(), nullValue());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
import org.elasticsearch.client.ESRestHighLevelClientTestCase;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.watcher.ActivateWatchRequest;
import org.elasticsearch.client.watcher.ActivateWatchResponse;
import org.elasticsearch.client.watcher.WatchStatus;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentType;
Expand Down Expand Up @@ -132,4 +135,59 @@ public void onFailure(Exception e) {
}
}

public void testActivateWatch() throws Exception {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will have a new ay to deal with the docs+test, we should wait to merge until it is merged.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hub-cap which is the issue that it is introducing this change?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#34125 and it looks like its merged!

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-execute
ActivateWatchRequest request = new ActivateWatchRequest("my_watch_id");
ActivateWatchResponse response = client.watcher().activateWatch(request, RequestOptions.DEFAULT);
//end::activate-watch-execute

//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-execute-listener
ActionListener<ActivateWatchResponse> listener = new ActionListener<ActivateWatchResponse>() {
@Override
public void onResponse(ActivateWatchResponse response) {
// <1>
}

@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::activate-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::activate-watch-execute-async
client.watcher().activateWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
//end::activate-watch-execute-async

assertTrue(latch.await(30L, TimeUnit.SECONDS));

}
}
}
2 changes: 2 additions & 0 deletions docs/java-rest/high-level/supported-apis.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -298,9 +298,11 @@ The Java High Level REST Client supports the following Watcher APIs:

* <<java-rest-high-x-pack-watcher-put-watch>>
* <<java-rest-high-x-pack-watcher-delete-watch>>
* <<java-rest-high-watcher-activate-watch>>

include::watcher/put-watch.asciidoc[]
include::watcher/delete-watch.asciidoc[]
include::watcher/activate-watch.asciidoc[]

== Graph APIs

Expand Down
Loading