Java Code Examples for org.elasticsearch.common.xcontent.XContentParser#booleanValue()

The following examples show how to use org.elasticsearch.common.xcontent.XContentParser#booleanValue() . 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: NXYSignificanceHeuristic.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context)
        throws IOException, QueryParsingException {
    String givenName = parser.currentName();
    boolean includeNegatives = false;
    boolean backgroundIsSuperset = true;
    XContentParser.Token token = parser.nextToken();
    while (!token.equals(XContentParser.Token.END_OBJECT)) {
        if (parseFieldMatcher.match(parser.currentName(), INCLUDE_NEGATIVES_FIELD)) {
            parser.nextToken();
            includeNegatives = parser.booleanValue();
        } else if (parseFieldMatcher.match(parser.currentName(), BACKGROUND_IS_SUPERSET)) {
            parser.nextToken();
            backgroundIsSuperset = parser.booleanValue();
        } else {
            throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown field [{}]", givenName, parser.currentName());
        }
        token = parser.nextToken();
    }
    return newHeuristic(includeNegatives, backgroundIsSuperset);
}
 
Example 2
Source File: GND.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context)
        throws IOException, QueryParsingException {
    String givenName = parser.currentName();
    boolean backgroundIsSuperset = true;
    XContentParser.Token token = parser.nextToken();
    while (!token.equals(XContentParser.Token.END_OBJECT)) {
        if (parseFieldMatcher.match(parser.currentName(), BACKGROUND_IS_SUPERSET)) {
            parser.nextToken();
            backgroundIsSuperset = parser.booleanValue();
        } else {
            throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown field [{}]", givenName, parser.currentName());
        }
        token = parser.nextToken();
    }
    return newHeuristic(true, backgroundIsSuperset);
}
 
Example 3
Source File: AbstractXContentParser.java    From crate with Apache License 2.0 6 votes vote down vote up
static Object readValue(XContentParser parser, MapFactory mapFactory, XContentParser.Token token) throws IOException {
    if (token == XContentParser.Token.VALUE_NULL) {
        return null;
    } else if (token == XContentParser.Token.VALUE_STRING) {
        return parser.text();
    } else if (token == XContentParser.Token.VALUE_NUMBER) {
        return parser.numberValue();
    } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
        return parser.booleanValue();
    } else if (token == XContentParser.Token.START_OBJECT) {
        return readMap(parser, mapFactory);
    } else if (token == XContentParser.Token.START_ARRAY) {
        return readList(parser, mapFactory);
    } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) {
        return parser.binaryValue();
    }
    return null;
}
 
Example 4
Source File: GeoBoundsParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {
    ValuesSourceParser<GeoPoint> vsParser = ValuesSourceParser.geoPoint(aggregationName, InternalGeoBounds.TYPE, context)
            .targetValueType(ValueType.GEOPOINT)
            .formattable(true)
            .build();
    boolean wrapLongitude = true;
    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
            
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("wrap_longitude".equals(currentFieldName) || "wrapLongitude".equals(currentFieldName)) {
                wrapLongitude = parser.booleanValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
                    + currentFieldName + "].", parser.getTokenLocation());
        }
    }
    return new GeoBoundsAggregator.Factory(aggregationName, vsParser.config(), wrapLongitude);
}
 
Example 5
Source File: CancelAllocationCommand.java    From crate with Apache License 2.0 5 votes vote down vote up
public static CancelAllocationCommand fromXContent(XContentParser parser) throws IOException {
    String index = null;
    int shardId = -1;
    String nodeId = null;
    boolean allowPrimary = false;

    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue()) {
            if ("index".equals(currentFieldName)) {
                index = parser.text();
            } else if ("shard".equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if ("node".equals(currentFieldName)) {
                nodeId = parser.text();
            } else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
                allowPrimary = parser.booleanValue();
            } else {
                throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
        }
    }
    if (index == null) {
        throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
    }
    if (shardId == -1) {
        throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
    }
    if (nodeId == null) {
        throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
    }
    return new CancelAllocationCommand(index, shardId, nodeId, allowPrimary);
}
 
