Search in sources :

Example 16 with XContentParser

use of org.elasticsearch.common.xcontent.XContentParser in project elasticsearch by elastic.

the class BytesRestResponse method errorFromXContent.

public static ElasticsearchStatusException errorFromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.nextToken();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);
    ElasticsearchException exception = null;
    RestStatus status = null;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        }
        if (STATUS.equals(currentFieldName)) {
            if (token != XContentParser.Token.FIELD_NAME) {
                ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser::getTokenLocation);
                status = RestStatus.fromCode(parser.intValue());
            }
        } else {
            exception = ElasticsearchException.failureFromXContent(parser);
        }
    }
    if (exception == null) {
        throw new IllegalStateException("Failed to parse elasticsearch status exception: no exception was found");
    }
    ElasticsearchStatusException result = new ElasticsearchStatusException(exception.getMessage(), status, exception.getCause());
    for (String header : exception.getHeaderKeys()) {
        result.addHeader(header, exception.getHeader(header));
    }
    for (String metadata : exception.getMetadataKeys()) {
        result.addMetadata(metadata, exception.getMetadata(metadata));
    }
    return result;
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentParser(org.elasticsearch.common.xcontent.XContentParser) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException)

Example 17 with XContentParser

use of org.elasticsearch.common.xcontent.XContentParser in project elasticsearch by elastic.

the class RestClusterAllocationExplainAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    ClusterAllocationExplainRequest req;
    if (request.hasContentOrSourceParam() == false) {
        // Empty request signals "explain the first unassigned shard you find"
        req = new ClusterAllocationExplainRequest();
    } else {
        try (XContentParser parser = request.contentOrSourceParamParser()) {
            req = ClusterAllocationExplainRequest.parse(parser);
        }
    }
    req.includeYesDecisions(request.paramAsBoolean("include_yes_decisions", false));
    req.includeDiskInfo(request.paramAsBoolean("include_disk_info", false));
    return channel -> client.admin().cluster().allocationExplain(req, new RestBuilderListener<ClusterAllocationExplainResponse>(channel) {

        @Override
        public RestResponse buildResponse(ClusterAllocationExplainResponse response, XContentBuilder builder) throws IOException {
            response.getExplanation().toXContent(builder, ToXContent.EMPTY_PARAMS);
            return new BytesRestResponse(RestStatus.OK, builder);
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) ClusterAllocationExplainResponse(org.elasticsearch.action.admin.cluster.allocation.ClusterAllocationExplainResponse) RestResponse(org.elasticsearch.rest.RestResponse) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) ToXContent(org.elasticsearch.common.xcontent.ToXContent) IOException(java.io.IOException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) XContentParser(org.elasticsearch.common.xcontent.XContentParser) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) Settings(org.elasticsearch.common.settings.Settings) RestStatus(org.elasticsearch.rest.RestStatus) RestRequest(org.elasticsearch.rest.RestRequest) NodeClient(org.elasticsearch.client.node.NodeClient) ClusterAllocationExplainRequest(org.elasticsearch.action.admin.cluster.allocation.ClusterAllocationExplainRequest) ClusterAllocationExplainRequest(org.elasticsearch.action.admin.cluster.allocation.ClusterAllocationExplainRequest) ClusterAllocationExplainResponse(org.elasticsearch.action.admin.cluster.allocation.ClusterAllocationExplainResponse) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) IOException(java.io.IOException) XContentParser(org.elasticsearch.common.xcontent.XContentParser) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 18 with XContentParser

use of org.elasticsearch.common.xcontent.XContentParser in project elasticsearch by elastic.

