当前位置: 首页>>代码示例>>Java>>正文


Java RestChannel类代码示例

本文整理汇总了Java中org.elasticsearch.rest.RestChannel的典型用法代码示例。如果您正苦于以下问题:Java RestChannel类的具体用法?Java RestChannel怎么用?Java RestChannel使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


RestChannel类属于org.elasticsearch.rest包,在下文中一共展示了RestChannel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: sendResponse

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
protected void sendResponse(final RestChannel channel, final Map<String, Object> params, final boolean pretty) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        if (pretty) {
            builder.prettyPrint();
        }
        builder.startObject();
        builder.field("acknowledged", true);
        if (params != null) {
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                builder.field(entry.getKey(), entry.getValue());
            }
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final IOException e) {
        throw new ElasticsearchException("Failed to create a resposne.", e);
    }
}
 
开发者ID:codelibs,项目名称:elasticsearch-indexing-proxy,代码行数:20,代码来源:RestIndexingProxyProcessAction.java

示例2: listTasksResponseListener

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
/**
 * Standard listener for extensions of {@link ListTasksResponse} that supports {@code group_by=nodes}.
 */
public static <T extends ListTasksResponse> ActionListener<T> listTasksResponseListener(
            Supplier<DiscoveryNodes> nodesInCluster,
            String groupBy,
            final RestChannel channel) {
    if ("nodes".equals(groupBy)) {
        return new RestBuilderListener<T>(channel) {
            @Override
            public RestResponse buildResponse(T response, XContentBuilder builder) throws Exception {
                builder.startObject();
                response.toXContentGroupedByNode(builder, channel.request(), nodesInCluster.get());
                builder.endObject();
                return new BytesRestResponse(RestStatus.OK, builder);
            }
        };
    } else if ("parents".equals(groupBy)) {
        return new RestToXContentListener<>(channel);
    } else {
        throw new IllegalArgumentException("[group_by] must be one of [nodes] or [parents] but was [" + groupBy + "]");
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:RestListTasksAction.java

示例3: buildXContentBuilder

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
public static RestResponse buildXContentBuilder(Table table, RestChannel channel) throws Exception {
    RestRequest request = channel.request();
    XContentBuilder builder = channel.newBuilder();
    List<DisplayHeader> displayHeaders = buildDisplayHeaders(table, request);

    builder.startArray();
    List<Integer> rowOrder = getRowOrder(table, request);
    for (Integer row : rowOrder) {
        builder.startObject();
        for (DisplayHeader header : displayHeaders) {
            builder.field(header.display, renderValue(request, table.getAsMap().get(header.name).get(row).value));
        }
        builder.endObject();
    }
    builder.endArray();
    return new BytesRestResponse(RestStatus.OK, builder);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:RestTable.java

示例4: send

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
public static void send(final RestChannel channel, final RestStatus status, final String message) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        builder.startObject()
                .field("status", status.getStatus())
                .field("message", message).endObject();
        BytesRestResponse bytesRestResponse = new BytesRestResponse(status, builder);
        if (status == RestStatus.UNAUTHORIZED) {
            bytesRestResponse.addHeader("WWW-authenticate", "Basic realm=\"Elasticsearch Authentication\"");
        }
        channel.sendResponse(bytesRestResponse);
    } catch (final IOException e) {
        logger.error("Failed to send a response.", e);
        try {
            channel.sendResponse(new BytesRestResponse(channel, e));
        } catch (final IOException e1) {
            logger.error("Failed to send a failure response.", e1);
        }
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:21,代码来源:ResponseUtil.java

示例5: process

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) {
    LoginUserContext user = null;
    request.putInContext(RestRequest.REQUEST_START_TIME, System.currentTimeMillis());
    try {
        user = new LoginUserContext(request, clusterService);
    } catch (NoPermissionException e) {
        logger.info("errors while parsing userinfo from request, error msg is [{}]", e.getMessage());
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, e.getMessage());
        return;
    }

    if (user.loginUsername() == null || user.loginUsername().length() ==0) {
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, "Username is empty");
        logger.info("Username is empty");
    }
    if (!user.authenticated() && (user.password() == null || user.password().length() ==0)) {
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, "Password is empty");
        logger.info("Password is empty");
    }
    // put user info into context
    request.putHeader(LoginUserContext.USER_INFO_KEY, user);
    filterChain.continueProcessing(request, channel);
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:24,代码来源:AuthRestFilter.java