Example 6
Source File: AbstractXContentParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
static Object readValue(XContentParser parser, MapFactory mapFactory, XContentParser.Token token) throws IOException {
    if (token == XContentParser.Token.VALUE_NULL) {
        return null;
    } else if (token == XContentParser.Token.VALUE_STRING) {
        return parser.text();
    } else if (token == XContentParser.Token.VALUE_NUMBER) {
        XContentParser.NumberType numberType = parser.numberType();
        if (numberType == XContentParser.NumberType.INT) {
            return parser.intValue();
        } else if (numberType == XContentParser.NumberType.LONG) {
            return parser.longValue();
        } else if (numberType == XContentParser.NumberType.FLOAT) {
            return parser.floatValue();
        } else if (numberType == XContentParser.NumberType.DOUBLE) {
            return parser.doubleValue();
        }
    } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
        return parser.booleanValue();
    } else if (token == XContentParser.Token.START_OBJECT) {
        return readMap(parser, mapFactory);
    } else if (token == XContentParser.Token.START_ARRAY) {
        return readList(parser, mapFactory);
    } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) {
        return parser.binaryValue();
    }
    return null;
}
 
Example 7
Source File: AllocateAllocationCommand.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public AllocateAllocationCommand fromXContent(XContentParser parser) throws IOException {
    String index = null;
    int shardId = -1;
    String nodeId = null;
    boolean allowPrimary = false;

    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue()) {
            if ("index".equals(currentFieldName)) {
                index = parser.text();
            } else if ("shard".equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if ("node".equals(currentFieldName)) {
                nodeId = parser.text();
            } else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
                allowPrimary = parser.booleanValue();
            } else {
                throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
        }
    }
    if (index == null) {
        throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
    }
    if (shardId == -1) {
        throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
    }
    if (nodeId == null) {
        throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
    }
    return new AllocateAllocationCommand(new ShardId(index, shardId), nodeId, allowPrimary);
}
 
Example 8
Source File: ShardStateMetaData.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public ShardStateMetaData fromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.nextToken();
    if (token == null) {
        return null;
    }
    Boolean primary = null;
    String currentFieldName = null;
    String indexUUID = IndexMetaData.INDEX_UUID_NA_VALUE;
    AllocationId allocationId = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue()) {
            if (PRIMARY_KEY.equals(currentFieldName)) {
                primary = parser.booleanValue();
            } else if (INDEX_UUID_KEY.equals(currentFieldName)) {
                indexUUID = parser.text();
            } else if (VERSION_KEY.equals(currentFieldName)) {
                // ES versions before 6.0 wrote this for legacy reasons, just ignore for now and remove in 7.0
            } else {
                throw new CorruptStateException("unexpected field in shard state [" + currentFieldName + "]");
            }
        } else if (token == XContentParser.Token.START_OBJECT) {
            if (ALLOCATION_ID_KEY.equals(currentFieldName)) {
                allocationId = AllocationId.fromXContent(parser);
            } else {
                throw new CorruptStateException("unexpected object in shard state [" + currentFieldName + "]");
            }
        } else {
            throw new CorruptStateException("unexpected token in shard state [" + token.name() + "]");
        }
    }
    if (primary == null) {
        throw new CorruptStateException("missing value for [primary] in shard state");
    }
    return new ShardStateMetaData(primary, indexUUID, allocationId);
}
 
Example 9
Source File: TermsParametersParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parseSpecial(String aggregationName, XContentParser parser, SearchContext context, XContentParser.Token token, String currentFieldName) throws IOException {
    if (token == XContentParser.Token.START_OBJECT) {
        if ("order".equals(currentFieldName)) {
            this.orderElements = Collections.singletonList(parseOrderParam(aggregationName, parser, context));
        } else {
            throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                    + currentFieldName + "].", parser.getTokenLocation());
        }
    } else if (token == XContentParser.Token.START_ARRAY) {
        if ("order".equals(currentFieldName)) {
            orderElements = new ArrayList<>();
            while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                if (token == XContentParser.Token.START_OBJECT) {
                    OrderElement orderParam = parseOrderParam(aggregationName, parser, context);
                    orderElements.add(orderParam);
                } else {
                    throw new SearchParseException(context, "Order elements must be of type object in [" + aggregationName + "].",
                            parser.getTokenLocation());
                }
            }
        } else {
            throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                    + currentFieldName + "].", parser.getTokenLocation());
        }
    } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
        if (context.parseFieldMatcher().match(currentFieldName, SHOW_TERM_DOC_COUNT_ERROR)) {
            showTermDocCountError = parser.booleanValue();
        }
    } else {
        throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName
                + "].", parser.getTokenLocation());
    }
}
 
