Skip to content

Commit b23d5eb

Browse files
committed
Rest HL client: Add put watch action
Relates elastic#29827
1 parent edf83c1 commit b23d5eb

File tree

41 files changed

+508
-122
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+508
-122
lines changed

client/rest-high-level/build.gradle

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,7 @@ integTestRunner {
163163
classpath += shadowJar.outputs.files
164164
dependsOn shadowJar
165165
}
166+
167+
integTestCluster {
168+
setting 'xpack.license.self_generated.type', 'trial'
169+
}

client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@
106106
import org.elasticsearch.index.VersionType;
107107
import org.elasticsearch.index.rankeval.RankEvalRequest;
108108
import org.elasticsearch.protocol.xpack.XPackInfoRequest;
109+
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
109110
import org.elasticsearch.rest.action.search.RestSearchAction;
110111
import org.elasticsearch.script.mustache.MultiSearchTemplateRequest;
111112
import org.elasticsearch.script.mustache.SearchTemplateRequest;
@@ -1096,6 +1097,25 @@ static Request xPackInfo(XPackInfoRequest infoRequest) {
10961097
return request;
10971098
}
10981099

1100+
static Request xPackWatcherPutWatch(PutWatchRequest putWatchRequest) {
1101+
String endpoint = new EndpointBuilder()
1102+
.addPathPartAsIs("_xpack")
1103+
.addPathPartAsIs("watcher")
1104+
.addPathPartAsIs("watch")
1105+
.addPathPart(putWatchRequest.getId())
1106+
.build();
1107+
1108+
Request request = new Request(HttpPut.METHOD_NAME, endpoint);
1109+
Params params = new Params(request).withVersion(putWatchRequest.getVersion());
1110+
if (putWatchRequest.isActive() == false) {
1111+
params.putParam("active", "false");
1112+
}
1113+
ContentType contentType = createContentType(putWatchRequest.xContentType());
1114+
BytesReference source = putWatchRequest.getSource();
1115+
request.setEntity(new ByteArrayEntity(source.toBytesRef().bytes, 0, source.length(), contentType));
1116+
return request;
1117+
}
1118+
10991119
private static HttpEntity createEntity(ToXContent toXContent, XContentType xContentType) throws IOException {
11001120
BytesRef source = XContentHelper.toXContent(toXContent, xContentType, false).toBytesRef();
11011121
return new ByteArrayEntity(source.bytes, source.offset, source.length, createContentType(xContentType));
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.elasticsearch.client;
20+
21+
import org.elasticsearch.action.ActionListener;
22+
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
23+
import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse;
24+
25+
import java.io.IOException;
26+
27+
import static java.util.Collections.emptySet;
28+
29+
public final class WatcherClient {
30+
31+
private final RestHighLevelClient restHighLevelClient;
32+
33+
WatcherClient(RestHighLevelClient restHighLevelClient) {
34+
this.restHighLevelClient = restHighLevelClient;
35+
}
36+
37+
/**
38+
* Put a watch into the cluster
39+
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-put-watch.html">
40+
* the docs</a> for more.
41+
* @param request the request
42+
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
43+
* @return the response
44+
* @throws IOException in case there is a problem sending the request or parsing back the response
45+
*/
46+
public PutWatchResponse putWatch(PutWatchRequest request, RequestOptions options) throws IOException {
47+
return restHighLevelClient.performRequestAndParseEntity(request, RequestConverters::xPackWatcherPutWatch, options,
48+
PutWatchResponse::fromXContent, emptySet());
49+
}
50+
51+
/**
52+
* Asynchronously put a watch into the cluster
53+
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-put-watch.html">
54+
* the docs</a> for more.
55+
* @param request the request
56+
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
57+
* @param listener the listener to be notified upon request completion
58+
*/
59+
public void putWatchAsync(PutWatchRequest request, RequestOptions options,
60+
ActionListener<PutWatchResponse> listener) {
61+
restHighLevelClient.performRequestAsyncAndParseEntity(request, RequestConverters::xPackWatcherPutWatch, options,
62+
PutWatchResponse::fromXContent, listener, emptySet());
63+
}
64+
}

client/rest-high-level/src/main/java/org/elasticsearch/client/XPackClient.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,17 @@
3737
* X-Pack APIs on elastic.co</a> for more information.
3838
*/
3939
public final class XPackClient {
40+
4041
private final RestHighLevelClient restHighLevelClient;
42+
private final WatcherClient watcherClient;
4143

4244
XPackClient(RestHighLevelClient restHighLevelClient) {
4345
this.restHighLevelClient = restHighLevelClient;
46+
this.watcherClient = new WatcherClient(restHighLevelClient);
47+
}
48+
49+
public WatcherClient watcher() {
50+
return watcherClient;
4451
}
4552

4653
/**

client/rest-high-level/src/test/java/org/elasticsearch/client/PingAndInfoIT.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,13 @@ public void testXPackInfo() throws IOException {
6666

6767
assertEquals(mainResponse.getBuild().shortHash(), info.getBuildInfo().getHash());
6868

69-
assertEquals("basic", info.getLicenseInfo().getType());
70-
assertEquals("basic", info.getLicenseInfo().getMode());
69+
assertEquals("trial", info.getLicenseInfo().getType());
70+
assertEquals("trial", info.getLicenseInfo().getMode());
7171
assertEquals(LicenseStatus.ACTIVE, info.getLicenseInfo().getStatus());
7272

7373
FeatureSet graph = info.getFeatureSetsInfo().getFeatureSets().get("graph");
7474
assertNotNull(graph.description());
75-
assertFalse(graph.available());
75+
assertTrue(graph.available());
7676
assertTrue(graph.enabled());
7777
assertNull(graph.nativeCodeInfo());
7878
FeatureSet monitoring = info.getFeatureSetsInfo().getFeatureSets().get("monitoring");
@@ -82,7 +82,7 @@ public void testXPackInfo() throws IOException {
8282
assertNull(monitoring.nativeCodeInfo());
8383
FeatureSet ml = info.getFeatureSetsInfo().getFeatureSets().get("ml");
8484
assertNotNull(ml.description());
85-
assertFalse(ml.available());
85+
assertTrue(ml.available());
8686
assertTrue(ml.enabled());
8787
assertEquals(mainResponse.getVersion().toString(),
8888
ml.nativeCodeInfo().get("version").toString().replace("-SNAPSHOT", ""));

client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
package org.elasticsearch.client;
2121

22+
import com.carrotsearch.randomizedtesting.annotations.Repeat;
2223
import org.apache.http.HttpEntity;
2324
import org.apache.http.client.methods.HttpDelete;
2425
import org.apache.http.client.methods.HttpGet;
@@ -125,6 +126,7 @@
125126
import org.elasticsearch.index.rankeval.RatedRequest;
126127
import org.elasticsearch.index.rankeval.RestRankEvalAction;
127128
import org.elasticsearch.protocol.xpack.XPackInfoRequest;
129+
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
128130
import org.elasticsearch.repositories.fs.FsRepository;
129131
import org.elasticsearch.rest.action.search.RestSearchAction;
130132
import org.elasticsearch.script.ScriptType;
@@ -145,6 +147,7 @@
145147
import org.elasticsearch.test.RandomObjects;
146148
import org.hamcrest.CoreMatchers;
147149

150+
import java.io.ByteArrayOutputStream;
148151
import java.io.IOException;
149152
import java.io.InputStream;
150153
import java.nio.charset.StandardCharsets;
@@ -2523,6 +2526,35 @@ public void testXPackInfo() {
25232526
assertEquals(expectedParams, request.getParameters());
25242527
}
25252528

2529+
public void testXPackPutWatch() throws Exception {
2530+
PutWatchRequest putWatchRequest = new PutWatchRequest();
2531+
String watchId = randomAlphaOfLength(10);
2532+
putWatchRequest.setId(watchId);
2533+
String body = randomAlphaOfLength(20);
2534+
putWatchRequest.setSource(new BytesArray(body), XContentType.JSON);
2535+
2536+
Map<String, String> expectedParams = new HashMap<>();
2537+
if (randomBoolean()) {
2538+
putWatchRequest.setActive(false);
2539+
expectedParams.put("active", "false");
2540+
}
2541+
2542+
if (randomBoolean()) {
2543+
long version = randomLongBetween(10, 100);
2544+
putWatchRequest.setVersion(version);
2545+
expectedParams.put("version", String.valueOf(version));
2546+
}
2547+
2548+
Request request = RequestConverters.xPackWatcherPutWatch(putWatchRequest);
2549+
assertEquals(HttpPut.METHOD_NAME, request.getMethod());
2550+
assertEquals("/_xpack/watcher/watch/" + watchId, request.getEndpoint());
2551+
assertEquals(expectedParams, request.getParameters());
2552+
assertThat(request.getEntity().getContentType().getValue(), is(XContentType.JSON.mediaTypeWithoutParameters()));
2553+
ByteArrayOutputStream bos = new ByteArrayOutputStream();
2554+
request.getEntity().writeTo(bos);
2555+
assertThat(bos.toString("UTF-8"), is(body));
2556+
}
2557+
25262558
/**
25272559
* Randomize the {@link FetchSourceContext} request parameters.
25282560
*/
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.elasticsearch.client;
20+
21+
import org.elasticsearch.common.bytes.BytesArray;
22+
import org.elasticsearch.common.bytes.BytesReference;
23+
import org.elasticsearch.common.xcontent.XContentType;
24+
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
25+
import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse;
26+
27+
import static org.hamcrest.Matchers.is;
28+
29+
public class WatcherIT extends ESRestHighLevelClientTestCase {
30+
31+
public void testPutWatch() throws Exception {
32+
String watchId = randomAlphaOfLength(10);
33+
String json = "{ \n" +
34+
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
35+
" \"input\": { \"none\": {} },\n" +
36+
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
37+
"}";
38+
BytesReference bytesReference = new BytesArray(json);
39+
PutWatchRequest putWatchRequest = new PutWatchRequest(watchId, bytesReference, XContentType.JSON);
40+
PutWatchResponse putWatchResponse = highLevelClient().xpack().watcher().putWatch(putWatchRequest, RequestOptions.DEFAULT);
41+
assertThat(putWatchResponse.isCreated(), is(true));
42+
assertThat(putWatchResponse.getId(), is(watchId));
43+
assertThat(putWatchResponse.getVersion(), is(1L));
44+
}
45+
46+
}

client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/MiscellaneousDocumentationIT.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,14 @@
3737
import org.elasticsearch.protocol.xpack.XPackInfoResponse.LicenseInfo;
3838

3939
import java.io.IOException;
40+
import java.time.Instant;
4041
import java.util.EnumSet;
4142
import java.util.concurrent.CountDownLatch;
4243
import java.util.concurrent.TimeUnit;
4344

45+
import static org.hamcrest.Matchers.greaterThan;
46+
import static org.hamcrest.Matchers.is;
47+
4448
/**
4549
* Documentation for miscellaneous APIs in the high level java client.
4650
* Code wrapped in {@code tag} and {@code end} tags is included in the docs.
@@ -92,8 +96,7 @@ public void testXPackInfo() throws Exception {
9296
//tag::x-pack-info-response
9397
BuildInfo build = response.getBuildInfo(); // <1>
9498
LicenseInfo license = response.getLicenseInfo(); // <2>
95-
assertEquals(XPackInfoResponse.BASIC_SELF_GENERATED_LICENSE_EXPIRATION_MILLIS,
96-
license.getExpiryDate()); // <3>
99+
assertThat(license.getExpiryDate(), is(greaterThan(Instant.now().toEpochMilli()))); // <3>
97100
FeatureSetsInfo features = response.getFeatureSetsInfo(); // <4>
98101
//end::x-pack-info-response
99102

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.elasticsearch.client.documentation;
20+
21+
import org.elasticsearch.action.ActionListener;
22+
import org.elasticsearch.action.LatchedActionListener;
23+
import org.elasticsearch.client.ESRestHighLevelClientTestCase;
24+
import org.elasticsearch.client.RequestOptions;
25+
import org.elasticsearch.client.RestHighLevelClient;
26+
import org.elasticsearch.common.bytes.BytesArray;
27+
import org.elasticsearch.common.bytes.BytesReference;
28+
import org.elasticsearch.common.xcontent.XContentType;
29+
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
30+
import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse;
31+
32+
import java.util.concurrent.CountDownLatch;
33+
import java.util.concurrent.TimeUnit;
34+
35+
public class WatcherDocumentationIT extends ESRestHighLevelClientTestCase {
36+
37+
public void testPutWatch() throws Exception {
38+
RestHighLevelClient client = highLevelClient();
39+
40+
{
41+
//tag::x-pack-put-watch-execute
42+
// you can also use the WatchSourceBuilder from x-pack-transport to create a watch programmatically
43+
BytesReference watch = new BytesArray("{ \n" +
44+
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
45+
" \"input\": { \"simple\": { \"foo\" : \"bar\" } },\n" +
46+
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
47+
"}");
48+
PutWatchRequest request = new PutWatchRequest("my_watch_id", watch, XContentType.JSON);
49+
request.setActive(false); // <1>
50+
PutWatchResponse response = client.xpack().watcher().putWatch(request, RequestOptions.DEFAULT);
51+
//end::x-pack-put-watch-execute
52+
53+
//tag::x-pack-put-watch-response
54+
String watchId = response.getId(); // <1>
55+
boolean isCreated = response.isCreated(); // <2>
56+
long version = response.getVersion(); // <3>
57+
//end::x-pack-put-watch-response
58+
}
59+
60+
{
61+
BytesReference watch = new BytesArray("{ \n" +
62+
" \"trigger\": { \"schedule\": { \"interval\": \"10h\" } },\n" +
63+
" \"input\": { \"simple\": { \"foo\" : \"bar\" } },\n" +
64+
" \"actions\": { \"logme\": { \"logging\": { \"text\": \"{{ctx.payload}}\" } } }\n" +
65+
"}");
66+
PutWatchRequest request = new PutWatchRequest("my_other_watch_id", watch, XContentType.JSON);
67+
// tag::x-pack-put-watch-execute-listener
68+
ActionListener<PutWatchResponse> listener = new ActionListener<PutWatchResponse>() {
69+
@Override
70+
public void onResponse(PutWatchResponse response) {
71+
// <1>
72+
}
73+
74+
@Override
75+
public void onFailure(Exception e) {
76+
// <2>
77+
}
78+
};
79+
// end::x-pack-put-watch-execute-listener
80+
81+
// Replace the empty listener by a blocking listener in test
82+
final CountDownLatch latch = new CountDownLatch(1);
83+
listener = new LatchedActionListener<>(listener, latch);
84+
85+
// tag::x-pack-put-watch-execute-async
86+
client.xpack().watcher().putWatchAsync(request, RequestOptions.DEFAULT, listener); // <1>
87+
// end::x-pack-put-watch-execute-async
88+
89+
assertTrue(latch.await(30L, TimeUnit.SECONDS));
90+
}
91+
}
92+
}

0 commit comments

Comments
 (0)