當前位置: 首頁>>代碼示例>>Java>>正文


Java RestStatus類代碼示例

本文整理匯總了Java中org.elasticsearch.rest.RestStatus的典型用法代碼示例。如果您正苦於以下問題:Java RestStatus類的具體用法?Java RestStatus怎麽用?Java RestStatus使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


RestStatus類屬於org.elasticsearch.rest包,在下文中一共展示了RestStatus類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testXContentBuilderClosedInBuildResponse

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
public void testXContentBuilderClosedInBuildResponse() throws Exception {
    AtomicReference<XContentBuilder> builderAtomicReference = new AtomicReference<>();
    RestBuilderListener<TransportResponse.Empty> builderListener =
        new RestBuilderListener<Empty>(new FakeRestChannel(new FakeRestRequest(), randomBoolean(), 1)) {
            @Override
            public RestResponse buildResponse(Empty empty, XContentBuilder builder) throws Exception {
                builderAtomicReference.set(builder);
                builder.close();
                return new BytesRestResponse(RestStatus.OK, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY);
            }
    };

    builderListener.buildResponse(Empty.INSTANCE);
    assertNotNull(builderAtomicReference.get());
    assertTrue(builderAtomicReference.get().generator().isClosed());
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:17,代碼來源:RestBuilderListenerTests.java

示例2: testHeadResponse

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
public void testHeadResponse() throws Exception {
    final String nodeName = "node1";
    final ClusterName clusterName = new ClusterName("cluster1");
    final String clusterUUID = randomAsciiOfLengthBetween(10, 20);
    final boolean available = randomBoolean();
    final RestStatus expectedStatus = available ? RestStatus.OK : RestStatus.SERVICE_UNAVAILABLE;
    final Version version = Version.CURRENT;
    final Build build = Build.CURRENT;

    final MainResponse mainResponse = new MainResponse(nodeName, version, clusterName, clusterUUID, build, available);
    XContentBuilder builder = JsonXContent.contentBuilder();
    RestRequest restRequest = new FakeRestRequest() {
        @Override
        public Method method() {
            return Method.HEAD;
        }
    };

    BytesRestResponse response = RestMainAction.convertMainResponse(mainResponse, restRequest, builder);
    assertNotNull(response);
    assertEquals(expectedStatus, response.status());

    // the empty responses are handled in the HTTP layer so we do
    // not assert on them here
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:26,代碼來源:RestMainActionTests.java

示例3: respIpForbidden

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
public static void respIpForbidden(final HttpRequest request, final HttpChannel channel, ESLogger logger) {
	XContentBuilder builder;
	try {
		builder = ContentBuilder.restContentBuilder(request);
		builder.startObject()  
        .field(new XContentBuilderString("status"), RestStatus.FORBIDDEN)  
        .field(new XContentBuilderString("message"),  
                "Your ip is not in auth list")  
        .endObject();
		
		channel.sendResponse(  
                new BytesRestResponse(RestStatus.FORBIDDEN, builder)); 
	} catch (IOException e) {
		if (logger != null) {
			logger.error("Get Exception in checkIpPermission: " + e.getMessage());
		}
		e.printStackTrace();
	}
}
 
開發者ID:ghostboyzone,項目名稱:ESAuthPlugin,代碼行數:20,代碼來源:ContentBuilder.java

示例4: apply

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
@Override
public <Request extends ActionRequest, Response extends ActionResponse> void apply(Task task, String action,
        Request request, ActionListener<Response> listener, ActionFilterChain<Request, Response> chain) {
    if (false == action.equals(SearchAction.NAME)) {
        chain.proceed(task, action, request, listener);
        return;
    }
    if (context.getHeader(EXAMPLE_HEADER) != null) {
        throw new IllegalArgumentException("Hurray! Sent the header!");
    }
    String auth = context.getHeader(AUTHORIZATION_HEADER);
    if (auth == null) {
        ElasticsearchSecurityException e = new ElasticsearchSecurityException("Authentication required",
                RestStatus.UNAUTHORIZED);
        e.addHeader("WWW-Authenticate", "Basic realm=auth-realm");
        throw e;
    }
    if (false == REQUIRED_AUTH.equals(auth)) {
        throw new ElasticsearchSecurityException("Bad Authorization", RestStatus.FORBIDDEN);
    }
    chain.proceed(task, action, request, listener);
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:23,代碼來源:ReindexFromRemoteWithAuthTests.java

示例5: testXContentBuilderNotClosedInBuildResponseAssertionsDisabled

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
public void testXContentBuilderNotClosedInBuildResponseAssertionsDisabled() throws Exception {
    AtomicReference<XContentBuilder> builderAtomicReference = new AtomicReference<>();
    RestBuilderListener<TransportResponse.Empty> builderListener =
        new RestBuilderListener<Empty>(new FakeRestChannel(new FakeRestRequest(), randomBoolean(), 1)) {
            @Override
            public RestResponse buildResponse(Empty empty, XContentBuilder builder) throws Exception {
                builderAtomicReference.set(builder);
                return new BytesRestResponse(RestStatus.OK, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY);
            }

            @Override
            boolean assertBuilderClosed(XContentBuilder xContentBuilder) {
                // don't check the actual builder being closed so we can test auto close
                return true;
            }
    };

    builderListener.buildResponse(Empty.INSTANCE);
    assertNotNull(builderAtomicReference.get());
    assertTrue(builderAtomicReference.get().generator().isClosed());
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:22,代碼來源:RestBuilderListenerTests.java

示例6: testPerformRequestOnSuccess

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
public void testPerformRequestOnSuccess() 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));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenReturn(mockResponse);
    {
        Integer result = restHighLevelClient.performRequest(mainRequest, requestConverter,
                response -> response.getStatusLine().getStatusCode(), Collections.emptySet());
        assertEquals(restStatus.getStatus(), result.intValue());
    }
    {
        IOException ioe = expectThrows(IOException.class, () -> restHighLevelClient.performRequest(mainRequest,
                requestConverter, response -> {throw new IllegalStateException();}, Collections.emptySet()));
        assertEquals("Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " +
                "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage());
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:22,代碼來源:RestHighLevelClientTests.java

示例7: testPerformRequestOnResponseExceptionWithoutEntity

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
public void testPerformRequestOnResponseExceptionWithoutEntity() 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));
    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(responseException.getMessage(), elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getCause());
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:18,代碼來源:RestHighLevelClientTests.java

示例8: visitCreateRepository

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
@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);
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:21,代碼來源:CreateRepositoryAnalyzer.java

示例9: checkWriteAction

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
void checkWriteAction(boolean indexShouldBeAutoCreated, TimeValue timeout, ActionRequestBuilder<?, ?, ?> builder) {
    long now = System.currentTimeMillis();
    try {
        builder.get();
        fail("Expected ClusterBlockException");
    } catch (ClusterBlockException e) {
        if (indexShouldBeAutoCreated) {
            // timeout is 200
            assertThat(System.currentTimeMillis() - now, greaterThan(timeout.millis() - 50));
            assertThat(e.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
        } else {
            // timeout is 5000
            assertThat(System.currentTimeMillis() - now, lessThan(timeout.millis() + 300));
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:17,代碼來源:NoMasterNodeIT.java

示例10: testCreateSnapshotWithIndexBlocks

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
public void testCreateSnapshotWithIndexBlocks() {
    logger.info("-->  creating a snapshot is not blocked when an index is read only");
    try {
        enableIndexBlock(INDEX_NAME, SETTING_READ_ONLY);
        assertThat(client().admin().cluster().prepareCreateSnapshot(REPOSITORY_NAME, "snapshot-1").setIndices(COMMON_INDEX_NAME_MASK).setWaitForCompletion(true).get().status(), equalTo(RestStatus.OK));
    } finally {
        disableIndexBlock(INDEX_NAME, SETTING_READ_ONLY);
    }

    logger.info("-->  creating a snapshot is blocked when an index is blocked for reads");
    try {
        enableIndexBlock(INDEX_NAME, SETTING_BLOCKS_READ);
        assertBlocked(client().admin().cluster().prepareCreateSnapshot(REPOSITORY_NAME, "snapshot-2").setIndices(COMMON_INDEX_NAME_MASK), IndexMetaData.INDEX_READ_BLOCK);
        logger.info("-->  creating a snapshot is not blocked when an read-blocked index is not part of the snapshot");
        assertThat(client().admin().cluster().prepareCreateSnapshot(REPOSITORY_NAME, "snapshot-2").setIndices(OTHER_INDEX_NAME).setWaitForCompletion(true).get().status(), equalTo(RestStatus.OK));
    } finally {
        disableIndexBlock(INDEX_NAME, SETTING_BLOCKS_READ);
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:SnapshotBlocksIT.java

示例11: buildErrorResource

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
/**
 * Storage Error JSON representation
 */
private static String buildErrorResource(RestStatus status, String message) throws IOException {
    return jsonBuilder()
            .startObject()
                .startObject("error")
                    .field("code", status.getStatus())
                    .field("message", message)
                    .startArray("errors")
                        .startObject()
                            .field("domain", "global")
                            .field("reason", status.toString())
                            .field("message", message)
                        .endObject()
                    .endArray()
                .endObject()
            .endObject()
            .string();
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:21,代碼來源:MockHttpTransport.java

示例12: checkWhiteList

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
public static AuthResult checkWhiteList(String user, Set<String> addrs, Set<String> ipWhiteList) {
    for (String addr : addrs) {
        String userAndIp = user + "@" + addr;
        try {
            if (!userIpCache.get(userAndIp)) {
                boolean addrInWhiteList = false;
                for (String ip : ipWhiteList) {
                    if (matchIP(addr, ip)) {
                        addrInWhiteList = true;
                        userIpCache.put(userAndIp, true);
                        break;
                    }
                }
                if (!addrInWhiteList) {
                    return new AuthResult(RestStatus.UNAUTHORIZED, "proxy or source address is not in whitelist: " + addr);
                }
            }
        } catch (Exception e) {
            return new AuthResult(RestStatus.FORBIDDEN, "load cache occurs exceptions");
        }
    }
    return new AuthResult(RestStatus.OK, null);
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:24,代碼來源:AuthService.java

示例13: checkUpdateAction

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
void checkUpdateAction(boolean autoCreateIndex, TimeValue timeout, ActionRequestBuilder<?, ?, ?> builder) {
    // we clean the metadata when loosing a master, therefore all operations on indices will auto create it, if allowed
    long now = System.currentTimeMillis();
    try {
        builder.get();
        fail("expected ClusterBlockException or MasterNotDiscoveredException");
    } catch (ClusterBlockException | MasterNotDiscoveredException e) {
        if (e instanceof MasterNotDiscoveredException) {
            assertTrue(autoCreateIndex);
        } else {
            assertFalse(autoCreateIndex);
        }
        // verify we waited before giving up...
        assertThat(e.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
        assertThat(System.currentTimeMillis() - now, greaterThan(timeout.millis() - 50));
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:18,代碼來源:NoMasterNodeIT.java

示例14: visitAlterBlobTable

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
@Override
public AlterBlobTableAnalyzedStatement visitAlterBlobTable(AlterBlobTable node, Analysis analysis) {
    AlterBlobTableAnalyzedStatement statement = new AlterBlobTableAnalyzedStatement(schemas);

    statement.table(tableToIdent(node.table()));

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

    if (node.genericProperties().isPresent()) {
        TABLE_PROPERTIES_ANALYZER.analyze(
                statement.tableParameter(), statement.table().tableParameterInfo(),
                node.genericProperties(), analysis.parameterContext().parameters());
    } else if (!node.resetProperties().isEmpty()) {
        TABLE_PROPERTIES_ANALYZER.analyze(
                statement.tableParameter(), statement.table().tableParameterInfo(),
                node.resetProperties());
    }

    return statement;
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:27,代碼來源:AlterBlobTableAnalyzer.java

示例15: check

import org.elasticsearch.rest.RestStatus; //導入依賴的package包/類
static void check(SearchResponse response) {
    if (response.status() != RestStatus.OK) {
        throw new StarGraphException("ES failure. RestStatus is " + response.status());
    }
    if (response.getFailedShards() > 0) {
        throw new StarGraphException("Shard Search Failure.");
    }
}
 
開發者ID:Lambda-3,項目名稱:Stargraph,代碼行數:9,代碼來源:ESUtils.java


注:本文中的org.elasticsearch.rest.RestStatus類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。