Java Code Examples for org.elasticsearch.common.Strings#splitStringByCommaToArray()

The following examples show how to use org.elasticsearch.common.Strings#splitStringByCommaToArray() . 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: RestIndicesExistsAction.java    From Elasticsearch with Apache License 2.0 13 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    IndicesExistsRequest indicesExistsRequest = new IndicesExistsRequest(Strings.splitStringByCommaToArray(request.param("index")));
    indicesExistsRequest.indicesOptions(IndicesOptions.fromRequest(request, indicesExistsRequest.indicesOptions()));
    indicesExistsRequest.local(request.paramAsBoolean("local", indicesExistsRequest.local()));
    client.admin().indices().exists(indicesExistsRequest, new RestResponseListener<IndicesExistsResponse>(channel) {
        @Override
        public RestResponse buildResponse(IndicesExistsResponse response) {
            if (response.isExists()) {
                return new BytesRestResponse(OK);
            } else {
                return new BytesRestResponse(NOT_FOUND);
            }
        }

    });
}
 
Example 2
Source File: RestIndicesShardStoresAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    IndicesShardStoresRequest indicesShardStoresRequest = new IndicesShardStoresRequest(Strings.splitStringByCommaToArray(request.param("index")));
    if (request.hasParam("status")) {
        indicesShardStoresRequest.shardStatuses(Strings.splitStringByCommaToArray(request.param("status")));
    }
    indicesShardStoresRequest.indicesOptions(IndicesOptions.fromRequest(request, indicesShardStoresRequest.indicesOptions()));
    client.admin().indices().shardStores(indicesShardStoresRequest, new RestBuilderListener<IndicesShardStoresResponse>(channel) {
        @Override
        public RestResponse buildResponse(IndicesShardStoresResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            response.toXContent(builder, request);
            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
Example 3
Source File: RestShardsAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public 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).metaData(true).routingTable(true).indices(indices);
    client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
        @Override
        public void processResponse(final ClusterStateResponse clusterStateResponse) {
            IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest(indices);
            indicesStatsRequest.all();
            client.admin().indices().stats(indicesStatsRequest, new RestResponseListener<IndicesStatsResponse>(channel) {
                @Override
                public RestResponse buildResponse(IndicesStatsResponse indicesStatsResponse) throws Exception {
                    return RestTable.buildResponse(buildTable(request, clusterStateResponse, indicesStatsResponse), channel);
                }
            });
        }
    });
}
 
Example 4
Source File: ClusterState.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static EnumSet<Metric> parseString(String param, boolean ignoreUnknown) {
    String[] metrics = Strings.splitStringByCommaToArray(param);
    EnumSet<Metric> result = EnumSet.noneOf(Metric.class);
    for (String metric : metrics) {
        if ("_all".equals(metric)) {
            result = EnumSet.allOf(Metric.class);
            break;
        }
        Metric m = valueToEnum.get(metric);
        if (m == null) {
            if (!ignoreUnknown) {
                throw new IllegalArgumentException("Unknown metric [" + metric + "]");
            }
        } else {
            result.add(m);
        }
    }
    return result;
}
 
Example 5
Source File: RestNodesHotThreadsAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId"));
    NodesHotThreadsRequest nodesHotThreadsRequest = new NodesHotThreadsRequest(nodesIds);
    nodesHotThreadsRequest.threads(request.paramAsInt("threads", nodesHotThreadsRequest.threads()));
    nodesHotThreadsRequest.ignoreIdleThreads(request.paramAsBoolean("ignore_idle_threads", nodesHotThreadsRequest.ignoreIdleThreads()));
    nodesHotThreadsRequest.type(request.param("type", nodesHotThreadsRequest.type()));
    nodesHotThreadsRequest.interval(TimeValue.parseTimeValue(request.param("interval"), nodesHotThreadsRequest.interval(), "interval"));
    nodesHotThreadsRequest.snapshots(request.paramAsInt("snapshots", nodesHotThreadsRequest.snapshots()));
    nodesHotThreadsRequest.timeout(request.param("timeout"));
    client.admin().cluster().nodesHotThreads(nodesHotThreadsRequest, new RestResponseListener<NodesHotThreadsResponse>(channel) {
        @Override
        public RestResponse buildResponse(NodesHotThreadsResponse response) throws Exception {
            StringBuilder sb = new StringBuilder();
            for (NodeHotThreads node : response) {
                sb.append("::: ").append(node.getNode().toString()).append("\n");
                Strings.spaceify(3, node.getHotThreads(), sb);
                sb.append('\n');
            }
            return new BytesRestResponse(RestStatus.OK, sb.toString());
        }
    });
}
 