Example 10
Source File: Feature.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
/**
 * Parse raw json content into feature instance.
 *
 * @param parser json based content parser
 * @return feature instance
 * @throws IOException IOException if content can't be parsed correctly
 */
public static Feature parse(XContentParser parser) throws IOException {
    String id = UUIDs.base64UUID();
    String name = null;
    Boolean enabled = null;
    AggregationBuilder aggregation = null;

    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
    while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
        String fieldName = parser.currentName();

        parser.nextToken();
        switch (fieldName) {
            case FEATURE_ID_FIELD:
                id = parser.text();
                break;
            case FEATURE_NAME_FIELD:
                name = parser.text();
                break;
            case FEATURE_ENABLED_FIELD:
                enabled = parser.booleanValue();
                break;
            case AGGREGATION_QUERY:
                ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
                aggregation = ParseUtils.toAggregationBuilder(parser);
                break;
            default:
                break;
        }
    }
    return new Feature(id, name, enabled, aggregation);
}
 
Example 11
Source File: MissingQueryParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    deprecationLogger.deprecated("The [missing] query is deprecated, please use an [exist] query in a [must_not] clause instead.");

    XContentParser parser = parseContext.parser();

    String fieldPattern = null;
    String queryName = null;
    boolean nullValue = DEFAULT_NULL_VALUE;
    boolean existence = DEFAULT_EXISTENCE_VALUE;

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue()) {
            if ("field".equals(currentFieldName)) {
                fieldPattern = parser.text();
            } else if ("null_value".equals(currentFieldName)) {
                nullValue = parser.booleanValue();
            } else if ("existence".equals(currentFieldName)) {
                existence = parser.booleanValue();
            } else if ("_name".equals(currentFieldName)) {
                queryName = parser.text();
            } else {
                throw new QueryParsingException(parseContext, "[missing] query does not support [" + currentFieldName + "]");
            }
        }
    }

    if (fieldPattern == null) {
        throw new QueryParsingException(parseContext, "missing must be provided with a [field]");
    }

    return newFilter(parseContext, fieldPattern, existence, nullValue, queryName);
}
 
Example 12
Source File: HistogramParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {

    ValuesSourceParser vsParser = ValuesSourceParser.numeric(aggregationName, InternalHistogram.TYPE, context)
            .targetValueType(ValueType.NUMERIC)
            .formattable(true)
            .build();

    boolean keyed = false;
    long minDocCount = 0;
    InternalOrder order = (InternalOrder) InternalOrder.KEY_ASC;
    long interval = -1;
    ExtendedBounds extendedBounds = null;
    long offset = 0;

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
        } else if (token.isValue()) {
            if ("interval".equals(currentFieldName)) {
                interval = parser.longValue();
            } else if ("min_doc_count".equals(currentFieldName) || "minDocCount".equals(currentFieldName)) {
                minDocCount = parser.longValue();
            } else if ("keyed".equals(currentFieldName)) {
                keyed = parser.booleanValue();
            } else if ("offset".equals(currentFieldName)) {
                offset = parser.longValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else if (token == XContentParser.Token.START_OBJECT) {
            if ("order".equals(currentFieldName)) {
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else if (token == XContentParser.Token.VALUE_STRING) {
                        String dir = parser.text();
                        boolean asc = "asc".equals(dir);
                        if (!asc && !"desc".equals(dir)) {
                            throw new SearchParseException(context, "Unknown order direction [" + dir + "] in aggregation ["
                                    + aggregationName + "]. Should be either [asc] or [desc]", parser.getTokenLocation());
                        }
                        order = resolveOrder(currentFieldName, asc);
                    }
                }
            } else if (context.parseFieldMatcher().match(currentFieldName, EXTENDED_BOUNDS)) {
                extendedBounds = new ExtendedBounds();
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else if (token.isValue()) {
                        if ("min".equals(currentFieldName)) {
                            extendedBounds.min = parser.longValue(true);
                        } else if ("max".equals(currentFieldName)) {
                            extendedBounds.max = parser.longValue(true);
                        } else {
                            throw new SearchParseException(context, "Unknown extended_bounds key for a " + token + " in aggregation ["
                                    + aggregationName + "]: [" + currentFieldName + "].", parser.getTokenLocation());
                        }
                    }
                }

            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in aggregation [" + aggregationName + "].",
                    parser.getTokenLocation());
        }
    }

    if (interval < 1) {
        throw new SearchParseException(context,
                "Missing required field [interval] for histogram aggregation [" + aggregationName + "]", parser.getTokenLocation());
    }

    Rounding rounding = new Rounding.Interval(interval);
    if (offset != 0) {
        rounding = new Rounding.OffsetRounding((Rounding.Interval) rounding, offset);
    }

    if (extendedBounds != null) {
        // with numeric histogram, we can process here and fail fast if the bounds are invalid
        extendedBounds.processAndValidate(aggregationName, context, ValueParser.RAW);
    }

    return new HistogramAggregator.Factory(aggregationName, vsParser.config(), rounding, order, keyed, minDocCount, extendedBounds,
            new InternalHistogram.Factory());

}
 
