private void wipeCluster() throws IOException { if (preserveIndicesUponCompletion() == false) { // wipe indices try { adminClient().performRequest("DELETE", "*"); } catch (ResponseException e) { // 404 here just means we had no indexes if (e.getResponse().getStatusLine().getStatusCode() != 404) { throw e; } } } // wipe index templates if (preserveTemplatesUponCompletion() == false) { adminClient().performRequest("DELETE", "_template/*"); } wipeSnapshots(); }
@Override public Map<String, Object> getMapping(String indexName, String type) throws IOException { final Response response; try { response = client.performRequest("GET", "/" + indexName + "/_mapping/" + type); } catch (ResponseException e) { LOGGER.warning("Requested index/type (" + indexName + "/" + type + ") not found"); return null; } try (final InputStream inputStream = response.getEntity().getContent()) { final Map<String,ElasticMappings> values; values = mapper.readValue(inputStream, new TypeReference<Map<String, ElasticMappings>>() {}); final Map<String,Object> properties; if (!values.containsKey(indexName) || !values.get(indexName).getMappings().containsKey(type)) { properties = null; } else { properties = values.get(indexName).getMappings().get(type).getProperties(); } return properties; } }
@Before public void setupIndex() throws IOException { try { client().performRequest("DELETE", indexName()); } catch (ResponseException e) { // If we get an error, it should be because the index doesn't exist assertEquals(404, e.getResponse().getStatusLine().getStatusCode()); } client().performRequest("PUT", indexName(), emptyMap(), new StringEntity("{\"settings\":{\"refresh_interval\":-1}}", ContentType.APPLICATION_JSON)); }
public void testBadRequest() throws IOException { final Response response = client().performRequest("GET", "/_nodes/settings", Collections.emptyMap()); final ObjectPath objectPath = ObjectPath.createFromResponse(response); final Map<String, Object> map = objectPath.evaluate("nodes"); int maxMaxInitialLineLength = Integer.MIN_VALUE; final Setting<ByteSizeValue> httpMaxInitialLineLength = HttpTransportSettings.SETTING_HTTP_MAX_INITIAL_LINE_LENGTH; final String key = httpMaxInitialLineLength.getKey().substring("http.".length()); for (Map.Entry<String, Object> entry : map.entrySet()) { @SuppressWarnings("unchecked") final Map<String, Object> settings = (Map<String, Object>)((Map<String, Object>)entry.getValue()).get("settings"); final int maxIntialLineLength; if (settings.containsKey("http")) { @SuppressWarnings("unchecked") final Map<String, Object> httpSettings = (Map<String, Object>)settings.get("http"); if (httpSettings.containsKey(key)) { maxIntialLineLength = ByteSizeValue.parseBytesSizeValue((String)httpSettings.get(key), key).bytesAsInt(); } else { maxIntialLineLength = httpMaxInitialLineLength.getDefault(Settings.EMPTY).bytesAsInt(); } } else { maxIntialLineLength = httpMaxInitialLineLength.getDefault(Settings.EMPTY).bytesAsInt(); } maxMaxInitialLineLength = Math.max(maxMaxInitialLineLength, maxIntialLineLength); } final String path = "/" + new String(new byte[maxMaxInitialLineLength], Charset.forName("UTF-8")).replace('\0', 'a'); final ResponseException e = expectThrows( ResponseException.class, () -> client().performRequest(randomFrom("GET", "POST", "PUT"), path, Collections.emptyMap())); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(BAD_REQUEST.getStatus())); assertThat(e, hasToString(containsString("too_long_frame_exception"))); assertThat(e, hasToString(matches("An HTTP line is larger than \\d+ bytes"))); }
public void testSniffNodes() throws IOException { HttpHost httpHost = new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort()); try (RestClient restClient = RestClient.builder(httpHost).build()) { ElasticsearchHostsSniffer sniffer = new ElasticsearchHostsSniffer(restClient, sniffRequestTimeout, scheme); try { List<HttpHost> sniffedHosts = sniffer.sniffHosts(); if (sniffResponse.isFailure) { fail("sniffNodes should have failed"); } assertThat(sniffedHosts.size(), equalTo(sniffResponse.hosts.size())); Iterator<HttpHost> responseHostsIterator = sniffResponse.hosts.iterator(); for (HttpHost sniffedHost : sniffedHosts) { assertEquals(sniffedHost, responseHostsIterator.next()); } } catch(ResponseException e) { Response response = e.getResponse(); if (sniffResponse.isFailure) { assertThat(e.getMessage(), containsString("GET " + httpHost + "/_nodes/http?timeout=" + sniffRequestTimeout + "ms")); assertThat(e.getMessage(), containsString(Integer.toString(sniffResponse.nodesInfoResponseCode))); assertThat(response.getHost(), equalTo(httpHost)); assertThat(response.getStatusLine().getStatusCode(), equalTo(sniffResponse.nodesInfoResponseCode)); assertThat(response.getRequestLine().toString(), equalTo("GET /_nodes/http?timeout=" + sniffRequestTimeout + "ms HTTP/1.1")); } else { fail("sniffNodes should have succeeded: " + response.getStatusLine()); } } } }
public void testThatErrorTraceParamReturns400() throws IOException { ResponseException e = expectThrows(ResponseException.class, () -> getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"))); Response response = e.getResponse(); assertThat(response.getHeader("Content-Type"), is("application/json; charset=UTF-8")); assertThat(EntityUtils.toString(e.getResponse().getEntity()), containsString("\"error\":\"error traces in responses are disabled.\"")); assertThat(response.getStatusLine().getStatusCode(), is(400)); }
public void testThatSettingHeadersWorks() throws IOException { ensureGreen(); try { getRestClient().performRequest("GET", "/_protected"); fail("request should have failed"); } catch(ResponseException e) { Response response = e.getResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(401)); assertThat(response.getHeader("Secret"), equalTo("required")); } Response authResponse = getRestClient().performRequest("GET", "/_protected", new BasicHeader("Secret", "password")); assertThat(authResponse.getStatusLine().getStatusCode(), equalTo(200)); assertThat(authResponse.getHeader("Secret"), equalTo("granted")); }
public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws IOException { try { getRestClient().performRequest("GET", "/", new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", "http://evil-host:9200")); fail("request should have failed"); } catch(ResponseException e) { Response response = e.getResponse(); // a rejected origin gets a FORBIDDEN - 403 assertThat(response.getStatusLine().getStatusCode(), is(403)); assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue()); } }
public void testThatPreFlightRequestReturnsNullOnNonMatch() throws IOException { try { getRestClient().performRequest("OPTIONS", "/", new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", "http://evil-host:9200"), new BasicHeader("Access-Control-Request-Method", "GET")); fail("request should have failed"); } catch(ResponseException e) { Response response = e.getResponse(); // a rejected origin gets a FORBIDDEN - 403 assertThat(response.getStatusLine().getStatusCode(), is(403)); assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue()); assertThat(response.getHeader("Access-Control-Allow-Methods"), nullValue()); } }
public ESSaveResponse update(String index, String type, Long sourceId, Map<String, String> params, HttpEntity requestBody) { params = addTenantId2Param(params); // for real-time fetch //params.put("refresh", "true"); try { Response response = client.performRequest( "POST", index + "/" + type + "/" + sourceId + "/_update", params, requestBody); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode > 299) { logger.warn("Problem while indexing a document: {}" + response.getStatusLine().getReasonPhrase()); throw new ElasticAPIException("Could not index a document, status code is " + statusCode); } ESSaveResponse esResponse = gson.fromJson(IOUtils.toString(response.getEntity().getContent()), ESSaveResponse.class); return esResponse; } catch (ResponseException rex) { logger.warn("Got elasticsearch exception " + rex); Response res = rex.getResponse(); if (res.getStatusLine().getStatusCode() == 409) { logger.warn("Conflict on store object"); throw new ElasticVersionConflictException("type:" + type + " params:" + params.toString() + " exception:" + rex); } }catch (IOException e) { logger.error("Failed to update document with type [" + type + "] id ["+sourceId+"]"); } return null; }
public ESSaveResponse Store(String index, String type, Long sourceId, Map<String, String> params, HttpEntity requestBody) { params = addTenantId2Param(params); // for real-time fetch //params.put("refresh", "true"); try { Response response = client.performRequest( "POST", index + "/" + type + "/" + sourceId, params, requestBody); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode > 299) { logger.warn("Problem while indexing a document: {}" + response.getStatusLine().getReasonPhrase()); throw new ElasticAPIException("Could not index a document, status code is " + statusCode); } ESSaveResponse esQueryResponse = gson.fromJson(IOUtils.toString(response.getEntity().getContent()), ESSaveResponse.class); return esQueryResponse; } catch (ResponseException rex) { logger.warn("Got elasticsearch exception " + rex); Response res = rex.getResponse(); if (res.getStatusLine().getStatusCode() == 409) { logger.warn("Conflict on store object"); throw new ElasticVersionConflictException(index+type); } } catch (IOException e) { logger.error("Failed to store document with type [" + type + "] id [" + sourceId + "]: ",e); } return null; }
/** * By specifying the unique identification of an object we can return only that object. If we cannot find the object * we throw an {@link QueryByIdNotFoundException}. * * @param request Object containing the required parameters * @param <T> Type of the object to be mapped to * @return Found object of type T */ public <T> T queryById(QueryByIdRequest request) { if (request.getTypeReference() == null) { throw new QueryExecutionException("The TypeReference in the request cannot be null"); } try { String endpoint = createEndpointString(request.getIndex(), request.getType(), request.getId()); Response response = client.performRequest(GET, endpoint, getRequestParams(request)); GetByIdResponse<T> queryResponse = jacksonObjectMapper.readValue(response.getEntity().getContent(), request.getTypeReference()); if (!queryResponse.getFound()) { throw new QueryByIdNotFoundException(request.getIndex(), request.getType(), request.getId()); } T entity = queryResponse.getSource(); if (request.getAddId()) { addIdToEntity(request.getId(), entity); } return entity; } catch (ResponseException re) { if (re.getResponse().getStatusLine().getStatusCode() == 404) { throw new QueryByIdNotFoundException(request.getIndex(), request.getType(), request.getId()); } else { logger.warn("Problem while executing request.", re); throw new QueryExecutionException("Error when executing a document"); } } catch (IOException e) { logger.warn("Problem while executing request.", e); throw new QueryExecutionException("Error when executing a document"); } }
public void testHttpConnectionWithNoAuthentication() throws Exception { try { Response bad = getRestClient().performRequest("GET", "/", Collections.emptyMap()); fail("an exception should be thrown but got: " + bad.getEntity().toString()); } catch (ResponseException e) { Response response = e.getResponse(); assertThat(response.getStatusLine().getStatusCode(), is(401)); String value = response.getHeader("WWW-Authenticate"); assertThat(value, is("custom-challenge")); } }
@Override public List<String> getTypes(String indexName) throws IOException { final Response response; try { response = client.performRequest("GET", "/" + indexName + "/_mapping"); } catch (ResponseException e) { if (e.getResponse().getStatusLine().getStatusCode() == 404) { return new ArrayList<>(); } throw e; } try (final InputStream inputStream = response.getEntity().getContent()) { final Map<String,ElasticMappings> values; values = mapper.readValue(inputStream, new TypeReference<Map<String, ElasticMappings>>() {}); final Map<String, Mapping> mappings; if (values.containsKey(indexName)) { mappings = values.get(indexName).getMappings(); } else { final String aliasedIndex = getIndices(indexName).stream().findFirst().orElse(null); if (values.containsKey(aliasedIndex)) { mappings = values.get(aliasedIndex).getMappings(); } else { LOGGER.severe("No types found for index/alias " + indexName); mappings = Collections.EMPTY_MAP; } } return mappings.keySet().stream().map(key -> (String) key).collect(Collectors.toList()); } }
ClientYamlTestResponseException(ResponseException responseException) throws IOException { super(responseException); this.responseException = responseException; this.restTestResponse = new ClientYamlTestResponse(responseException.getResponse()); }
public SearchResponseException(String message, ResponseException responseException) { super(message, responseException); this.responseException = responseException; }
public SearchResponseException(ResponseException responseException) { super(responseException); this.responseException = responseException; }
public ResponseException getResponseException() { return responseException; }
/** * Exposes the origina {@link ResponseException}. Note that the entity will always be null as it * gets eagerly consumed and exposed through {@link #getRestTestResponse()}. */ public ResponseException getResponseException() { return responseException; }