Example 6
Source File: RestListTasksAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 7
Source File: RestUpgradeAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
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);
        }
    });
}
 
Example 8
Source File: RestTable.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts all the required fields from the RestRequest 'h' parameter. In order to support wildcards like
 * 'bulk.*' this needs potentially parse all the configured headers and its aliases and needs to ensure
 * that everything is only added once to the returned headers, even if 'h=bulk.*.bulk.*' is specified
 * or some headers are contained twice due to matching aliases
 */
private static Set<String> expandHeadersFromRequest(Table table, RestRequest request) {
    Set<String> headers = new LinkedHashSet<>(table.getHeaders().size());

    // check headers and aliases
    for (String header : Strings.splitStringByCommaToArray(request.param("h"))) {
        if (Regex.isSimpleMatchPattern(header)) {
            for (Table.Cell tableHeaderCell : table.getHeaders()) {
                String configuredHeader = tableHeaderCell.value.toString();
                if (Regex.simpleMatch(header, configuredHeader)) {
                    headers.add(configuredHeader);
                } else if (tableHeaderCell.attr.containsKey("alias")) {
                    String[] aliases = Strings.splitStringByCommaToArray(tableHeaderCell.attr.get("alias"));
                    for (String alias : aliases) {
                        if (Regex.simpleMatch(header, alias)) {
                            headers.add(configuredHeader);
                            break;
                        }
                    }
                }
            }
        } else {
            headers.add(header);
        }
    }

    return headers;
}
 
Example 9
Source File: RestRefreshAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    RefreshRequest refreshRequest = new RefreshRequest(Strings.splitStringByCommaToArray(request.param("index")));
    refreshRequest.indicesOptions(IndicesOptions.fromRequest(request, refreshRequest.indicesOptions()));
    client.admin().indices().refresh(refreshRequest, new RestBuilderListener<RefreshResponse>(channel) {
        @Override
        public RestResponse buildResponse(RefreshResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            buildBroadcastShardsHeader(builder, request, response);
            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
Example 10
Source File: RestCancelTasksAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId"));
    TaskId taskId = new TaskId(request.param("taskId"));
    String[] actions = Strings.splitStringByCommaToArray(request.param("actions"));
    TaskId parentTaskId = new TaskId(request.param("parent_task_id"));

    CancelTasksRequest cancelTasksRequest = new CancelTasksRequest();
    cancelTasksRequest.setTaskId(taskId);
    cancelTasksRequest.setNodesIds(nodesIds);
    cancelTasksRequest.setActions(actions);
    cancelTasksRequest.setParentTaskId(parentTaskId);
    client.admin().cluster().cancelTasks(cancelTasksRequest, new RestToXContentListener<CancelTasksResponse>(channel));
}
 
Example 11
Source File: RestSyncedFlushAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    IndicesOptions indicesOptions = IndicesOptions.fromRequest(request, IndicesOptions.lenientExpandOpen());
    SyncedFlushRequest syncedFlushRequest = new SyncedFlushRequest(Strings.splitStringByCommaToArray(request.param("index")));
    syncedFlushRequest.indicesOptions(indicesOptions);
    client.admin().indices().syncedFlush(syncedFlushRequest, new RestBuilderListener<SyncedFlushResponse>(channel) {
        @Override
        public RestResponse buildResponse(SyncedFlushResponse results, XContentBuilder builder) throws Exception {
            builder.startObject();
            results.toXContent(builder, request);
            builder.endObject();
            return new BytesRestResponse(results.restStatus(), builder);
        }
    });
}
 
Example 12
Source File: XContentMapValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an array of string value from a node value.
 *
 * If the node represents an array the corresponding array of strings is returned.
 * Otherwise the node is treated as a comma-separated string.
 */
public static String[] nodeStringArrayValue(Object node) {
    if (isArray(node)) {
        List list = (List) node;
        String[] arr = new String[list.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = nodeStringValue(list.get(i), null);
        }
        return arr;
    } else {
        return Strings.splitStringByCommaToArray(node.toString());
    }
}
 
Example 13
Source File: RestRecoveryAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void doRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final RecoveryRequest recoveryRequest = new RecoveryRequest(Strings.splitStringByCommaToArray(request.param("index")));
    recoveryRequest.detailed(request.paramAsBoolean("detailed", false));
    recoveryRequest.activeOnly(request.paramAsBoolean("active_only", false));
    recoveryRequest.indicesOptions(IndicesOptions.fromRequest(request, recoveryRequest.indicesOptions()));

    client.admin().indices().recoveries(recoveryRequest, new RestResponseListener<RecoveryResponse>(channel) {
        @Override
        public RestResponse buildResponse(final RecoveryResponse response) throws Exception {
            return RestTable.buildResponse(buildRecoveryTable(request, response), channel);
        }
    });
}
 
