当前位置: 首页>>代码示例>>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;未经允许,请勿转载。