Search in sources :

Example 26 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class RestHighLevelClientTests method testPerformRequestOnResponseExceptionWithEntity.

public void testPerformRequestOnResponseExceptionWithEntity() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getSuppressed()[0]);
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Header(org.apache.http.Header) StatusLine(org.apache.http.StatusLine) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) ArgumentMatcher(org.mockito.ArgumentMatcher) RequestLine(org.apache.http.RequestLine) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Matchers.eq(org.mockito.Matchers.eq) ClusterName(org.elasticsearch.cluster.ClusterName) JsonParseException(com.fasterxml.jackson.core.JsonParseException) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Matchers.anyVararg(org.mockito.Matchers.anyVararg) ActionRequest(org.elasticsearch.action.ActionRequest) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) StringEntity(org.apache.http.entity.StringEntity) XContentHelper.toXContent(org.elasticsearch.common.xcontent.XContentHelper.toXContent) MainResponse(org.elasticsearch.action.main.MainResponse) CheckedFunction(org.elasticsearch.common.CheckedFunction) List(java.util.List) Version(org.elasticsearch.Version) ArrayEquals(org.mockito.internal.matchers.ArrayEquals) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException) Matchers.argThat(org.mockito.Matchers.argThat) RestStatus(org.elasticsearch.rest.RestStatus) Mockito.mock(org.mockito.Mockito.mock) XContentType(org.elasticsearch.common.xcontent.XContentType) BasicStatusLine(org.apache.http.message.BasicStatusLine) Matchers(org.mockito.Matchers) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.anyString(org.mockito.Matchers.anyString) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) Matchers.anyMapOf(org.mockito.Matchers.anyMapOf) SocketTimeoutException(java.net.SocketTimeoutException) Matchers.anyObject(org.mockito.Matchers.anyObject) ESTestCase(org.elasticsearch.test.ESTestCase) MainRequest(org.elasticsearch.action.main.MainRequest) Before(org.junit.Before) CborXContent(org.elasticsearch.common.xcontent.cbor.CborXContent) BasicRequestLine(org.apache.http.message.BasicRequestLine) SmileXContent(org.elasticsearch.common.xcontent.smile.SmileXContent) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) XContentParser(org.elasticsearch.common.xcontent.XContentParser) ProtocolVersion(org.apache.http.ProtocolVersion) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Build(org.elasticsearch.Build) VarargMatcher(org.mockito.internal.matchers.VarargMatcher) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) MainRequest(org.elasticsearch.action.main.MainRequest) ActionRequest(org.elasticsearch.action.ActionRequest) MainRequest(org.elasticsearch.action.main.MainRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) Matchers.anyString(org.mockito.Matchers.anyString) ElasticsearchException(org.elasticsearch.ElasticsearchException) MainResponse(org.elasticsearch.action.main.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) StringEntity(org.apache.http.entity.StringEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) RestStatus(org.elasticsearch.rest.RestStatus) HttpHost(org.apache.http.HttpHost)

Example 27 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project crate by crate.

the class SQLExceptions method createSQLActionException.

/**
     * Create a {@link SQLActionException} out of a {@link Throwable}.
     * If concrete {@link ElasticsearchException} is found, first transform it
     * to a {@link CrateException}
     */
public static SQLActionException createSQLActionException(Throwable e) {
    if (e instanceof SQLActionException) {
        return (SQLActionException) e;
    }
    e = esToCrateException(e);
    int errorCode = 5000;
    RestStatus restStatus = RestStatus.INTERNAL_SERVER_ERROR;
    if (e instanceof CrateException) {
        CrateException crateException = (CrateException) e;
        if (e instanceof ValidationException) {
            errorCode = 4000 + crateException.errorCode();
            restStatus = RestStatus.BAD_REQUEST;
        } else if (e instanceof ReadOnlyException) {
            errorCode = 4030 + crateException.errorCode();
            restStatus = RestStatus.FORBIDDEN;
        } else if (e instanceof ResourceUnknownException) {
            errorCode = 4040 + crateException.errorCode();
            restStatus = RestStatus.NOT_FOUND;
        } else if (e instanceof ConflictException) {
            errorCode = 4090 + crateException.errorCode();
            restStatus = RestStatus.CONFLICT;
        } else if (e instanceof UnhandledServerException) {
            errorCode = 5000 + crateException.errorCode();
        }
    } else if (e instanceof ParsingException) {
        errorCode = 4000;
        restStatus = RestStatus.BAD_REQUEST;
    } else if (e instanceof MapperParsingException) {
        errorCode = 4000;
        restStatus = RestStatus.BAD_REQUEST;
    }
    String message = e.getMessage();
    if (message == null) {
        if (e instanceof CrateException && e.getCause() != null) {
            // use cause because it contains a more meaningful error in most cases
            e = e.getCause();
        }
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        if (stackTraceElements.length > 0) {
            message = String.format(Locale.ENGLISH, "%s in %s", e.getClass().getSimpleName(), stackTraceElements[0]);
        } else {
            message = "Error in " + e.getClass().getSimpleName();
        }
    } else {
        message = e.getClass().getSimpleName() + ": " + message;
    }
    return new SQLActionException(message, errorCode, restStatus, e.getStackTrace());
}
Also used : SQLActionException(io.crate.action.sql.SQLActionException) MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException) RestStatus(org.elasticsearch.rest.RestStatus) ParsingException(io.crate.sql.parser.ParsingException) MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException)

Example 28 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project nifi by apache.