示例6: handlePost

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
void handlePost(final RestRequest request, RestChannel channel, Client client) {
    UpgradeRequest upgradeReq = new UpgradeRequest(Strings.splitStringByCommaToArray(request.param("index")));
    upgradeReq.upgradeOnlyAncientSegments(request.paramAsBoolean("only_ancient_segments", false));
    client.admin().indices().upgrade(upgradeReq, new RestBuilderListener<UpgradeResponse>(channel) {
        @Override
        public RestResponse buildResponse(UpgradeResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            buildBroadcastShardsHeader(builder, request, response);
            builder.startObject("upgraded_indices");
            for (Map.Entry<String, Tuple<Version, String>> entry : response.versions().entrySet()) {
                builder.startObject(entry.getKey(), XContentBuilder.FieldCaseConversion.NONE);
                builder.field("upgrade_version", entry.getValue().v1());
                builder.field("oldest_lucene_segment_version", entry.getValue().v2());
                builder.endObject();
            }
            builder.endObject();
            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:22,代码来源:RestUpgradeAction.java

示例7: handleRequest

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    boolean detailed = request.paramAsBoolean("detailed", false);
    String[] nodesIds = Strings.splitStringByCommaToArray(request.param("node_id"));
    TaskId taskId = new TaskId(request.param("taskId"));
    String[] actions = Strings.splitStringByCommaToArray(request.param("actions"));
    TaskId parentTaskId = new TaskId(request.param("parent_task_id"));
    boolean waitForCompletion = request.paramAsBoolean("wait_for_completion", false);
    TimeValue timeout = request.paramAsTime("timeout", null);

    ListTasksRequest listTasksRequest = new ListTasksRequest();
    listTasksRequest.setTaskId(taskId);
    listTasksRequest.setNodesIds(nodesIds);
    listTasksRequest.setDetailed(detailed);
    listTasksRequest.setActions(actions);
    listTasksRequest.setParentTaskId(parentTaskId);
    listTasksRequest.setWaitForCompletion(waitForCompletion);
    listTasksRequest.setTimeout(timeout);
    client.admin().cluster().listTasks(listTasksRequest, new RestToXContentListener<ListTasksResponse>(channel));
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:21,代码来源:RestListTasksAction.java

示例8: doRequest

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
@Override
public void doRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    CountRequest countRequest = new CountRequest(indices);
    String source = request.param("source");
    if (source != null) {
        countRequest.source(source);
    } else {
        QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
        if (querySourceBuilder != null) {
            countRequest.source(querySourceBuilder);
        }
    }

    client.search(countRequest.toSearchRequest(), new RestResponseListener<SearchResponse>(channel) {
        @Override
        public RestResponse buildResponse(SearchResponse countResponse) throws Exception {
            return RestTable.buildResponse(buildTable(request, countResponse), channel);
        }
    });
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:22,代码来源:RestCountAction.java

示例9: doRequest

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
@Override
protected void doRequest(final RestRequest request, RestChannel channel, Client client) {
    GetSnapshotsRequest getSnapshotsRequest = new GetSnapshotsRequest()
            .repository(request.param("repository"))
            .snapshots(new String[]{GetSnapshotsRequest.ALL_SNAPSHOTS});

    getSnapshotsRequest.ignoreUnavailable(request.paramAsBoolean("ignore_unavailable", getSnapshotsRequest.ignoreUnavailable()));

    getSnapshotsRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getSnapshotsRequest.masterNodeTimeout()));

    client.admin().cluster().getSnapshots(getSnapshotsRequest, new RestResponseListener<GetSnapshotsResponse>(channel) {
        @Override
        public RestResponse buildResponse(GetSnapshotsResponse getSnapshotsResponse) throws Exception {
            return RestTable.buildResponse(buildTable(request, getSnapshotsResponse), channel);
        }
    });
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:18,代码来源:RestSnapshotAction.java

示例10: doRequest

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
@Override
protected void doRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));

    final ClusterStateRequest clusterStateRequest = new ClusterStateRequest();
    clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
    clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
    clusterStateRequest.clear().nodes(true).routingTable(true).indices(indices);

    client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
        @Override
        public void processResponse(final ClusterStateResponse clusterStateResponse) {
            final IndicesSegmentsRequest indicesSegmentsRequest = new IndicesSegmentsRequest();
            indicesSegmentsRequest.indices(indices);
            client.admin().indices().segments(indicesSegmentsRequest, new RestResponseListener<IndicesSegmentResponse>(channel) {
                @Override
                public RestResponse buildResponse(final IndicesSegmentResponse indicesSegmentResponse) throws Exception {
                    final Map<String, IndexSegments> indicesSegments = indicesSegmentResponse.getIndices();
                    Table tab = buildTable(request, clusterStateResponse, indicesSegments);
                    return RestTable.buildResponse(tab, channel);
                }
            });
        }
    });
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:26,代码来源:RestSegmentsAction.java