Example 13
Source File: PhraseCountQueryBuilder.java    From pyramid with Apache License 2.0 4 votes vote down vote up
public static Optional<PhraseCountQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
    XContentParser parser = parseContext.parser();
    String fieldName = null;
    Object value = null;
    float boost = AbstractQueryBuilder.DEFAULT_BOOST;
    String analyzer = null;
    int slop = MatchQuery.DEFAULT_PHRASE_SLOP;
    boolean inOrder = false;
    boolean weightedCount = false;
    String queryName = null;
    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (parseContext.isDeprecatedSetting(currentFieldName)) {
            // skip
        } else if (token == XContentParser.Token.START_OBJECT) {
            throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
            fieldName = currentFieldName;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (token.isValue()) {
                    if (PhraseCountQueryBuilder.QUERY_FIELD.match(currentFieldName)) {
                        value = parser.objectText();
                    } else if (ANALYZER_FIELD.match(currentFieldName)) {
                        analyzer = parser.text();
                    } else if(IN_ORDER_FIELD.match(currentFieldName)) {
                        inOrder = parser.booleanValue();
                    } else if (WEIGHTED_COUNT_FIELD.match(currentFieldName)) {
                        weightedCount = parser.booleanValue();
                    } else if (BOOST_FIELD.match(currentFieldName)) {
                        boost = parser.floatValue();
                    } else if (SLOP_FIELD.match(currentFieldName)) {
                        slop = parser.intValue();
                    } else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName)) {
                        queryName = parser.text();
                    } else {
                        throw new ParsingException(parser.getTokenLocation(),
                            "[" + NAME + "] query does not support [" + currentFieldName + "]");
                    }
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                        "[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
                }
            }
        } else {
            throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, parser.currentName());
            fieldName = parser.currentName();
            value = parser.objectText();
        }
    }

    PhraseCountQueryBuilder phraseCountQuery = new PhraseCountQueryBuilder(fieldName, value);
    phraseCountQuery.analyzer(analyzer);
    phraseCountQuery.slop(slop);
    phraseCountQuery.inOrder(inOrder);
    phraseCountQuery.weightedCount(weightedCount);
    phraseCountQuery.queryName(queryName);
    phraseCountQuery.boost(boost);
    return Optional.of(phraseCountQuery);
}
 