the class TestDeleteElasticsearch5 method testDeleteSuccessful.

@Test
public void testDeleteSuccessful() throws IOException {
    restStatus = RestStatus.OK;
    deleteResponse = new DeleteResponse(null, TYPE1, documentId, 1, true) {

        @Override
        public RestStatus status() {
            return restStatus;
        }
    };
    runner.enqueue(new byte[] {}, new HashMap<String, String>() {

        {
            put("documentId", documentId);
        }
    });
    runner.run(1, true, true);
    runner.assertAllFlowFilesTransferred(DeleteElasticsearch5.REL_SUCCESS, 1);
    final MockFlowFile out = runner.getFlowFilesForRelationship(DeleteElasticsearch5.REL_SUCCESS).get(0);
    assertNotNull(out);
    assertEquals(null, out.getAttribute(DeleteElasticsearch5.ES_ERROR_MESSAGE));
    out.assertAttributeEquals(DeleteElasticsearch5.ES_FILENAME, documentId);
    out.assertAttributeEquals(DeleteElasticsearch5.ES_INDEX, INDEX1);
    out.assertAttributeEquals(DeleteElasticsearch5.ES_TYPE, TYPE1);
}
Also used : MockFlowFile(org.apache.nifi.util.MockFlowFile) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) RestStatus(org.elasticsearch.rest.RestStatus) Test(org.junit.Test)

Example 29 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project baseio by generallycloud.

the class TestPut method test.

@SuppressWarnings("resource")
public static void test() throws Exception {
    Settings esSettings = Settings.builder().build();
    /*
          这里的连接方式指的是没有安装x-pack插件,如果安装了x-pack则参考{@link ElasticsearchXPackClient}
          1. java客户端的方式是以tcp协议在9300端口上进行通信
          2. http客户端的方式是以http协议在9200端口上进行通信
         */
    TransportClient client = new PreBuiltTransportClient(esSettings).addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
    System.out.println("ElasticsearchClient 连接成功");
    String index = "twitter";
    IndexResponse putResponse = client.prepareIndex(index, "tweet", "1").setSource(jsonBuilder().startObject().field("user", "kimchy").field("postDate", new Date()).field("message", "trying out Elasticsearch").endObject()).get();
    // Index name
    String _index = putResponse.getIndex();
    // Type name
    String _type = putResponse.getType();
    // Document ID (generated or not)
    String _id = putResponse.getId();
    // Version (if it's the first time you index this document, you will get: 1)
    long _version = putResponse.getVersion();
    // status has stored current instance statement.
    RestStatus status = putResponse.status();
    System.out.println(_index);
    System.out.println(_type);
    System.out.println(_id);
    System.out.println(_version);
    System.out.println(status);
    GetRequest getRequest = new GetRequest("twitter", _type, _id);
    GetResponse getResponse = client.get(getRequest).get();
    System.out.println(getResponse.getSource());
    client.close();
}
Also used : TransportClient(org.elasticsearch.client.transport.TransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) RestStatus(org.elasticsearch.rest.RestStatus) IndexResponse(org.elasticsearch.action.index.IndexResponse) TransportAddress(org.elasticsearch.common.transport.TransportAddress) GetRequest(org.elasticsearch.action.get.GetRequest) GetResponse(org.elasticsearch.action.get.GetResponse) Settings(org.elasticsearch.common.settings.Settings) Date(java.util.Date)

Example 30 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project flink by apache.

the class ElasticsearchWriter method extractFailures.

private void extractFailures(BulkRequest request, BulkResponse response) {
    if (!response.hasFailures()) {
        pendingActions -= request.numberOfActions();
        return;
    }
    Throwable chainedFailures = null;
    for (int i = 0; i < response.getItems().length; i++) {
        final BulkItemResponse itemResponse = response.getItems()[i];
        if (!itemResponse.isFailed()) {
            continue;
        }
        final Throwable failure = itemResponse.getFailure().getCause();
        if (failure == null) {
            continue;
        }
        final RestStatus restStatus = itemResponse.getFailure().getStatus();
        final DocWriteRequest<?> actionRequest = request.requests().get(i);
        chainedFailures = firstOrSuppressed(wrapException(restStatus, failure, actionRequest), chainedFailures);
    }
    if (chainedFailures == null) {
        return;
    }
    throw new FlinkRuntimeException(chainedFailures);
}
Also used : RestStatus(org.elasticsearch.rest.RestStatus) FlinkRuntimeException(org.apache.flink.util.FlinkRuntimeException) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse)

Aggregations

RestStatus (org.elasticsearch.rest.RestStatus)32 IOException (java.io.IOException)17 ElasticsearchException (org.elasticsearch.ElasticsearchException)12 MainResponse (org.elasticsearch.action.main.MainResponse)11 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)10 Version (org.elasticsearch.Version)9 HttpHost (org.apache.http.HttpHost)8 HttpResponse (org.apache.http.HttpResponse)8 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)8 List (java.util.List)7 HttpEntity (org.apache.http.HttpEntity)7 StringEntity (org.apache.http.entity.StringEntity)7 Build (org.elasticsearch.Build)7 ActionListener (org.elasticsearch.action.ActionListener)7 ClusterName (org.elasticsearch.cluster.ClusterName)7 Collections (java.util.Collections)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 ActionRequestValidationException (org.elasticsearch.action.ActionRequestValidationException)6 JsonParseException (com.fasterxml.jackson.core.JsonParseException)5 SocketTimeoutException (java.net.SocketTimeoutException)5