org.elasticsearch.rest.RestStatus Java Examples
The following examples show how to use
org.elasticsearch.rest.RestStatus.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValidatingDispatcher.java From deprecated-security-ssl with Apache License 2.0 | 6 votes |
protected void checkRequest(final RestRequest request, final RestChannel channel) { if(SSLRequestHelper.containsBadHeader(threadContext, "_opendistro_security_ssl_")) { final ElasticsearchException exception = ExceptionUtils.createBadHeaderException(); errorHandler.logError(exception, request, 1); throw exception; } try { if(SSLRequestHelper.getSSLInfo(settings, configPath, request, null) == null) { logger.error("Not an SSL request"); throw new ElasticsearchSecurityException("Not an SSL request", RestStatus.INTERNAL_SERVER_ERROR); } } catch (SSLPeerUnverifiedException e) { logger.error("No client certificates found but such are needed (Security 8)."); errorHandler.logError(e, request, 0); throw ExceptionsHelper.convertToElastic(e); } }
Example #2
Source File: ESTemplate.java From canal-1.1.3 with Apache License 2.0 | 6 votes |
/** * 提交批次 */ public void commit() { if (getBulk().numberOfActions() > 0) { BulkResponse response = getBulk().execute().actionGet(); if (response.hasFailures()) { for (BulkItemResponse itemResponse : response.getItems()) { if (!itemResponse.isFailed()) { continue; } if (itemResponse.getFailure().getStatus() == RestStatus.NOT_FOUND) { logger.error(itemResponse.getFailureMessage()); } else { throw new RuntimeException("ES sync commit error" + itemResponse.getFailureMessage()); } } } } }
Example #3
Source File: CreateRepositoryAnalyzer.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override public CreateRepositoryAnalyzedStatement visitCreateRepository(CreateRepository node, Analysis context) { // Add SQL Authentication // GaoPan 2016/06/16 AuthResult authResult = AuthService.sqlAuthenticate(context.parameterContext().getLoginUserContext(), VirtualTableNames.sys.name(), VirtualTableNames.repositories.name(), PrivilegeType.READ_WRITE); if (authResult.getStatus() != RestStatus.OK) { throw new NoPermissionException(authResult.getStatus().getStatus(), authResult.getMessage()); } String repositoryName = node.repository(); if (repositoryService.getRepository(repositoryName) != null) { throw new RepositoryAlreadyExistsException(repositoryName); } Settings settings = repositoryParamValidator.convertAndValidate( node.type(), node.properties(), context.parameterContext()); return new CreateRepositoryAnalyzedStatement(repositoryName, node.type(), settings); }
Example #4
Source File: ElasticsearchSystemProducerTest.java From samza with Apache License 2.0 | 6 votes |
@Test public void testIgnoreVersionConficts() throws Exception { ArgumentCaptor<BulkProcessor.Listener> listenerCaptor = ArgumentCaptor.forClass(BulkProcessor.Listener.class); when(BULK_PROCESSOR_FACTORY.getBulkProcessor(eq(CLIENT), listenerCaptor.capture())) .thenReturn(processorOne); producer.register(SOURCE_ONE); BulkResponse response = getRespWithFailedDocument(RestStatus.CONFLICT); listenerCaptor.getValue().afterBulk(0, null, response); assertEquals(1, metrics.conflicts.getCount()); producer.flush(SOURCE_ONE); }
Example #5
Source File: TestDeleteElasticsearch5.java From nifi with Apache License 2.0 | 6 votes |
@Test public void testDeleteServerFailure() throws IOException { restStatus = RestStatus.SERVICE_UNAVAILABLE; 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_FAILURE, 1); final MockFlowFile out = runner.getFlowFilesForRelationship(DeleteElasticsearch5.REL_FAILURE).get(0); assertNotNull(out); assertEquals(DeleteElasticsearch5.UNABLE_TO_DELETE_DOCUMENT_MESSAGE,out.getAttribute(DeleteElasticsearch5.ES_ERROR_MESSAGE)); out.assertAttributeEquals(DeleteElasticsearch5.ES_REST_STATUS, restStatus.toString()); out.assertAttributeEquals(DeleteElasticsearch5.ES_FILENAME, documentId); out.assertAttributeEquals(DeleteElasticsearch5.ES_INDEX, INDEX1); out.assertAttributeEquals(DeleteElasticsearch5.ES_TYPE, TYPE1); }
Example #6
Source File: ElasticsearchRequestSubmitterTest.java From metron with Apache License 2.0 | 6 votes |
@Test public void searchShouldSucceedWhenOK() throws InvalidSearchException, IOException { // mocks SearchResponse response = mock(SearchResponse.class); SearchRequest request = new SearchRequest(); // response will indicate 1 search hit SearchHits hits = mock(SearchHits.class); when(hits.getTotalHits()).thenReturn(1L); // response will have status of OK and no failed shards when(response.status()).thenReturn(RestStatus.OK); when(response.getFailedShards()).thenReturn(0); when(response.getTotalShards()).thenReturn(2); when(response.getHits()).thenReturn(hits); // search should succeed ElasticsearchRequestSubmitter submitter = setup(response); SearchResponse actual = submitter.submitSearch(request); assertNotNull(actual); }
Example #7
Source File: ElasticsearchClientTransport.java From c2mon with GNU Lesser General Public License v3.0 | 6 votes |
@Override public boolean indexData(IndexMetadata indexMetadata, String data) { IndexRequest indexRequest = new IndexRequest(indexMetadata.getName(), TYPE); if (indexMetadata.getId() != null && !indexMetadata.getId().isEmpty()) { indexRequest.id(indexMetadata.getId()); } indexRequest.source(data, XContentType.JSON); indexRequest.routing(indexMetadata.getRouting()); try { IndexResponse indexResponse = client.index(indexRequest).get(); return indexResponse.status().equals(RestStatus.CREATED) || indexResponse.status().equals(RestStatus.OK); } catch (InterruptedException | ExecutionException e) { log.error("Error indexing '#{}' to '{}'.", indexMetadata.getId(), indexMetadata.getName(), e); } return false; }
Example #8
Source File: IndexAuthenticator.java From elasticsearch-auth with Apache License 2.0 | 6 votes |
@Override public void deleteUser(final String username, final ActionListener<Void> listener) { client.prepareDelete(authIndex, userType, getUserId(username)) .setRefresh(true).execute(new ActionListener<DeleteResponse>() { @Override public void onResponse(final DeleteResponse response) { if (response.isFound()) { listener.onResponse(null); } else { listener.onFailure(new AuthException( RestStatus.BAD_REQUEST, "Could not delete " + username)); } } @Override public void onFailure(final Throwable e) { listener.onFailure(new AuthException( RestStatus.INTERNAL_SERVER_ERROR, "Could not delete " + username, e)); } }); }
Example #9
Source File: AuthService.java From elasticsearch-auth with Apache License 2.0 | 6 votes |
public void init(final ActionListener<Void> listener) { client.admin().cluster().prepareHealth().setWaitForYellowStatus() .execute(new ActionListener<ClusterHealthResponse>() { @Override public void onResponse(final ClusterHealthResponse response) { if (response.getStatus() == ClusterHealthStatus.RED) { listener.onFailure(new AuthException( RestStatus.SERVICE_UNAVAILABLE, "This cluster is not ready.")); } else { createConstraintIndexIfNotExist(listener); } } @Override public void onFailure(final Throwable e) { listener.onFailure(e); } }); }
Example #10
Source File: ESTest.java From canal with Apache License 2.0 | 6 votes |
private void commit(BulkRequestBuilder bulkRequestBuilder) { if (bulkRequestBuilder.numberOfActions() > 0) { BulkResponse response = bulkRequestBuilder.execute().actionGet(); if (response.hasFailures()) { for (BulkItemResponse itemResponse : response.getItems()) { if (!itemResponse.isFailed()) { continue; } if (itemResponse.getFailure().getStatus() == RestStatus.NOT_FOUND) { System.out.println(itemResponse.getFailureMessage()); } else { System.out.println("ES bulk commit error" + itemResponse.getFailureMessage()); } } } } }
Example #11
Source File: AzureHttpHandler.java From crate with Apache License 2.0 | 6 votes |
private static String toAzureErrorCode(final RestStatus status) { assert status.getStatus() >= 400; switch (status) { case BAD_REQUEST: return "InvalidMetadata"; case NOT_FOUND: return "BlobNotFound"; case INTERNAL_SERVER_ERROR: return "InternalError"; case SERVICE_UNAVAILABLE: return "ServerBusy"; case CONFLICT: return "BlobAlreadyExists"; default: throw new IllegalArgumentException("Error code [" + status.getStatus() + "] is not mapped to an existing Azure code"); } }
Example #12
Source File: ReplicationResponse.java From crate with Apache License 2.0 | 5 votes |
public Failure(StreamInput in) throws IOException { shardId = new ShardId(in); super.shardId = shardId.getId(); index = shardId.getIndexName(); nodeId = in.readOptionalString(); cause = in.readException(); status = RestStatus.readFrom(in); primary = in.readBoolean(); }
Example #13
Source File: IndexAnomalyDetectorActionHandler.java From anomaly-detection with Apache License 2.0 | 5 votes |
private void onCreateMappingsResponse(CreateIndexResponse response) throws IOException { if (response.isAcknowledged()) { logger.info("Created {} with mappings.", ANOMALY_DETECTORS_INDEX); prepareAnomalyDetectorIndexing(); } else { logger.warn("Created {} with mappings call not acknowledged.", ANOMALY_DETECTORS_INDEX); channel .sendResponse( new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, response.toXContent(channel.newErrorBuilder(), EMPTY_PARAMS)) ); } }
Example #14
Source File: IndexAnomalyDetectorActionHandler.java From anomaly-detection with Apache License 2.0 | 5 votes |
private ActionListener<IndexResponse> indexAnomalyDetectorResponse() { return new RestResponseListener<IndexResponse>(channel) { @Override public RestResponse buildResponse(IndexResponse response) throws Exception { if (response.getShardInfo().getSuccessful() < 1) { return new BytesRestResponse(response.status(), response.toXContent(channel.newErrorBuilder(), EMPTY_PARAMS)); } XContentBuilder builder = channel .newBuilder() .startObject() .field(RestHandlerUtils._ID, response.getId()) .field(RestHandlerUtils._VERSION, response.getVersion()) .field(RestHandlerUtils._SEQ_NO, response.getSeqNo()) .field(RestHandlerUtils._PRIMARY_TERM, response.getPrimaryTerm()) .field("anomaly_detector", anomalyDetector) .endObject(); BytesRestResponse restResponse = new BytesRestResponse(response.status(), builder); if (response.status() == RestStatus.CREATED) { String location = String.format(Locale.ROOT, "%s/%s", AnomalyDetectorPlugin.AD_BASE_URI, response.getId()); restResponse.addHeader("Location", location); } return restResponse; } }; }
Example #15
Source File: SnapshotShardFailure.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public void readFrom(StreamInput in) throws IOException { nodeId = in.readOptionalString(); index = in.readString(); shardId = in.readVInt(); reason = in.readString(); status = RestStatus.readFrom(in); }
Example #16
Source File: ElasticsearchClientRest.java From c2mon with GNU Lesser General Public License v3.0 | 5 votes |
@Override public boolean deleteIndex(IndexMetadata indexMetadata) { try { DeleteRequest deleteRequest = new DeleteRequest(indexMetadata.getName(), TYPE, indexMetadata.getId()); deleteRequest.routing(indexMetadata.getRouting()); DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT); return deleteResponse.status().equals(RestStatus.OK); } catch (IOException e) { log.error("Error deleting '{}' index from ElasticSearch.", indexMetadata.getName(), e); } return false; }
Example #17
Source File: SnapshotShardFailure.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(nodeId); out.writeString(index); out.writeVInt(shardId); out.writeString(reason); RestStatus.writeTo(out, status); }
Example #18
Source File: CreateTenantStatementAnalyzer.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public CreateTenantAnalyzedStatement visitCreateTenant(CreateTenant node, Analysis context) { // Add SQL Authentication UserProperty currentOperateUser = context.parameterContext().userProperty(); if (!currentOperateUser.getUsernameWithoutTenant().equalsIgnoreCase(UserProperty.ROOT_NAME)) { throw new NoPermissionException(RestStatus.FORBIDDEN.getStatus(), "only root have permission to create tenant"); } Settings settings = GenericPropertiesConverter.settingsFromProperties( node.properties(), context.parameterContext(), SETTINGS).build(); CreateTenantAnalyzedStatement statement = new CreateTenantAnalyzedStatement(node.name(), settings.get(TenantSettings.SUPERUSER_PASSWORD.name()), settings.getAsInt(TenantSettings.NUMBER_OF_INSTANCES.name(), TenantSettings.NUMBER_OF_INSTANCES.defaultValue()), settings.get(TenantSettings.INSTANCE_LIST.name())); return statement; }
Example #19
Source File: DropBlobTableStatementAnalyzer.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public DropBlobTableAnalyzedStatement visitDropBlobTable(DropBlobTable node, Analysis analysis) { DropBlobTableAnalyzedStatement statement = new DropBlobTableAnalyzedStatement(schemas, node.ignoreNonExistentTable()); statement.table(tableToIdent(node.table())); // Add SQL Authentication // GaoPan 2016/06/16 AuthResult authResult = AuthService.sqlAuthenticate(analysis.parameterContext().getLoginUserContext(), statement.table().ident().schema(), null, PrivilegeType.READ_WRITE); if (authResult.getStatus() != RestStatus.OK) { throw new NoPermissionException(authResult.getStatus().getStatus(), authResult.getMessage()); } return statement; }
Example #20
Source File: RestStatsAnomalyDetectorAction.java From anomaly-detection with Apache License 2.0 | 5 votes |
/** * Listener sends response once Node Stats and Cluster Stats are gathered * * @param channel Channel * @return ActionListener for ADStatsResponse */ private ActionListener<ADStatsResponse> getRestStatsListener(RestChannel channel) { return ActionListener .wrap( adStatsResponse -> { channel.sendResponse(new BytesRestResponse(RestStatus.OK, adStatsResponse.toXContent(channel.newBuilder()))); }, exception -> channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, exception.getMessage())) ); }
Example #21
Source File: ElasticJoinExecutor.java From elasticsearch-sql with Apache License 2.0 | 5 votes |
public void sendResponse(RestChannel channel){ try { XContentBuilder builder = ElasticUtils.hitsAsXContentBuilder(results,metaResults); BytesRestResponse bytesRestResponse = new BytesRestResponse(RestStatus.OK, builder); channel.sendResponse(bytesRestResponse); } catch (IOException e) { e.printStackTrace(); } }
Example #22
Source File: SearchService.java From jakduk-api with MIT License | 5 votes |
public void deleteDocumentGallery(String id) { DeleteResponse response = client.prepareDelete() .setIndex(elasticsearchProperties.getIndexGallery()) .setType(Constants.ES_TYPE_GALLERY) .setId(id) .get(); if (! response.status().equals(RestStatus.OK)) log.info("gallery id {} is not found. so can't delete it!", id); }
Example #23
Source File: AnomalyDetectorRestApiIT.java From anomaly-detection with Apache License 2.0 | 5 votes |
public void testPreviewAnomalyDetector() throws Exception { AnomalyDetector detector = createRandomAnomalyDetector(true, false); AnomalyDetectorExecutionInput input = new AnomalyDetectorExecutionInput( detector.getDetectorId(), Instant.now().minusSeconds(60 * 10), Instant.now(), null ); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false); Exception ex = expectThrows( ResponseException.class, () -> TestHelpers .makeRequest( client(), "POST", String.format(AD_BASE_PREVIEW_URI, input.getDetectorId()), ImmutableMap.of(), toHttpEntity(input), null ) ); assertThat(ex.getMessage(), containsString(CommonErrorMessages.DISABLED_ERR_MSG)); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, true); Response response = TestHelpers .makeRequest( client(), "POST", String.format(AD_BASE_PREVIEW_URI, input.getDetectorId()), ImmutableMap.of(), toHttpEntity(input), null ); assertEquals("Execute anomaly detector failed", RestStatus.OK, restStatus(response)); }
Example #24
Source File: DefaultShardOperationFailedException.java From crate with Apache License 2.0 | 5 votes |
@Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(index); out.writeVInt(shardId); out.writeException(cause); RestStatus.writeTo(out, status); }
Example #25
Source File: ExceptionsHelper.java From Elasticsearch with Apache License 2.0 | 5 votes |
public static RestStatus status(Throwable t) { if (t != null) { if (t instanceof ElasticsearchException) { return ((ElasticsearchException) t).status(); } else if (t instanceof IllegalArgumentException) { return RestStatus.BAD_REQUEST; } } return RestStatus.INTERNAL_SERVER_ERROR; }
Example #26
Source File: AnomalyDetectorRestApiIT.java From anomaly-detection with Apache License 2.0 | 5 votes |
public void testDeleteAnomalyDetectorWithRunningAdJob() throws Exception { AnomalyDetector detector = createRandomAnomalyDetector(true, false); Response startAdJobResponse = TestHelpers .makeRequest( client(), "POST", TestHelpers.AD_BASE_DETECTORS_URI + "/" + detector.getDetectorId() + "/_start", ImmutableMap.of(), "", null ); assertEquals("Fail to start AD job", RestStatus.OK, restStatus(startAdJobResponse)); TestHelpers .assertFailWith( ResponseException.class, "Detector job is running", () -> TestHelpers .makeRequest( client(), "DELETE", TestHelpers.AD_BASE_DETECTORS_URI + "/" + detector.getDetectorId(), ImmutableMap.of(), "", null ) ); }
Example #27
Source File: ElasticsearchAssertions.java From crate with Apache License 2.0 | 5 votes |
/** * Run future.actionGet() and check that it throws an exception of the right type, optionally checking the exception's rest status * * @param exceptionClass expected exception class * @param status {@link org.elasticsearch.rest.RestStatus} to check for. Can be null to disable the check * @param extraInfo extra information to add to the failure message. Can be null. */ public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass, @Nullable RestStatus status, @Nullable String extraInfo) { boolean fail = false; extraInfo = extraInfo == null || extraInfo.isEmpty() ? "" : extraInfo + ": "; extraInfo += "expected a " + exceptionClass + " exception to be thrown"; if (status != null) { extraInfo += " with status [" + status + "]"; } try { future.actionGet(); fail = true; } catch (ElasticsearchException esException) { assertThat(extraInfo, esException.unwrapCause(), instanceOf(exceptionClass)); if (status != null) { assertThat(extraInfo, ExceptionsHelper.status(esException), equalTo(status)); } } catch (Exception e) { assertThat(extraInfo, e, instanceOf(exceptionClass)); if (status != null) { assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status)); } } // has to be outside catch clause to get a proper message if (fail) { throw new AssertionError(extraInfo); } }
Example #28
Source File: JobRestHandler.java From elasticsearch-rest-command with The Unlicense | 5 votes |
@Override public RestResponse buildResponse(SearchResponse result, XContentBuilder builder) throws Exception { Response resp = new Response(); resp.type = ResponseType.SearchResponse; resp.search = result; resp.fieldNames = search.tableFieldNames; queryResultCache.put(retId, resp); Search.buildQuery(from, builder, result, logger, search.tableFieldNames, showMeta); return new BytesRestResponse(RestStatus.OK, builder); }
Example #29
Source File: RestApiTest.java From siren-join with GNU Affero General Public License v3.0 | 5 votes |
@Test public void testCoordinateSearchApi() throws IOException, RestException, ExecutionException, InterruptedException { assertAcked(prepareCreate("index1").addMapping("type", "id", "type=string", "foreign_key", "type=string")); assertAcked(prepareCreate("index2").addMapping("type", "id", "type=string", "tag", "type=string")); ensureGreen(); indexRandom(true, client().prepareIndex("index1", "type", "1").setSource("id", "1", "foreign_key", new String[]{"1", "3"}), client().prepareIndex("index1", "type", "2").setSource("id", "2"), client().prepareIndex("index1", "type", "3").setSource("id", "3", "foreign_key", new String[]{"2"}), client().prepareIndex("index1", "type", "4").setSource("id", "4", "foreign_key", new String[]{"1", "4"}), client().prepareIndex("index2", "type", "1").setSource("id", "1", "tag", "aaa"), client().prepareIndex("index2", "type", "2").setSource("id", "2", "tag", "aaa"), client().prepareIndex("index2", "type", "3").setSource("id", "3", "tag", "bbb"), client().prepareIndex("index2", "type", "4").setSource("id", "4", "tag", "ccc") ); // Check body search query with filter join String q = boolQuery().filter( filterJoin("foreign_key").indices("index2").types("type").path("id").query( boolQuery().filter(termQuery("tag", "aaa")) )).toString(); String body = "{ \"query\" : " + q + "}"; HttpResponse response = httpClient().method("GET").path("/_coordinate_search").body(body).execute(); assertThat(response.getStatusCode(), equalTo(RestStatus.OK.getStatus())); Map<String, Object> map = XContentHelper.convertToMap(new BytesArray(response.getBody().getBytes("UTF-8")), false).v2(); assertThat((Integer) ((Map) map.get("hits")).get("total"), equalTo(3)); // Check uri search response = httpClient().method("GET").path("/_coordinate_search").addParam("q", "tag:aaa").execute(); assertThat(response.getStatusCode(), equalTo(RestStatus.OK.getStatus())); map = XContentHelper.convertToMap(new BytesArray(response.getBody().getBytes("UTF-8")), false).v2(); assertThat((Integer) ((Map) map.get("hits")).get("total"), equalTo(2)); }
Example #30
Source File: AccountRestAction.java From elasticsearch-auth with Apache License 2.0 | 5 votes |
@Override protected void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { final BytesReference content = request.content(); final XContentType xContentType = XContentFactory.xContentType(content); XContentParser parser = null; String authenticator = null; String username = null; String password = null; String[] roles = null; try { parser = XContentFactory.xContent(xContentType).createParser( content); final XContentParser.Token t = parser.nextToken(); if (t != null) { final Map<String, Object> contentMap = parser.map(); authenticator = MapUtil.getAsString(contentMap, "authenticator", null); username = MapUtil.getAsString(contentMap, "username", null); password = MapUtil.getAsString(contentMap, "password", null); roles = MapUtil.getAsArray(contentMap, "roles", new String[0]); } } catch (final Exception e) { logger.error("Could not parse the content.", e); ResponseUtil.send(request, channel, RestStatus.BAD_REQUEST, "message", "Could not parse the content."); return; } finally { if (parser != null) { parser.close(); } } processRequest(request, channel, authenticator, username, password, roles); }