Browse Source

HLRC: Deactivate Watch API (#34192)

Relates to #29827
Mark Tozzi 7 years ago
parent
commit
d94406a68a

+ 31 - 0
client/rest-high-level/src/main/java/org/elasticsearch/client/WatcherClient.java

@@ -19,6 +19,8 @@
 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;
@@ -125,6 +127,35 @@ public final class WatcherClient {
             PutWatchResponse::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
+     */
+    public void deactivateWatchAsync(DeactivateWatchRequest request, RequestOptions options,
+                                     ActionListener<DeactivateWatchResponse> listener) {
+        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">

+ 12 - 0
client/rest-high-level/src/main/java/org/elasticsearch/client/WatcherRequestConverters.java

@@ -24,6 +24,7 @@ import org.apache.http.client.methods.HttpPost;
 import org.apache.http.client.methods.HttpPut;
 import org.apache.http.entity.ByteArrayEntity;
 import org.apache.http.entity.ContentType;
+import org.elasticsearch.client.watcher.DeactivateWatchRequest;
 import org.elasticsearch.client.watcher.ActivateWatchRequest;
 import org.elasticsearch.client.watcher.AckWatchRequest;
 import org.elasticsearch.client.watcher.StartWatchServiceRequest;
@@ -75,6 +76,17 @@ final class WatcherRequestConverters {
         return request;
     }
 
+    static Request deactivateWatch(DeactivateWatchRequest deactivateWatchRequest) {
+        String endpoint = new RequestConverters.EndpointBuilder()
+            .addPathPartAsIs("_xpack")
+            .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("_xpack")

+ 43 - 0
client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeactivateWatchRequest.java

@@ -0,0 +1,43 @@
+/*
+ * 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.protocol.xpack.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;
+    }
+}
+

+ 65 - 0
client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeactivateWatchResponse.java

@@ -0,0 +1,65 @@
+/*
+ * 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;
+    }
+}

+ 21 - 0
client/rest-high-level/src/test/java/org/elasticsearch/client/WatcherIT.java

@@ -19,6 +19,10 @@
 package org.elasticsearch.client;
 
 import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.watcher.DeactivateWatchRequest;
+import org.elasticsearch.client.watcher.DeactivateWatchResponse;
+import org.elasticsearch.client.watcher.ActivateWatchRequest;
+import org.elasticsearch.client.watcher.ActivateWatchResponse;
 import org.elasticsearch.action.support.master.AcknowledgedResponse;
 import org.elasticsearch.client.watcher.AckWatchRequest;
 import org.elasticsearch.client.watcher.AckWatchResponse;
@@ -73,6 +77,23 @@ public class WatcherIT extends ESRestHighLevelClientTestCase {
         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
         {

+ 10 - 0
client/rest-high-level/src/test/java/org/elasticsearch/client/WatcherRequestConvertersTests.java

@@ -22,6 +22,7 @@ package org.elasticsearch.client;
 import org.apache.http.client.methods.HttpDelete;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.client.methods.HttpPut;
+import org.elasticsearch.client.watcher.DeactivateWatchRequest;
 import org.elasticsearch.client.watcher.ActivateWatchRequest;
 import org.elasticsearch.client.watcher.AckWatchRequest;
 import org.elasticsearch.client.watcher.StartWatchServiceRequest;
@@ -83,6 +84,15 @@ public class WatcherRequestConvertersTests extends ESTestCase {
         assertThat(bos.toString("UTF-8"), is(body));
     }
 
+    public void testDeactivateWatch() {
+        String watchId = randomAlphaOfLength(10);
+        DeactivateWatchRequest deactivateWatchRequest = new DeactivateWatchRequest(watchId);
+        Request request = WatcherRequestConverters.deactivateWatch(deactivateWatchRequest);
+
+        assertEquals(HttpPut.METHOD_NAME, request.getMethod());
+        assertEquals("/_xpack/watcher/watch/" + watchId + "/_deactivate", request.getEndpoint());
+    }
+
     public void testDeleteWatch() {
         DeleteWatchRequest deleteWatchRequest = new DeleteWatchRequest();
         String watchId = randomAlphaOfLength(10);

+ 55 - 0
client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/WatcherDocumentationIT.java

@@ -32,6 +32,8 @@ 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.StartWatchServiceRequest;
 import org.elasticsearch.client.watcher.StopWatchServiceRequest;
 import org.elasticsearch.client.watcher.WatchStatus;
@@ -47,6 +49,8 @@ import org.elasticsearch.rest.RestStatus;
 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 {
@@ -297,6 +301,57 @@ public class WatcherDocumentationIT extends ESRestHighLevelClientTestCase {
         }
     }
 
+    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();
 

+ 41 - 0
client/rest-high-level/src/test/java/org/elasticsearch/client/watcher/DeactivateWatchRequestTests.java

@@ -0,0 +1,41 @@
+/*
+ * 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"));
+    }
+
+}

+ 58 - 0
client/rest-high-level/src/test/java/org/elasticsearch/client/watcher/DeactivateWatchResponseTests.java

@@ -0,0 +1,58 @@
+/*
+ * 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);
+    }
+}

+ 2 - 0
docs/java-rest/high-level/supported-apis.asciidoc

@@ -346,6 +346,7 @@ The Java High Level REST Client supports the following Watcher APIs:
 * <<{upid}-stop-watch-service>>
 * <<java-rest-high-x-pack-watcher-put-watch>>
 * <<java-rest-high-x-pack-watcher-delete-watch>>
+* <<java-rest-high-watcher-deactivate-watch>>
 * <<{upid}-ack-watch>>
 * <<{upid}-activate-watch>>
 
@@ -354,6 +355,7 @@ include::watcher/stop-watch-service.asciidoc[]
 include::watcher/put-watch.asciidoc[]
 include::watcher/delete-watch.asciidoc[]
 include::watcher/ack-watch.asciidoc[]
+include::watcher/deactivate-watch.asciidoc[]
 include::watcher/activate-watch.asciidoc[]
 
 == Graph APIs

+ 10 - 0
docs/java-rest/high-level/watcher/deactivate-watch.asciidoc

@@ -0,0 +1,10 @@
+--
+:api: deactivate-watch
+:request: deactivateWatchRequet
+:response: deactivateWatchResponse
+:doc-tests-file: {doc-tests}/WatcherDocumentationIT.java
+--
+[[java-rest-high-watcher-deactivate-watch]]
+=== Deactivate Watch API
+
+include::../execution.asciidoc[]