Example 14
Source File: MetaData.java    From crate with Apache License 2.0 4 votes vote down vote up
public static MetaData fromXContent(XContentParser parser) throws IOException {
    Builder builder = new Builder();

    // we might get here after the meta-data element, or on a fresh parser
    XContentParser.Token token = parser.currentToken();
    String currentFieldName = parser.currentName();
    if (!"meta-data".equals(currentFieldName)) {
        token = parser.nextToken();
        if (token == XContentParser.Token.START_OBJECT) {
            // move to the field name (meta-data)
            token = parser.nextToken();
            if (token != XContentParser.Token.FIELD_NAME) {
                throw new IllegalArgumentException("Expected a field name but got " + token);
            }
            // move to the next object
            token = parser.nextToken();
        }
        currentFieldName = parser.currentName();
    }

    if (!"meta-data".equals(parser.currentName())) {
        throw new IllegalArgumentException("Expected [meta-data] as a field name but got " + currentFieldName);
    }
    if (token != XContentParser.Token.START_OBJECT) {
        throw new IllegalArgumentException("Expected a START_OBJECT but got " + token);
    }

    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.START_OBJECT) {
            if ("cluster_coordination".equals(currentFieldName)) {
                builder.coordinationMetaData(CoordinationMetaData.fromXContent(parser));
            } else if ("settings".equals(currentFieldName)) {
                builder.persistentSettings(Settings.fromXContent(parser));
            } else if ("indices".equals(currentFieldName)) {
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    builder.put(IndexMetaData.Builder.fromXContent(parser), false);
                }
            } else if ("templates".equals(currentFieldName)) {
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    builder.put(IndexTemplateMetaData.Builder.fromXContent(parser, parser.currentName()));
                }
            } else {
                try {
                    Custom custom = parser.namedObject(Custom.class, currentFieldName, null);
                    builder.putCustom(custom.getWriteableName(), custom);
                } catch (NamedObjectNotFoundException ex) {
                    LOGGER.warn("Skipping unknown custom object with type {}", currentFieldName);
                    parser.skipChildren();
                }
            }
        } else if (token.isValue()) {
            if ("version".equals(currentFieldName)) {
                builder.version = parser.longValue();
            } else if ("cluster_uuid".equals(currentFieldName) || "uuid".equals(currentFieldName)) {
                builder.clusterUUID = parser.text();
            } else if ("cluster_uuid_committed".equals(currentFieldName)) {
                builder.clusterUUIDCommitted = parser.booleanValue();
            } else {
                throw new IllegalArgumentException("Unexpected field [" + currentFieldName + "]");
            }
        } else {
            throw new IllegalArgumentException("Unexpected token " + token);
        }
    }
    return builder.build();
}
 
Example 15
Source File: GeohashCellQuery.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    String fieldName = null;
    String geohash = null;
    int levels = -1;
    boolean neighbors = false;


    XContentParser.Token token;
    if ((token = parser.currentToken()) != Token.START_OBJECT) {
        throw new ElasticsearchParseException("failed to parse [{}] query. expected an object but found [{}] instead", NAME, token);
    }

    while ((token = parser.nextToken()) != Token.END_OBJECT) {
        if (token == Token.FIELD_NAME) {
            String field = parser.currentName();

            if (parseContext.isDeprecatedSetting(field)) {
                // skip
            } else if (PRECISION.equals(field)) {
                token = parser.nextToken();
                if(token == Token.VALUE_NUMBER) {
                    levels = parser.intValue();
                } else if(token == Token.VALUE_STRING) {
                    double meters = DistanceUnit.parse(parser.text(), DistanceUnit.DEFAULT, DistanceUnit.METERS);
                    levels = GeoUtils.geoHashLevelsForPrecision(meters);
                }
            } else if (NEIGHBORS.equals(field)) {
                parser.nextToken();
                neighbors = parser.booleanValue();
            } else {
                fieldName = field;
                token = parser.nextToken();
                if(token == Token.VALUE_STRING) {
                    // A string indicates either a gehash or a lat/lon string
                    String location = parser.text();
                    if(location.indexOf(",")>0) {
                        geohash = GeoUtils.parseGeoPoint(parser).geohash();
                    } else {
                        geohash = location;
                    }
                } else {
                    geohash = GeoUtils.parseGeoPoint(parser).geohash();
                }
            }
        } else {
            throw new ElasticsearchParseException("failed to parse [{}] query. unexpected token [{}]", NAME, token);
        }
    }

    if (geohash == null) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing geohash value", NAME);
    }

    MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
    if (fieldType == null) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing [{}] field [{}]", NAME, BaseGeoPointFieldMapper.CONTENT_TYPE, fieldName);
    }

    if (!(fieldType instanceof BaseGeoPointFieldMapper.GeoPointFieldType)) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. field [{}] is not a geo_point field", NAME, fieldName);
    }

    BaseGeoPointFieldMapper.GeoPointFieldType geoFieldType = ((BaseGeoPointFieldMapper.GeoPointFieldType) fieldType);
    if (!geoFieldType.isGeoHashPrefixEnabled()) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. [geohash_prefix] is not enabled for field [{}]", NAME, fieldName);
    }

    if(levels > 0) {
        int len = Math.min(levels, geohash.length());
        geohash = geohash.substring(0, len);
    }

    Query filter;
    if (neighbors) {
        filter = create(parseContext, geoFieldType, geohash, GeoHashUtils.addNeighbors(geohash, new ArrayList<CharSequence>(8)));
    } else {
        filter = create(parseContext, geoFieldType, geohash, null);
    }

    return filter;
}
 
