Params putParam(String name, String value) { if (Strings.hasLength(value)) { request.addParameter(name, value); } return this; }
private Mono<ClientResponse> sendRequest(WebClient webClient, String logId, Request request, HttpHeaders headers) { RequestBodySpec requestBodySpec = webClient.method(HttpMethod.valueOf(request.getMethod().toUpperCase())) // .uri(builder -> { builder = builder.path(request.getEndpoint()); if (!ObjectUtils.isEmpty(request.getParameters())) { for (Entry<String, String> entry : request.getParameters().entrySet()) { builder = builder.queryParam(entry.getKey(), entry.getValue()); if (request.getOptions() != null) { if (!ObjectUtils.isEmpty(request.getOptions().getHeaders())) { request.getOptions().getHeaders().forEach(it -> theHeaders.add(it.getName(), it.getValue())); if (request.getEntity() != null) { ClientLogger.logRequest(logId, request.getMethod().toUpperCase(), request.getEndpoint(), request.getParameters(), body::get); requestBodySpec.contentType(MediaType.valueOf(request.getEntity().getContentType().getValue())); requestBodySpec.body(Mono.fromSupplier(body::get), String.class); } else { ClientLogger.logRequest(logId, request.getMethod().toUpperCase(), request.getEndpoint(), request.getParameters());
@Override public void performLowLevelRequest(String method, String endpoint, String jsonEntity) throws IOException { Request request = new Request(method, endpoint); if (!isNullOrEmpty(jsonEntity)) { request.setJsonEntity(jsonEntity); } client.getLowLevelClient().performRequest(request); }
public static Request ping() { return new Request(HttpMethod.HEAD.name(), "/"); }
static Request scroll(String scroll, TimeValue keepAlive, Version remoteVersion) { Request request = new Request("POST", "/_search/scroll"); if (remoteVersion.before(Version.V_5_0_0)) { /* Versions of Elasticsearch before 5.0 couldn't parse nanos or micros * so we toss out that resolution, rounding up so we shouldn't end up * with 0s. */ keepAlive = timeValueMillis((long) Math.ceil(keepAlive.millisFrac())); } request.addParameter("scroll", keepAlive.getStringRep()); if (remoteVersion.before(Version.fromId(2000099))) { // Versions before 2.0.0 extract the plain scroll_id from the body request.setEntity(new NStringEntity(scroll, ContentType.TEXT_PLAIN)); return request; } try (XContentBuilder entity = JsonXContent.contentBuilder()) { entity.startObject() .field("scroll_id", scroll) .endObject(); request.setJsonEntity(Strings.toString(entity)); } catch (IOException e) { throw new ElasticsearchException("failed to build scroll entity", e); } return request; }
/** * Creates a new instance of the Elasticsearch sniffer. It will use the provided {@link RestClient} to fetch the hosts * through the nodes info api, the provided sniff request timeout value and scheme. * @param restClient client used to fetch the hosts from elasticsearch through nodes info api. Usually the same instance * that is also provided to {@link Sniffer#builder(RestClient)}, so that the hosts are set to the same * client that was used to sniff them. * @param sniffRequestTimeoutMillis the sniff request timeout (in milliseconds) to be passed in as a query string parameter * to elasticsearch. Allows to halt the request without any failure, as only the nodes * that have responded within this timeout will be returned. * @param scheme the scheme to associate sniffed nodes with (as it is not returned by elasticsearch) */ public ElasticsearchNodesSniffer(RestClient restClient, long sniffRequestTimeoutMillis, Scheme scheme) { this.restClient = Objects.requireNonNull(restClient, "restClient cannot be null"); if (sniffRequestTimeoutMillis < 0) { throw new IllegalArgumentException("sniffRequestTimeoutMillis must be greater than 0"); } this.request = new Request("GET", "/_nodes/http"); request.addParameter("timeout", sniffRequestTimeoutMillis + "ms"); this.scheme = Objects.requireNonNull(scheme, "scheme cannot be null"); }
private static Request toRequest(ElasticsearchRequest elasticsearchRequest, HttpEntity entity) { Request request = new Request( elasticsearchRequest.getMethod(), elasticsearchRequest.getPath() ); for ( Entry<String, String> parameter : elasticsearchRequest.getParameters().entrySet() ) { request.addParameter( parameter.getKey(), parameter.getValue() ); } request.setEntity( entity ); return request; }
static Request clearScroll(String scroll, Version remoteVersion) { Request request = new Request("DELETE", "/_search/scroll"); if (remoteVersion.before(Version.fromId(2000099))) { // Versions before 2.0.0 extract the plain scroll_id from the body request.setEntity(new NStringEntity(scroll, ContentType.TEXT_PLAIN)); return request; } try (XContentBuilder entity = JsonXContent.contentBuilder()) { entity.startObject() .array("scroll_id", scroll) .endObject(); request.setJsonEntity(Strings.toString(entity)); } catch (IOException e) { throw new ElasticsearchException("failed to build clear scroll entity", e); } return request; } }
Request request = new Request("POST", "/" + this.esIndex + "/SampleResult/_bulk"); StringBuilder bulkRequestBody = new StringBuilder(); String actionMetaData = String.format(SEND_BULK_REQUEST, this.esIndex, "SampleResult"); request.setEntity(new NStringEntity(bulkRequestBody.toString(), ContentType.APPLICATION_JSON)); RequestOptions.Builder options = request.getOptions().toBuilder(); options.addHeader("Authorization", "Basic " + encodedCredentials); request.setOptions(options);
addIndexesOrTypes(path, "Type", searchRequest.types()); path.append("_search"); Request request = new Request("POST", path.toString()); request.addParameter("scroll", keepAlive.getStringRep()); request.addParameter("size", Integer.toString(searchRequest.source().size())); if (searchRequest.source().version() == null || searchRequest.source().version() == true) { request.addParameter("version", null); request.addParameter("search_type", "scan"); } else { StringBuilder sorts = new StringBuilder(sortToUri(searchRequest.source().sorts().get(0))); sorts.append(',').append(sortToUri(searchRequest.source().sorts().get(i))); request.addParameter("sort", sorts.toString()); request.addParameter(storedFieldsParamName, fields.toString()); request.setJsonEntity(Strings.toString(entity)); } catch (IOException e) { throw new ElasticsearchException("unexpected error building entity", e);
/** * Add all headers from the provided varargs argument to a {@link Request}. This only exists * to support methods that exist for backwards compatibility. */ @Deprecated private static void setOptions(Request request, HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory, Header... headers) { Objects.requireNonNull(headers, "headers cannot be null"); RequestOptions.Builder options = request.getOptions().toBuilder(); for (Header header : headers) { Objects.requireNonNull(header, "header cannot be null"); options.addHeader(header.getName(), header.getValue()); } options.setHttpAsyncResponseConsumerFactory(httpAsyncResponseConsumerFactory); request.setOptions(options); }
/** * Defines a helper method for requests that can 404 and in which case will return an empty Optional * otherwise tries to parse the response body */ protected final <Req extends Validatable, Resp> Optional<Resp> performRequestAndParseOptionalEntity(Req request, CheckedFunction<Req, Request, IOException> requestConverter, RequestOptions options, CheckedFunction<XContentParser, Resp, IOException> entityParser ) throws IOException { Optional<ValidationException> validationException = request.validate(); if (validationException != null && validationException.isPresent()) { throw validationException.get(); } Request req = requestConverter.apply(request); req.setOptions(options); Response response; try { response = client.performRequest(req); } catch (ResponseException e) { if (RestStatus.NOT_FOUND.getStatus() == e.getResponse().getStatusLine().getStatusCode()) { return Optional.empty(); } throw parseResponseException(e); } try { return Optional.of(parseEntity(response.getEntity(), entityParser)); } catch (Exception e) { throw new IOException("Unable to parse response body for " + response, e); } }
@Override public void performLowLevelRequest(String method, String endpoint, String jsonEntity) throws IOException { Request request = new Request(method, endpoint); if (!isNullOrEmpty(jsonEntity)) { request.setJsonEntity(jsonEntity); } client.getLowLevelClient().performRequest(request); }
public static Request info() { return new Request(HttpMethod.GET.name(), "/"); }
/** * Creates a new instance of the Elasticsearch sniffer. It will use the provided {@link RestClient} to fetch the hosts * through the nodes info api, the provided sniff request timeout value and scheme. * @param restClient client used to fetch the hosts from elasticsearch through nodes info api. Usually the same instance * that is also provided to {@link Sniffer#builder(RestClient)}, so that the hosts are set to the same * client that was used to sniff them. * @param sniffRequestTimeoutMillis the sniff request timeout (in milliseconds) to be passed in as a query string parameter * to elasticsearch. Allows to halt the request without any failure, as only the nodes * that have responded within this timeout will be returned. * @param scheme the scheme to associate sniffed nodes with (as it is not returned by elasticsearch) */ public ElasticsearchNodesSniffer(RestClient restClient, long sniffRequestTimeoutMillis, Scheme scheme) { this.restClient = Objects.requireNonNull(restClient, "restClient cannot be null"); if (sniffRequestTimeoutMillis < 0) { throw new IllegalArgumentException("sniffRequestTimeoutMillis must be greater than 0"); } this.request = new Request("GET", "/_nodes/http"); request.addParameter("timeout", sniffRequestTimeoutMillis + "ms"); this.scheme = Objects.requireNonNull(scheme, "scheme cannot be null"); }
private static Request toRequest(ElasticsearchRequest elasticsearchRequest, HttpEntity entity) { Request request = new Request( elasticsearchRequest.getMethod(), elasticsearchRequest.getPath() ); for ( Entry<String, String> parameter : elasticsearchRequest.getParameters().entrySet() ) { request.addParameter( parameter.getKey(), parameter.getValue() ); } request.setEntity( entity ); return request; }
/** * Provides common functionality for asynchronously performing a request. */ private <Req, Resp> void internalPerformRequestAsync(Req request, CheckedFunction<Req, Request, IOException> requestConverter, RequestOptions options, CheckedFunction<Response, Resp, IOException> responseConverter, ActionListener<Resp> listener, Set<Integer> ignores) { Request req; try { req = requestConverter.apply(request); } catch (Exception e) { listener.onFailure(e); return; } req.setOptions(options); ResponseListener responseListener = wrapResponseListener(responseConverter, listener, ignores); client.performRequestAsync(req, responseListener); }
/** * Fully removes a type from an index (removes data) * @param index index name * @param type type * @throws IOException In case of error */ public void deleteByQuery(String index, String type) throws IOException { logger.debug("deleteByQuery [{}]/[{}]", index, type); String deleteByQuery = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " }\n" + "}"; Request request = new Request("POST", "/" + index + "/" + type + "/_delete_by_query"); request.setJsonEntity(deleteByQuery); Response restResponse = client.getLowLevelClient().performRequest(request); Map<String, Object> response = asMap(restResponse); logger.debug("reindex response: {}", response); }