Refine search
private Map<String, Object> parseResponse(Response response) throws IOException { final int code = response.getStatusLine().getStatusCode(); if (code >= 200 & code < 300) { InputStream inputStream = response.getEntity().getContent(); byte[] result = IOUtils.toByteArray(inputStream); inputStream.close(); return mapper.readValue(new String(result, charset), Map.class); } else { String errorMessage = String.format("ElasticSearch reported an error while trying to run the query: %s", response.getStatusLine().getReasonPhrase()); throw new IOException(errorMessage); } }
/** * Determines whether a resource exists in ES. This will call a GET method to a particular path and * return true if status 200; false otherwise. * * @param resourcePath The path of the resource to get. * @return True if it exists; false otherwise. * @throws IOException If an error occurred during requests to ES. */ public boolean doesResourceExist(final String resourcePath) throws IOException { Response response = elasticSearchAdminClient.performRequest(HttpMethod.HEAD, resourcePath); return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; }
/** * https://www.elastic.co/guide/en/elasticsearch/reference/5.6/indices-put-mapping.html * @param index * @param mappingType https://www.elastic.co/guide/en/elasticsearch/reference/5.6/mapping.html#mapping-type * @param mapping * @throws IOException */ public void putMapping(String index, String mappingType, String mapping) throws IOException { HttpEntity entity = new StringEntity(mapping); Response response = lowLevelClient.performRequest("PUT" , "/" + index + "/_mapping/" + mappingType , Collections.emptyMap() , entity ); if(response.getStatusLine().getStatusCode() != 200) { String responseStr = IOUtils.toString(response.getEntity().getContent()); throw new IllegalStateException("Got a " + response.getStatusLine().getStatusCode() + " due to " + responseStr); } }
@Override // TODO change interface to return Settings. public Map getSetting(String indexName) { Assert.notNull(indexName, "No index defined for getSettings"); ObjectMapper objMapper = new ObjectMapper(); Map settings = null; RestClient restClient = client.getLowLevelClient(); try { Response response = restClient.performRequest("GET", "/" + indexName + "/_settings"); settings = convertSettingResponse(EntityUtils.toString(response.getEntity()), indexName); } catch (Exception e) { throw new ElasticsearchException("Error while getting settings for indexName : " + indexName, e); } return settings; }
private ElasticsearchJson.Result httpRequest(ObjectNode query) throws IOException { Objects.requireNonNull(query, "query"); String uri = String.format(Locale.ROOT, "/%s/%s/_search", indexName, typeName); Hook.QUERY_PLAN.run(query); final String json = mapper.writeValueAsString(query); LOGGER.debug("Elasticsearch Query: {}", json); HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); Response response = restClient.performRequest("POST", uri, Collections.emptyMap(), entity); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { final String error = EntityUtils.toString(response.getEntity()); final String message = String.format(Locale.ROOT, "Error while querying Elastic (on %s/%s) status: %s\nQuery:\n%s\nError:\n%s\n", response.getHost(), response.getRequestLine(), response.getStatusLine(), query, error); throw new RuntimeException(message); } try (InputStream is = response.getEntity().getContent()) { return mapper.readValue(is, ElasticsearchJson.Result.class); } }
private Response performRequest(String method, String path, byte[] requestData) throws IOException { final HttpEntity entity = requestData != null ? new ByteArrayEntity(requestData, ContentType.APPLICATION_JSON) : null; final Response response = delegate.performRequest( method, path, Collections.emptyMap(), entity); if (response.getStatusLine().getStatusCode() >= 400) { throw new IOException("Error executing request: " + response.getStatusLine().getReasonPhrase()); } return response; }
private RequestBuilder handleResponseException(ResponseException e) throws OptimisticLockException { if (customExceptionHandler != null) { HttpEntity result = customExceptionHandler.apply(e); if (result != null) { responseEntity = result; return this; } } JSONObject error = extractErrorJSON(e); if (e.getResponse().getStatusLine().getStatusCode() == 409) { throw new OptimisticLockException(error.getString(PARAM_REASON), e); } throw Exceptions.handle() .to(Elastic.LOG) .error(e) .withSystemErrorMessage("Elasticsearch (%s) reported an error: %s (%s)", e.getResponse().getHost(), error == null ? "unknown" : error.getString(PARAM_REASON), error == null ? "-" : error.getString(PARAM_TYPE)) .handle(); }
private static String buildMessage(Response response) throws IOException { String message = response.getRequestLine().getMethod() + " " + response.getHost() + response.getRequestLine().getUri() + ": " + response.getStatusLine().toString(); HttpEntity entity = response.getEntity(); if (entity != null) { if (entity.isRepeatable() == false) { entity = new BufferedHttpEntity(entity); response.getHttpResponse().setEntity(entity); } message += "\n" + EntityUtils.toString(entity); } return message; }
String body = EntityUtils.toString(response.getEntity()); Map jsonMap = new ObjectMapper().readValue(body, Map.class); if (jsonMap.containsKey("status")) { LOGGER.warn("Caught ResponseException calling {}: {}", CLUSTER_HEALTH_ENDPOINT, e.getResponse().getStatusLine()); } catch (IOException e) { LOGGER.error("Caught IOException calling _cluster/health: {}", e.getMessage());
protected JSONObject extractErrorJSON(ResponseException e) { try { JSONObject response = JSON.parseObject(EntityUtils.toString(e.getResponse().getEntity())); return response.getJSONObject(PARAM_ERROR); } catch (IOException ex) { Exceptions.handle(Elastic.LOG, ex); throw Exceptions.handle() .to(Elastic.LOG) .error(e) .withSystemErrorMessage("Elasticsearch (%s) reported an error which cannot be unpacked: %s", e.getResponse().getHost()) .handle(); } }
public ClientYamlTestResponse(Response response) throws IOException { this.response = response; if (response.getEntity() != null) { String contentType = response.getHeader("Content-Type"); this.bodyContentType = XContentType.fromMediaTypeOrFormat(contentType); try { byte[] bytes = EntityUtils.toByteArray(response.getEntity()); //skip parsing if we got text back (e.g. if we called _cat apis) if (bodyContentType != null) { this.parsedResponse = ObjectPath.createFromXContent(bodyContentType.xContent(), new BytesArray(bytes)); } this.body = bytes; } catch (IOException e) { EntityUtils.consumeQuietly(response.getEntity()); throw e; } } else { this.body = null; this.bodyContentType = null; } }
public static ObjectPath createFromResponse(Response response) throws IOException { byte[] bytes = EntityUtils.toByteArray(response.getEntity()); String contentType = response.getHeader("Content-Type"); XContentType xContentType = XContentType.fromMediaTypeOrFormat(contentType); return ObjectPath.createFromXContent(xContentType.xContent(), new BytesArray(bytes)); }
private Map<String, Object> map(final Response response) throws IOException { try (InputStream is = response.getEntity().getContent()) { final ObjectMapper mapper = new ObjectMapper(); @SuppressWarnings("unchecked") final Map<String, Object> map = mapper.readValue(is, Map.class); return map; } }
public ElasticsearchResponse(Response response) throws IOException { this.statusLine = response.getStatusLine(); if (response.getEntity() != null) { this.entity = parseResponse(response); } }
/** * Queries {@code _mapping} definition to automatically detect all types for an index * * @return list of types associated with this index * @throws IOException for any IO related issues * @throws IllegalStateException if reply is not understood */ private Set<String> listTypesFromElastic() throws IOException { final String endpoint = "/" + index + "/_mapping"; final Response response = client.performRequest("GET", endpoint); try (InputStream is = response.getEntity().getContent()) { JsonNode root = mapper.readTree(is); if (!root.isObject() || root.size() != 1) { final String message = String.format(Locale.ROOT, "Invalid response for %s/%s " + "Expected object of size 1 got %s (of size %d)", response.getHost(), response.getRequestLine(), root.getNodeType(), root.size()); throw new IllegalStateException(message); } JsonNode mappings = root.iterator().next().get("mappings"); if (mappings == null || mappings.size() == 0) { final String message = String.format(Locale.ROOT, "Index %s does not have any types", index); throw new IllegalStateException(message); } Set<String> types = Sets.newHashSet(mappings.fieldNames()); types.remove("_default_"); return types; } }
/** * Parses the response body and extracts a specific value from it (identified by the provided path) */ public Object evaluate(String path, Stash stash) throws IOException { if (response == null) { return null; } if (parsedResponse == null) { //special case: api that don't support body (e.g. exists) return true if 200, false if 404, even if no body //is_true: '' means the response had no body but the client returned true (caused by 200) //is_false: '' means the response had no body but the client returned false (caused by 404) if ("".equals(path) && HttpHead.METHOD_NAME.equals(response.getRequestLine().getMethod())) { return isError() == false; } return null; } return parsedResponse.evaluate(path, stash); } }
try { final Response searchResponse = search(table, key); final int statusCode = searchResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_NOT_FOUND) { return Status.NOT_FOUND; final Response deleteResponse = restClient.performRequest("DELETE", "/" + indexKey + "/" + table + "/" + hit.get("_id")); if (deleteResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return Status.ERROR;
/** * Gets ALL Elasticsearch indices, or null if status code returned is not OK 200. */ public String[] getIndices() throws IOException { Response response = lowLevelClient.performRequest("GET", "/_cat/indices"); if(response.getStatusLine().getStatusCode() == 200) { String responseStr = IOUtils.toString(response.getEntity().getContent()); List<String> indices = new ArrayList<>(); for(String line : Splitter.on("\n").split(responseStr)) { Iterable<String> splits = Splitter.on(" ").split(line.replaceAll("\\s+", " ").trim()); if(Iterables.size(splits) > 3) { String index = Iterables.get(splits, 2, ""); if(!StringUtils.isEmpty(index)) { indices.add(index.trim()); } } } String[] ret = new String[indices.size()]; ret=indices.toArray(ret); return ret; } return null; }
@Override public Map getMapping(String indexName, String type) { Assert.notNull(indexName, "No index defined for getMapping()"); Assert.notNull(type, "No type defined for getMapping()"); Map mappings = null; RestClient restClient = client.getLowLevelClient(); try { Response response = restClient.performRequest("GET", "/" + indexName + "/_mapping/" + type); mappings = convertMappingResponse(EntityUtils.toString(response.getEntity()), type); } catch (Exception e) { throw new ElasticsearchException( "Error while getting mapping for indexName : " + indexName + " type : " + type + " ", e); } return mappings; }
private static String buildMessage(Response response) throws IOException { String message = String.format(Locale.ROOT, "method [%s], host [%s], URI [%s], status line [%s]", response.getRequestLine().getMethod(), response.getHost(), response.getRequestLine().getUri(), response.getStatusLine().toString() ); HttpEntity entity = response.getEntity(); if (entity != null) { if (entity.isRepeatable() == false) { entity = new BufferedHttpEntity(entity); response.getHttpResponse().setEntity(entity); } message += "\n" + EntityUtils.toString(entity); } return message; }