Java Code Examples for org.elasticsearch.rest.RestStatus

The following examples show how to use org.elasticsearch.rest.RestStatus. These examples are extracted from open source projects. 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 Project: Elasticsearch   Source File: CreateRepositoryAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
@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 2
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 3
Source Project: elasticsearch-auth   Source File: AuthService.java    License: Apache License 2.0 6 votes vote down vote up
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 4
Source Project: metron   Source File: ElasticsearchRequestSubmitterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: samza   Source File: ElasticsearchSystemProducerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
Source Project: elasticsearch-auth   Source File: IndexAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: canal   Source File: ESTest.java    License: Apache License 2.0 6 votes vote down vote up
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 8
Source Project: canal-1.1.3   Source File: ESTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 提交批次
 */
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 9
Source Project: crate   Source File: AzureHttpHandler.java    License: Apache License 2.0 6 votes vote down vote up
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 10
@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 11
Source Project: nifi   Source File: TestDeleteElasticsearch5.java    License: Apache License 2.0 6 votes vote down vote up
@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 12
@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 13
Source Project: Elasticsearch   Source File: ShardSearchFailure.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void readFrom(StreamInput in) throws IOException {
    if (in.readBoolean()) {
        shardTarget = readSearchShardTarget(in);
    }
    reason = in.readString();
    status = RestStatus.readFrom(in);
    cause = in.readThrowable();
}
 
Example 14
@Test
public void badUnsolicitedSsoTest() throws Exception {
    mockSamlIdpServer.setSignResponses(true);
    mockSamlIdpServer.loadSigningKeys("saml/kirk-keystore.jks", "kirk");
    mockSamlIdpServer.setAuthenticateUser("horst");
    mockSamlIdpServer.setEndpointQueryString(null);
    mockSamlIdpServer.setDefaultAssertionConsumerService("http://wherever/opendistrosecurity/saml/acs/idpinitiated");

    Settings settings = Settings.builder().put("idp.metadata_url", mockSamlIdpServer.getMetadataUri())
            .put("kibana_url", "http://wherever").put("idp.entity_id", mockSamlIdpServer.getIdpEntityId())
            .put("exchange_key", "abc").put("roles_key", "roles").put("path.home", ".").build();

    HTTPSamlAuthenticator samlAuthenticator = new HTTPSamlAuthenticator(settings, null);

    String encodedSamlResponse = mockSamlIdpServer.createUnsolicitedSamlResponse();

    AuthenticateHeaders authenticateHeaders = new AuthenticateHeaders("http://wherever/opendistrosecurity/saml/acs/",
            "wrong_request_id");

    RestRequest tokenRestRequest = buildTokenExchangeRestRequest(encodedSamlResponse, authenticateHeaders,
            "/opendistrosecurity/saml/acs/idpinitiated");
    TestRestChannel tokenRestChannel = new TestRestChannel(tokenRestRequest);

    samlAuthenticator.reRequestAuthentication(tokenRestChannel, null);

    Assert.assertEquals(RestStatus.UNAUTHORIZED, tokenRestChannel.response.status());
}
 
Example 15
Source Project: samza   Source File: ElasticsearchSystemProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = SamzaException.class)
public void testFlushFailedSendFromFailedDocument() 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.BAD_REQUEST);

  listenerCaptor.getValue().afterBulk(0, null, response);

  producer.flush(SOURCE_ONE);
}
 
Example 16
private void sendDefaultResponse(SearchHits hits, RestChannel channel) {
    try {
        XContentBuilder builder = ElasticUtils.hitsAsXContentBuilder(hits, new MetaSearchResult());
        BytesRestResponse bytesRestResponse = new BytesRestResponse(RestStatus.OK, builder);
        channel.sendResponse(bytesRestResponse);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 17
Source Project: samza   Source File: ElasticsearchSystemProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
private BulkResponse getRespWithFailedDocument(RestStatus status) {
  BulkResponse response = mock(BulkResponse.class);
  when(response.hasFailures()).thenReturn(true);

  BulkItemResponse itemResp = mock(BulkItemResponse.class);
  when(itemResp.isFailed()).thenReturn(true);
  BulkItemResponse.Failure failure = mock(BulkItemResponse.Failure.class);
  when(failure.getStatus()).thenReturn(status);
  when(itemResp.getFailure()).thenReturn(failure);
  BulkItemResponse[] itemResponses = new BulkItemResponse[]{itemResp};

  when(response.getItems()).thenReturn(itemResponses);

  return response;
}
 
Example 18
Source Project: Elasticsearch   Source File: SetStatementAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
public static ResetAnalyzedStatement analyze(ResetStatement node, ParameterContext parameterContext) {

        // Add SQL Authentication
        // GaoPan 2016/06/16
        AuthResult authResult = AuthService.sqlAuthenticate(parameterContext.getLoginUserContext(),
                VirtualTableNames.sys.name(), VirtualTableNames.cluster.name(), PrivilegeType.READ_WRITE);
        if (authResult.getStatus() != RestStatus.OK) {
            throw new NoPermissionException(authResult.getStatus().getStatus(), authResult.getMessage());
        }

        Set<String> settingsToRemove = Sets.newHashSet();
        for (Expression expression : node.columns()) {
            String settingsName = ExpressionToStringVisitor.convert(expression, parameterContext.parameters());
            if (!settingsToRemove.contains(settingsName)) {
                Set<String> settingNames = CrateSettings.settingNamesByPrefix(settingsName);
                if (settingNames.size() == 0) {
                    throw new IllegalArgumentException(String.format(Locale.ENGLISH, "setting '%s' not supported", settingsName));
                }
                for (String setting : settingNames) {
                    checkIfSettingIsRuntime(setting);
                }
                settingsToRemove.addAll(settingNames);
                logger.info("resetting [{}]", settingNames);
            }
        }
        return new ResetAnalyzedStatement(settingsToRemove);
    }
 
Example 19
@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 Project: Elasticsearch   Source File: SnapshotShardFailure.java    License: Apache License 2.0 5 votes vote down vote up
@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 21
Source Project: Elasticsearch   Source File: SnapshotShardFailure.java    License: Apache License 2.0 5 votes vote down vote up
@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 22
@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 23
Source Project: crate   Source File: ReplicationResponse.java    License: Apache License 2.0 5 votes vote down vote up
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 24
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 25
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 26
/**
 * 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 27
Source Project: elasticsearch-sql   Source File: ElasticJoinExecutor.java    License: Apache License 2.0 5 votes vote down vote up
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 28
Source Project: jakduk-api   Source File: SearchService.java    License: MIT License 5 votes vote down vote up
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 29
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 30
Source Project: Elasticsearch   Source File: ExceptionsHelper.java    License: Apache License 2.0 5 votes vote down vote up
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;
}