示例11: execute

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
@Override
public void execute(Client client, Map<String, String> params, QueryAction queryAction, RestChannel channel) throws Exception {
    Object queryResult = QueryActionElasticExecutor.executeAnyAction(client, queryAction);

    boolean flat = getBooleanOrDefault(params,"flat",false);
    String separator = ",";
    if(params.containsKey("separator")){
     separator = params.get("separator");
    }
    boolean includeScore = getBooleanOrDefault(params,"_score",false);
    boolean includeType = getBooleanOrDefault(params,"_type",false);
    boolean includeId = getBooleanOrDefault(params,"_id",false);
    CSVResult result  = new CSVResultsExtractor(includeScore,includeType,includeId).extractResults(queryResult,flat,separator);
    String newLine = "\n";
    if(params.containsKey("newLine")){
     newLine = params.get("newLine");
    }
    String csvString = buildString(separator, result, newLine);
    BytesRestResponse bytesRestResponse = new BytesRestResponse(RestStatus.OK, csvString);
    channel.sendResponse(bytesRestResponse);
}
 
开发者ID:mazhou,项目名称:es-sql,代码行数:22,代码来源:CSVResultRestExecutor.java

示例12: prepareRequest

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
/**
 *@description 插件的业务处理方法
 *@time 创建时间:2017年8月31日下午4:21:52
 *@param request
 *@param client
 *@return
 *@throws IOException
 *@author dzn
 */
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client)
        throws IOException {
    LOGGER.info("My Rest Action Handler");  
    Map<String, String> params = request.params();
    LOGGER.info("Param : {}", params);
    final String actionParam = request.param("action");
    LOGGER.info("actionParam : {}", actionParam);
    RestChannelConsumer res = new RestChannelConsumer(){
        @Override
        public void accept(RestChannel channel) throws Exception {
            XContentBuilder builder = channel.newBuilder();
            builder.startObject();  
            //返回给页面的信息
            builder.field("message", "This is my first plugin");
            if(null != actionParam && actionParam.trim().length() > 0){
                builder.field("接收到参数actionParam", actionParam);
            }
            builder.endObject();  
            channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
        }
    };
    return res;
}
 
开发者ID:SnailFastGo,项目名称:elasticsearch_plugin,代码行数:34,代码来源:MyRestAction.java

示例13: handleRequest

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
@Override
protected void handleRequest(final RestRequest request,
        final RestChannel channel, Client client) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        if (request.hasParam("pretty")) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("index", request.param("index"));
        builder.field("type", request.param("type"));
        builder.field("description", "This is a elasticsearch-heatmap response: "
                + new Date().toString());
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final IOException e) {
        try {
            channel.sendResponse(new BytesRestResponse(channel, e));
        } catch (final IOException e1) {
            logger.error("Failed to send a failure response.", e1);
        }
    }
}
 
开发者ID:boundlessgeo,项目名称:elasticsearch-heatmap,代码行数:24,代码来源:GeoHeatmapRestAction.java

示例14: checkRequest

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
protected void checkRequest(final RestRequest request, final RestChannel channel) {
    
    if(SSLRequestHelper.containsBadHeader(threadContext, "_sg_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 (SG 8).");
        errorHandler.logError(e, request, 0);
        throw ExceptionsHelper.convertToElastic(e);
    }
}
 
开发者ID:floragunncom,项目名称:search-guard-ssl,代码行数:20,代码来源:ValidatingDispatcher.java

示例15: authenticate

import org.elasticsearch.rest.RestChannel; //导入依赖的package包/类
@Override
public User authenticate(final RestRequest request, final RestChannel channel, final AuthenticationBackend backend,
        final Authorizator authorizator) throws AuthException {
    final String headerName = settings.get(ConfigConstants.ARMOR_AUTHENTICATION_PROXY_HEADER, "X-Authenticated-User");
    final List<String> trustedSourceIps = Arrays.asList(settings.getAsArray(
            ConfigConstants.ARMOR_AUTHENTICATION_PROXY_TRUSTED_IPS, new String[0]));

    if (!trustedSourceIps.contains("*")
            && !trustedSourceIps.contains(((InetSocketAddress) request.getRemoteAddress()).getAddress().getHostAddress())) {
        throw new AuthException("source ip not trusted");
    }

    final String proxyUser = request.header(headerName);

    if (proxyUser == null || proxyUser.isEmpty()) {
        throw new AuthException("no or empty " + headerName + " header");
    }

    final User authenticatedUser = backend.authenticate(new AuthCredentials(proxyUser, null));
    authorizator.fillRoles(authenticatedUser, new AuthCredentials(authenticatedUser.getName(), null));

    log.debug("User '{}' is authenticated", authenticatedUser);

    return authenticatedUser;
}
 
开发者ID:petalmd,项目名称:armor,代码行数:26,代码来源:HTTPProxyAuthenticator.java


注:本文中的org.elasticsearch.rest.RestChannel类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。