Example 16
Source File: FetchSourceParseElement.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public FetchSourceContext parse(XContentParser parser) throws IOException {
    XContentParser.Token token;

    List<String> includes = null, excludes = null;
    String currentFieldName = null;
    token = parser.currentToken(); // we get it on the value
    if (parser.isBooleanValue()) {
        return new FetchSourceContext(parser.booleanValue());
    } else if (token == XContentParser.Token.VALUE_STRING) {
        return new FetchSourceContext(new String[]{parser.text()});
    } else if (token == XContentParser.Token.START_ARRAY) {
        includes = new ArrayList<>();
        while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
            includes.add(parser.text());
        }
    } else if (token == XContentParser.Token.START_OBJECT) {

        List<String> currentList = null;

        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
                if ("includes".equals(currentFieldName) || "include".equals(currentFieldName)) {
                    currentList = includes != null ? includes : (includes = new ArrayList<>(2));
                } else if ("excludes".equals(currentFieldName) || "exclude".equals(currentFieldName)) {
                    currentList = excludes != null ? excludes : (excludes = new ArrayList<>(2));
                } else {
                    throw new ElasticsearchParseException("source definition may not contain [{}]", parser.text());
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    currentList.add(parser.text());
                }
            } else if (token.isValue()) {
                currentList.add(parser.text());
            } else {
                throw new ElasticsearchParseException("unexpected token while parsing source settings");
            }
        }
    } else {
        throw new ElasticsearchParseException("source element value can be of type [{}]", token.name());
    }

    return new FetchSourceContext(
            includes == null ? Strings.EMPTY_ARRAY : includes.toArray(new String[includes.size()]),
            excludes == null ? Strings.EMPTY_ARRAY : excludes.toArray(new String[excludes.size()]));
}
 
Example 17
Source File: DateRangeParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {

    ValuesSourceParser<ValuesSource.Numeric> vsParser = ValuesSourceParser.numeric(aggregationName, InternalDateRange.TYPE, context)
            .targetValueType(ValueType.DATE)
            .formattable(true)
            .build();

    List<RangeAggregator.Range> ranges = null;
    boolean keyed = false;

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("ranges".equals(currentFieldName)) {
                ranges = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    double from = Double.NEGATIVE_INFINITY;
                    String fromAsStr = null;
                    double to = Double.POSITIVE_INFINITY;
                    String toAsStr = null;
                    String key = null;
                    String toOrFromOrKey = null;
                    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                        if (token == XContentParser.Token.FIELD_NAME) {
                            toOrFromOrKey = parser.currentName();
                        } else if (token == XContentParser.Token.VALUE_NUMBER) {
                            if ("from".equals(toOrFromOrKey)) {
                                from = parser.doubleValue();
                            } else if ("to".equals(toOrFromOrKey)) {
                                to = parser.doubleValue();
                            } else {
                                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName
                                        + "]: [" + currentFieldName + "].", parser.getTokenLocation());
                            }
                        } else if (token == XContentParser.Token.VALUE_STRING) {
                            if ("from".equals(toOrFromOrKey)) {
                                fromAsStr = parser.text();
                            } else if ("to".equals(toOrFromOrKey)) {
                                toAsStr = parser.text();
                            } else if ("key".equals(toOrFromOrKey)) {
                                key = parser.text();
                            } else {
                                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].", parser.getTokenLocation());
                            }
                        }
                    }
                    ranges.add(new RangeAggregator.Range(key, from, fromAsStr, to, toAsStr));
                }
            }
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("keyed".equals(currentFieldName)) {
                keyed = parser.booleanValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].",
                    parser.getTokenLocation());
        }
    }

    if (ranges == null) {
        throw new SearchParseException(context, "Missing [ranges] in ranges aggregator [" + aggregationName + "]",
                parser.getTokenLocation());
    }

    return new RangeAggregator.Factory(aggregationName, vsParser.config(), InternalDateRange.FACTORY, ranges, keyed);
}
 