Example 14
Source File: RestGetIndicesAliasesAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final String[] aliases = Strings.splitStringByCommaToArray(request.param("name"));

    ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest()
            .routingTable(false)
            .nodes(false)
            .indices(indices);
    clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));

    client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) {
        @Override
        public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception {
            MetaData metaData = response.getState().metaData();
            builder.startObject();

            final boolean isAllAliasesRequested = isAllOrWildcard(aliases);
            for (IndexMetaData indexMetaData : metaData) {
                builder.startObject(indexMetaData.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
                builder.startObject("aliases");

                for (ObjectCursor<AliasMetaData> cursor : indexMetaData.getAliases().values()) {
                    if (isAllAliasesRequested || Regex.simpleMatch(aliases, cursor.value.alias())) {
                        AliasMetaData.Builder.toXContent(cursor.value, builder, ToXContent.EMPTY_PARAMS);
                    }
                }

                builder.endObject();
                builder.endObject();
            }

            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
Example 15
Source File: RestGetAliasesAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(aliases);
    getAliasesRequest.indices(indices);
    getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
    getAliasesRequest.local(request.paramAsBoolean("local", getAliasesRequest.local()));

    client.admin().indices().getAliases(getAliasesRequest, new RestBuilderListener<GetAliasesResponse>(channel) {
        @Override
        public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
            // empty body, if indices were specified but no aliases were
            if (indices.length > 0 && response.getAliases().isEmpty()) {
                return new BytesRestResponse(OK, builder.startObject().endObject());
            } else if (response.getAliases().isEmpty()) {
                String message = String.format(Locale.ROOT, "alias [%s] missing", toNamesString(getAliasesRequest.aliases()));
                builder.startObject()
                        .field("error", message)
                        .field("status", RestStatus.NOT_FOUND.getStatus())
                        .endObject();
                return new BytesRestResponse(RestStatus.NOT_FOUND, builder);
            }

            builder.startObject();
            for (ObjectObjectCursor<String, List<AliasMetaData>> entry : response.getAliases()) {
                builder.startObject(entry.key, XContentBuilder.FieldCaseConversion.NONE);
                builder.startObject(Fields.ALIASES);
                for (AliasMetaData alias : entry.value) {
                    AliasMetaData.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
                }
                builder.endObject();
                builder.endObject();
            }
            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
Example 16
Source File: RestExistsAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final ExistsRequest existsRequest = new ExistsRequest(Strings.splitStringByCommaToArray(request.param("index")));
    existsRequest.indicesOptions(IndicesOptions.fromRequest(request, existsRequest.indicesOptions()));
    if (RestActions.hasBodyContent(request)) {
        existsRequest.source(RestActions.getRestContent(request));
    } else {
        QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
        if (querySourceBuilder != null) {
            existsRequest.source(querySourceBuilder);
        }
    }
    existsRequest.routing(request.param("routing"));
    existsRequest.minScore(request.paramAsFloat("min_score", DEFAULT_MIN_SCORE));
    existsRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    existsRequest.preference(request.param("preference"));

    client.exists(existsRequest, new RestBuilderListener<ExistsResponse>(channel) {
        @Override
        public RestResponse buildResponse(ExistsResponse response, XContentBuilder builder) throws Exception {
            RestStatus status = response.exists() ? OK : NOT_FOUND;
            builder.startObject();
            builder.field("exists", response.exists());
            builder.endObject();
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example 17
Source File: RestGetAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final GetRequest getRequest = new GetRequest(request.param("index"), request.param("type"), request.param("id"));
    getRequest.operationThreaded(true);
    getRequest.refresh(request.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.routing(request.param("routing"));  // order is important, set it after routing, so it will set the routing
    getRequest.parent(request.param("parent"));
    getRequest.preference(request.param("preference"));
    getRequest.realtime(request.paramAsBoolean("realtime", null));
    getRequest.ignoreErrorsOnGeneratedFields(request.paramAsBoolean("ignore_errors_on_generated_fields", false));

    String sField = request.param("fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            getRequest.fields(sFields);
        }
    }

    getRequest.version(RestActions.parseVersion(request));
    getRequest.versionType(VersionType.fromString(request.param("version_type"), getRequest.versionType()));

    getRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));

    client.get(getRequest, new RestBuilderListener<GetResponse>(channel) {
        @Override
        public RestResponse buildResponse(GetResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            response.toXContent(builder, request);
            builder.endObject();
            if (!response.isExists()) {
                return new BytesRestResponse(NOT_FOUND, builder);
            } else {
                return new BytesRestResponse(OK, builder);
            }
        }
    });
}
 
Example 18
Source File: RestNodesStatsAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId"));
    Set<String> metrics = Strings.splitStringByCommaToSet(request.param("metric", "_all"));

    NodesStatsRequest nodesStatsRequest = new NodesStatsRequest(nodesIds);
    nodesStatsRequest.timeout(request.param("timeout"));

    if (metrics.size() == 1 && metrics.contains("_all")) {
        nodesStatsRequest.all();
        nodesStatsRequest.indices(CommonStatsFlags.ALL);
    } else {
        nodesStatsRequest.clear();
        nodesStatsRequest.os(metrics.contains("os"));
        nodesStatsRequest.jvm(metrics.contains("jvm"));
        nodesStatsRequest.threadPool(metrics.contains("thread_pool"));
        nodesStatsRequest.fs(metrics.contains("fs"));
        nodesStatsRequest.transport(metrics.contains("transport"));
        nodesStatsRequest.http(metrics.contains("http"));
        nodesStatsRequest.indices(metrics.contains("indices"));
        nodesStatsRequest.process(metrics.contains("process"));
        nodesStatsRequest.breaker(metrics.contains("breaker"));
        nodesStatsRequest.script(metrics.contains("script"));

        // check for index specific metrics
        if (metrics.contains("indices")) {
            Set<String> indexMetrics = Strings.splitStringByCommaToSet(request.param("indexMetric", "_all"));
            if (indexMetrics.size() == 1 && indexMetrics.contains("_all")) {
                nodesStatsRequest.indices(CommonStatsFlags.ALL);
            } else {
                CommonStatsFlags flags = new CommonStatsFlags();
                for (Flag flag : CommonStatsFlags.Flag.values()) {
                    flags.set(flag, indexMetrics.contains(flag.getRestName()));
                }
                nodesStatsRequest.indices(flags);
            }
        }
    }

    if (nodesStatsRequest.indices().isSet(Flag.FieldData) && (request.hasParam("fields") || request.hasParam("fielddata_fields"))) {
        nodesStatsRequest.indices().fieldDataFields(request.paramAsStringArray("fielddata_fields", request.paramAsStringArray("fields", null)));
    }
    if (nodesStatsRequest.indices().isSet(Flag.Completion) && (request.hasParam("fields") || request.hasParam("completion_fields"))) {
        nodesStatsRequest.indices().completionDataFields(request.paramAsStringArray("completion_fields", request.paramAsStringArray("fields", null)));
    }
    if (nodesStatsRequest.indices().isSet(Flag.Search) && (request.hasParam("groups"))) {
        nodesStatsRequest.indices().groups(request.paramAsStringArray("groups", null));
    }
    if (nodesStatsRequest.indices().isSet(Flag.Indexing) && (request.hasParam("types"))) {
        nodesStatsRequest.indices().types(request.paramAsStringArray("types", null));
    }

    client.admin().cluster().nodesStats(nodesStatsRequest, new RestToXContentListener<NodesStatsResponse>(channel));
}
 
Example 19
Source File: RestUpdateAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
    UpdateRequest updateRequest = new UpdateRequest(request.param("index"), request.param("type"), request.param("id"));
    updateRequest.routing(request.param("routing"));
    updateRequest.parent(request.param("parent"));
    updateRequest.timeout(request.paramAsTime("timeout", updateRequest.timeout()));
    updateRequest.refresh(request.paramAsBoolean("refresh", updateRequest.refresh()));
    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
        updateRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }
    updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert()));
    ScriptParameterParser scriptParameterParser = new ScriptParameterParser();
    scriptParameterParser.parseParams(request);
    ScriptParameterValue scriptValue = scriptParameterParser.getDefaultScriptParameterValue();
    if (scriptValue != null) {
        Map<String, Object> scriptParams = new HashMap<>();
        for (Map.Entry<String, String> entry : request.params().entrySet()) {
            if (entry.getKey().startsWith("sp_")) {
                scriptParams.put(entry.getKey().substring(3), entry.getValue());
            }
        }
        updateRequest.script(new Script(scriptValue.script(), scriptValue.scriptType(), scriptParameterParser.lang(), scriptParams));
    }
    String sField = request.param("fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            updateRequest.fields(sFields);
        }
    }
    updateRequest.retryOnConflict(request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));
    updateRequest.version(RestActions.parseVersion(request));
    updateRequest.versionType(VersionType.fromString(request.param("version_type"), updateRequest.versionType()));


    // see if we have it in the body
    if (request.hasContent()) {
        updateRequest.source(request.content());
        IndexRequest upsertRequest = updateRequest.upsertRequest();
        if (upsertRequest != null) {
            upsertRequest.routing(request.param("routing"));
            upsertRequest.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
            upsertRequest.timestamp(request.param("timestamp"));
            if (request.hasParam("ttl")) {
                upsertRequest.ttl(request.param("ttl"));
            }
            upsertRequest.version(RestActions.parseVersion(request));
            upsertRequest.versionType(VersionType.fromString(request.param("version_type"), upsertRequest.versionType()));
        }
        IndexRequest doc = updateRequest.doc();
        if (doc != null) {
            doc.routing(request.param("routing"));
            doc.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
            doc.timestamp(request.param("timestamp"));
            if (request.hasParam("ttl")) {
                doc.ttl(request.param("ttl"));
            }
            doc.version(RestActions.parseVersion(request));
            doc.versionType(VersionType.fromString(request.param("version_type"), doc.versionType()));
        }
    }

    client.update(updateRequest, new RestBuilderListener<UpdateResponse>(channel) {
        @Override
        public RestResponse buildResponse(UpdateResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            ActionWriteResponse.ShardInfo shardInfo = response.getShardInfo();
            builder.field(Fields._INDEX, response.getIndex())
                    .field(Fields._TYPE, response.getType())
                    .field(Fields._ID, response.getId())
                    .field(Fields._VERSION, response.getVersion());

            shardInfo.toXContent(builder, request);
            if (response.getGetResult() != null) {
                builder.startObject(Fields.GET);
                response.getGetResult().toXContentEmbedded(builder, request);
                builder.endObject();
            }

            builder.endObject();
            RestStatus status = shardInfo.status();
            if (response.isCreated()) {
                status = CREATED;
            }
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example 20
Source File: RestNodesInfoAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String[] nodeIds;
    Set<String> metrics;

    // special case like /_nodes/os (in this case os are metrics and not the nodeId)
    // still, /_nodes/_local (or any other node id) should work and be treated as usual
    // this means one must differentiate between allowed metrics and arbitrary node ids in the same place
    if (request.hasParam("nodeId") && !request.hasParam("metrics")) {
        Set<String> metricsOrNodeIds = Strings.splitStringByCommaToSet(request.param("nodeId", "_all"));
        boolean isMetricsOnly = ALLOWED_METRICS.containsAll(metricsOrNodeIds);
        if (isMetricsOnly) {
            nodeIds = new String[]{"_all"};
            metrics = metricsOrNodeIds;
        } else {
            nodeIds = metricsOrNodeIds.toArray(new String[]{});
            metrics = Sets.newHashSet("_all");
        }
    } else {
        nodeIds = Strings.splitStringByCommaToArray(request.param("nodeId", "_all"));
        metrics = Strings.splitStringByCommaToSet(request.param("metrics", "_all"));
    }

    final NodesInfoRequest nodesInfoRequest = new NodesInfoRequest(nodeIds);
    nodesInfoRequest.timeout(request.param("timeout"));
    // shortcut, dont do checks if only all is specified
    if (metrics.size() == 1 && metrics.contains("_all")) {
        nodesInfoRequest.all();
    } else {
        nodesInfoRequest.clear();
        nodesInfoRequest.settings(metrics.contains("settings"));
        nodesInfoRequest.os(metrics.contains("os"));
        nodesInfoRequest.process(metrics.contains("process"));
        nodesInfoRequest.jvm(metrics.contains("jvm"));
        nodesInfoRequest.threadPool(metrics.contains("thread_pool"));
        nodesInfoRequest.transport(metrics.contains("transport"));
        nodesInfoRequest.http(metrics.contains("http"));
        nodesInfoRequest.plugins(metrics.contains("plugins"));
    }

    settingsFilter.addFilterSettingParams(request);

    client.admin().cluster().nodesInfo(nodesInfoRequest, new RestBuilderListener<NodesInfoResponse>(channel) {

        @Override
        public RestResponse buildResponse(NodesInfoResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            response.toXContent(builder, request);
            builder.endObject();
            return new BytesRestResponse(RestStatus.OK, builder);
        }
    });
}