the class RestFieldStatsAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    if (request.hasContentOrSourceParam() && request.hasParam("fields")) {
        throw new IllegalArgumentException("can't specify a request body and [fields] request parameter, " + "either specify a request body or the [fields] request parameter");
    }
    final FieldStatsRequest fieldStatsRequest = new FieldStatsRequest();
    fieldStatsRequest.indices(Strings.splitStringByCommaToArray(request.param("index")));
    fieldStatsRequest.indicesOptions(IndicesOptions.fromRequest(request, fieldStatsRequest.indicesOptions()));
    fieldStatsRequest.level(request.param("level", FieldStatsRequest.DEFAULT_LEVEL));
    if (request.hasContentOrSourceParam()) {
        try (XContentParser parser = request.contentOrSourceParamParser()) {
            fieldStatsRequest.source(parser);
        }
    } else {
        fieldStatsRequest.setFields(Strings.splitStringByCommaToArray(request.param("fields")));
    }
    return channel -> client.fieldStats(fieldStatsRequest, new RestBuilderListener<FieldStatsResponse>(channel) {

        @Override
        public RestResponse buildResponse(FieldStatsResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            buildBroadcastShardsHeader(builder, request, response);
            builder.startObject("indices");
            for (Map.Entry<String, Map<String, FieldStats>> entry1 : response.getIndicesMergedFieldStats().entrySet()) {
                builder.startObject(entry1.getKey());
                builder.startObject("fields");
                for (Map.Entry<String, FieldStats> entry2 : entry1.getValue().entrySet()) {
                    builder.field(entry2.getKey());
                    entry2.getValue().toXContent(builder, request);
                }
                builder.endObject();
                builder.endObject();
            }
            builder.endObject();
            if (response.getConflicts().size() > 0) {
                builder.startObject("conflicts");
                for (Map.Entry<String, String> entry : response.getConflicts().entrySet()) {
                    builder.field(entry.getKey(), entry.getValue());
                }
                builder.endObject();
            }
            builder.endObject();
            return new BytesRestResponse(RestStatus.OK, builder);
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) GET(org.elasticsearch.rest.RestRequest.Method.GET) FieldStatsRequest(org.elasticsearch.action.fieldstats.FieldStatsRequest) RestResponse(org.elasticsearch.rest.RestResponse) IOException(java.io.IOException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) XContentParser(org.elasticsearch.common.xcontent.XContentParser) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) POST(org.elasticsearch.rest.RestRequest.Method.POST) Settings(org.elasticsearch.common.settings.Settings) RestActions.buildBroadcastShardsHeader(org.elasticsearch.rest.action.RestActions.buildBroadcastShardsHeader) RestStatus(org.elasticsearch.rest.RestStatus) Map(java.util.Map) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) RestRequest(org.elasticsearch.rest.RestRequest) NodeClient(org.elasticsearch.client.node.NodeClient) FieldStats(org.elasticsearch.action.fieldstats.FieldStats) FieldStatsResponse(org.elasticsearch.action.fieldstats.FieldStatsResponse) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) FieldStatsResponse(org.elasticsearch.action.fieldstats.FieldStatsResponse) IOException(java.io.IOException) FieldStats(org.elasticsearch.action.fieldstats.FieldStats) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentParser(org.elasticsearch.common.xcontent.XContentParser) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) FieldStatsRequest(org.elasticsearch.action.fieldstats.FieldStatsRequest)

Example 19 with XContentParser

use of org.elasticsearch.common.xcontent.XContentParser in project elasticsearch by elastic.

the class GeoDistanceSortBuilder method fromXContent.

/**
     * Creates a new {@link GeoDistanceSortBuilder} from the query held by the {@link QueryParseContext} in
     * {@link org.elasticsearch.common.xcontent.XContent} format.
     *
     * @param context the input parse context. The state on the parser contained in this context will be changed as a
     *                side effect of this method call
     * @param elementName in some sort syntax variations the field name precedes the xContent object that specifies
     *                    further parameters, e.g. in '{ "foo": { "order" : "asc"} }'. When parsing the inner object,
     *                    the field name can be passed in via this argument
     */