Example 18
Source File: RangeParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {

    List<RangeAggregator.Range> ranges = null;
    boolean keyed = false;

    ValuesSourceParser<ValuesSource.Numeric> vsParser = ValuesSourceParser.numeric(aggregationName, InternalRange.TYPE, context)
            .formattable(true)
            .build();

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("ranges".equals(currentFieldName)) {
                ranges = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    double from = Double.NEGATIVE_INFINITY;
                    String fromAsStr = null;
                    double to = Double.POSITIVE_INFINITY;
                    String toAsStr = null;
                    String key = null;
                    String toOrFromOrKey = null;
                    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                        if (token == XContentParser.Token.FIELD_NAME) {
                            toOrFromOrKey = parser.currentName();
                        } else if (token == XContentParser.Token.VALUE_NUMBER) {
                            if ("from".equals(toOrFromOrKey)) {
                                from = parser.doubleValue();
                            } else if ("to".equals(toOrFromOrKey)) {
                                to = parser.doubleValue();
                            }
                        } else if (token == XContentParser.Token.VALUE_STRING) {
                            if ("from".equals(toOrFromOrKey)) {
                                fromAsStr = parser.text();
                            } else if ("to".equals(toOrFromOrKey)) {
                                toAsStr = parser.text();
                            } else if ("key".equals(toOrFromOrKey)) {
                                key = parser.text();
                            }
                        }
                    }
                    ranges.add(new RangeAggregator.Range(key, from, fromAsStr, to, toAsStr));
                }
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("keyed".equals(currentFieldName)) {
                keyed = parser.booleanValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].",
                    parser.getTokenLocation());
        }
    }

    if (ranges == null) {
        throw new SearchParseException(context, "Missing [ranges] in ranges aggregator [" + aggregationName + "]",
                parser.getTokenLocation());
    }

    return new RangeAggregator.Factory(aggregationName, vsParser.config(), InternalRange.FACTORY, ranges, keyed);
}
 
Example 19
Source File: SnapshotInfo.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * This method creates a SnapshotInfo from internal x-content.  It does not
 * handle x-content written with the external version as external x-content
 * is only for display purposes and does not need to be parsed.
 */
public static SnapshotInfo fromXContentInternal(final XContentParser parser) throws IOException {
    String name = null;
    String uuid = null;
    Version version = Version.CURRENT;
    SnapshotState state = SnapshotState.IN_PROGRESS;
    String reason = null;
    List<String> indices = Collections.emptyList();
    long startTime = 0;
    long endTime = 0;
    int totalShards = 0;
    int successfulShards = 0;
    Boolean includeGlobalState = null;
    List<SnapshotShardFailure> shardFailures = Collections.emptyList();
    if (parser.currentToken() == null) { // fresh parser? move to the first token
        parser.nextToken();
    }
    if (parser.currentToken() == XContentParser.Token.START_OBJECT) {  // on a start object move to next token
        parser.nextToken();
    }
    XContentParser.Token token;
    if ((token = parser.nextToken()) == XContentParser.Token.START_OBJECT) {
        String currentFieldName = parser.currentName();
        if (SNAPSHOT.equals(currentFieldName)) {
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                    token = parser.nextToken();
                    if (token.isValue()) {
                        if (NAME.equals(currentFieldName)) {
                            name = parser.text();
                        } else if (UUID.equals(currentFieldName)) {
                            uuid = parser.text();
                        } else if (STATE.equals(currentFieldName)) {
                            state = SnapshotState.valueOf(parser.text());
                        } else if (REASON.equals(currentFieldName)) {
                            reason = parser.text();
                        } else if (START_TIME.equals(currentFieldName)) {
                            startTime = parser.longValue();
                        } else if (END_TIME.equals(currentFieldName)) {
                            endTime = parser.longValue();
                        } else if (TOTAL_SHARDS.equals(currentFieldName)) {
                            totalShards = parser.intValue();
                        } else if (SUCCESSFUL_SHARDS.equals(currentFieldName)) {
                            successfulShards = parser.intValue();
                        } else if (VERSION_ID.equals(currentFieldName)) {
                            version = Version.fromId(parser.intValue());
                        } else if (INCLUDE_GLOBAL_STATE.equals(currentFieldName)) {
                            includeGlobalState = parser.booleanValue();
                        }
                    } else if (token == XContentParser.Token.START_ARRAY) {
                        if (INDICES.equals(currentFieldName)) {
                            ArrayList<String> indicesArray = new ArrayList<>();
                            while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                                indicesArray.add(parser.text());
                            }
                            indices = Collections.unmodifiableList(indicesArray);
                        } else if (FAILURES.equals(currentFieldName)) {
                            ArrayList<SnapshotShardFailure> shardFailureArrayList = new ArrayList<>();
                            while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                                shardFailureArrayList.add(SnapshotShardFailure.fromXContent(parser));
                            }
                            shardFailures = Collections.unmodifiableList(shardFailureArrayList);
                        } else {
                            // It was probably created by newer version - ignoring
                            parser.skipChildren();
                        }
                    } else if (token == XContentParser.Token.START_OBJECT) {
                        // It was probably created by newer version - ignoring
                        parser.skipChildren();
                    }
                }
            }
        }
    } else {
        throw new ElasticsearchParseException("unexpected token  [" + token + "]");
    }
    if (uuid == null) {
        // the old format where there wasn't a UUID
        uuid = name;
    }
    return new SnapshotInfo(new SnapshotId(name, uuid),
                            indices,
                            state,
                            reason,
                            version,
                            startTime,
                            endTime,
                            totalShards,
                            successfulShards,
                            shardFailures,
                            includeGlobalState);
}
 
Example 20
Source File: AnomalyDetectorJob.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
public static AnomalyDetectorJob parse(XContentParser parser) throws IOException {
    String name = null;
    Schedule schedule = null;
    TimeConfiguration windowDelay = null;
    // we cannot set it to null as isEnabled() would do the unboxing and results in null pointer exception
    Boolean isEnabled = Boolean.FALSE;
    Instant enabledTime = null;
    Instant disabledTime = null;
    Instant lastUpdateTime = null;
    Long lockDurationSeconds = DEFAULT_AD_JOB_LOC_DURATION_SECONDS;

    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
    while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
        String fieldName = parser.currentName();
        parser.nextToken();

        switch (fieldName) {
            case NAME_FIELD:
                name = parser.text();
                break;
            case SCHEDULE_FIELD:
                schedule = ScheduleParser.parse(parser);
                break;
            case WINDOW_DELAY_FIELD:
                windowDelay = TimeConfiguration.parse(parser);
                break;
            case IS_ENABLED_FIELD:
                isEnabled = parser.booleanValue();
                break;
            case ENABLED_TIME_FIELD:
                enabledTime = ParseUtils.toInstant(parser);
                break;
            case DISABLED_TIME_FIELD:
                disabledTime = ParseUtils.toInstant(parser);
                break;
            case LAST_UPDATE_TIME_FIELD:
                lastUpdateTime = ParseUtils.toInstant(parser);
                break;
            case LOCK_DURATION_SECONDS:
                lockDurationSeconds = parser.longValue();
                break;
            default:
                parser.skipChildren();
                break;
        }
    }
    return new AnomalyDetectorJob(
        name,
        schedule,
        windowDelay,
        isEnabled,
        enabledTime,
        disabledTime,
        lastUpdateTime,
        lockDurationSeconds
    );
}