public static GeoDistanceSortBuilder fromXContent(QueryParseContext context, String elementName) throws IOException {
    XContentParser parser = context.parser();
    String fieldName = null;
    List<GeoPoint> geoPoints = new ArrayList<>();
    DistanceUnit unit = DistanceUnit.DEFAULT;
    GeoDistance geoDistance = GeoDistance.ARC;
    SortOrder order = SortOrder.ASC;
    SortMode sortMode = null;
    QueryBuilder nestedFilter = null;
    String nestedPath = null;
    GeoValidationMethod validation = null;
    XContentParser.Token token;
    String currentName = parser.currentName();
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentName = parser.currentName();
        } else if (token == XContentParser.Token.START_ARRAY) {
            parseGeoPoints(parser, geoPoints);
            fieldName = currentName;
        } else if (token == XContentParser.Token.START_OBJECT) {
            if (NESTED_FILTER_FIELD.match(currentName)) {
                nestedFilter = context.parseInnerQueryBuilder();
            } else {
                // the json in the format of -> field : { lat : 30, lon : 12 }
                if (fieldName != null && fieldName.equals(currentName) == false) {
                    throw new ParsingException(parser.getTokenLocation(), "Trying to reset fieldName to [{}], already set to [{}].", currentName, fieldName);
                }
                fieldName = currentName;
                GeoPoint point = new GeoPoint();
                GeoUtils.parseGeoPoint(parser, point);
                geoPoints.add(point);
            }
        } else if (token.isValue()) {
            if (ORDER_FIELD.match(currentName)) {
                order = SortOrder.fromString(parser.text());
            } else if (UNIT_FIELD.match(currentName)) {
                unit = DistanceUnit.fromString(parser.text());
            } else if (DISTANCE_TYPE_FIELD.match(currentName)) {
                geoDistance = GeoDistance.fromString(parser.text());
            } else if (VALIDATION_METHOD_FIELD.match(currentName)) {
                validation = GeoValidationMethod.fromString(parser.text());
            } else if (SORTMODE_FIELD.match(currentName)) {
                sortMode = SortMode.fromString(parser.text());
            } else if (NESTED_PATH_FIELD.match(currentName)) {
                nestedPath = parser.text();
            } else if (token == Token.VALUE_STRING) {
                if (fieldName != null && fieldName.equals(currentName) == false) {
                    throw new ParsingException(parser.getTokenLocation(), "Trying to reset fieldName to [{}], already set to [{}].", currentName, fieldName);
                }
                GeoPoint point = new GeoPoint();
                point.resetFromString(parser.text());
                geoPoints.add(point);
                fieldName = currentName;
            } else if (fieldName.equals(currentName)) {
                throw new ParsingException(parser.getTokenLocation(), "Only geohashes of type string supported for field [{}]", currentName);
            } else {
                throw new ParsingException(parser.getTokenLocation(), "[{}] does not support [{}]", NAME, currentName);
            }
        }
    }
    GeoDistanceSortBuilder result = new GeoDistanceSortBuilder(fieldName, geoPoints.toArray(new GeoPoint[geoPoints.size()]));
    result.geoDistance(geoDistance);
    result.unit(unit);
    result.order(order);
    if (sortMode != null) {
        result.sortMode(sortMode);
    }
    if (nestedFilter != null) {
        result.setNestedFilter(nestedFilter);
    }
    result.setNestedPath(nestedPath);
    if (validation != null) {
        result.validation(validation);
    }
    return result;
}
Also used : GeoValidationMethod(org.elasticsearch.index.query.GeoValidationMethod) ArrayList(java.util.ArrayList) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) GeoPoint(org.elasticsearch.common.geo.GeoPoint) Token(org.elasticsearch.common.xcontent.XContentParser.Token) ParsingException(org.elasticsearch.common.ParsingException) GeoDistance(org.elasticsearch.common.geo.GeoDistance) DistanceUnit(org.elasticsearch.common.unit.DistanceUnit) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 20 with XContentParser

use of org.elasticsearch.common.xcontent.XContentParser in project elasticsearch by elastic.

the class SortBuilder method parseCompoundSortField.

private static void parseCompoundSortField(QueryParseContext context, List<SortBuilder<?>> sortFields) throws IOException {
    XContentParser.Token token;
    XContentParser parser = context.parser();
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            String fieldName = parser.currentName();
            token = parser.nextToken();
            if (token == XContentParser.Token.VALUE_STRING) {
                SortOrder order = SortOrder.fromString(parser.text());
                sortFields.add(fieldOrScoreSort(fieldName).order(order));
            } else {
                if (PARSERS.containsKey(fieldName)) {
                    sortFields.add(PARSERS.get(fieldName).fromXContent(context, fieldName));
                } else {
                    sortFields.add(FieldSortBuilder.fromXContent(context, fieldName));
                }
            }
        }
    }
}
Also used : XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Aggregations

XContentParser (org.elasticsearch.common.xcontent.XContentParser)463 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)147 ParsingException (org.elasticsearch.common.ParsingException)110 IOException (java.io.IOException)77 BytesReference (org.elasticsearch.common.bytes.BytesReference)63 ArrayList (java.util.ArrayList)59 ElasticsearchParseException (org.elasticsearch.ElasticsearchParseException)56 XContentType (org.elasticsearch.common.xcontent.XContentType)47 QueryParseContext (org.elasticsearch.index.query.QueryParseContext)44 HashMap (java.util.HashMap)33 Map (java.util.Map)27 Matchers.containsString (org.hamcrest.Matchers.containsString)23 List (java.util.List)22 Settings (org.elasticsearch.common.settings.Settings)18 ToXContent (org.elasticsearch.common.xcontent.ToXContent)16 ShardId (org.elasticsearch.index.shard.ShardId)16 Script (org.elasticsearch.script.Script)16 XContent (org.elasticsearch.common.xcontent.XContent)15 ElasticsearchException (org.elasticsearch.ElasticsearchException)14 NodeClient (org.elasticsearch.client.node.NodeClient)14