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

The following examples show how to use org.elasticsearch.common.xcontent.XContentParser#currentToken() . 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: UserMetadata.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static UserMetadata fromXContent(XContentParser parser) throws IOException {
    Builder builder = new Builder();
    XContentParser.Token token = parser.currentToken();
    String currentFieldName = parser.currentName();
    if (currentFieldName == "users") {
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.START_OBJECT) {
                UserProperty userProperty = UserProperty.Builder.fromXContent(parser);
                builder.addOrChangeUserProperty(userProperty.getUsernameWithTenant(), userProperty);
            }
        }
    }
    return builder.build();
}
 
Example 2
Source File: CategoryContextMapping.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public FieldQuery parseQuery(String name, XContentParser parser) throws IOException, ElasticsearchParseException {
    Iterable<? extends CharSequence> values;
    Token token = parser.currentToken();
    if (token == Token.START_ARRAY) {
        ArrayList<String> list = new ArrayList<>();
        while ((token = parser.nextToken()) != Token.END_ARRAY) {
            list.add(parser.text());
        }
        values = list;
    } else if (token == Token.VALUE_NULL) {
        values = defaultValues;
    } else {
        values = Collections.singleton(parser.text());
    }

    return new FieldQuery(name, values);
}
 
Example 3
Source File: ElasticsearchException.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the output of {@link #generateFailureXContent(XContentBuilder, Params, Exception, boolean)}
 */
public static ElasticsearchException failureFromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.currentToken();
    ensureFieldName(parser, token, ERROR);

    token = parser.nextToken();
    if (token.isValue()) {
        return new ElasticsearchException(buildMessage("exception", parser.text(), null));
    }

    ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);
    token = parser.nextToken();

    // Root causes are parsed in the innerFromXContent() and are added as suppressed exceptions.
    return innerFromXContent(parser, true);
}
 
Example 4
Source File: MoreLikeThisQueryParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private static void parseLikeField(QueryParseContext parseContext, List<String> texts, List<Item> items) throws IOException {
    XContentParser parser = parseContext.parser();
    if (parser.currentToken().isValue()) {
        texts.add(parser.text());
    } else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
        items.add(Item.parse(parser, parseContext.parseFieldMatcher(), new Item()));
    } else {
        throw new IllegalArgumentException("Content of 'like' parameter should either be a string or an object");
    }
}
 
Example 5
Source File: AnomalyDetectorExecutionInput.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public static AnomalyDetectorExecutionInput parse(XContentParser parser, String detectorId) throws IOException {
    Instant periodStart = null;
    Instant periodEnd = null;
    AnomalyDetector detector = 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 PERIOD_START_FIELD:
                periodStart = ParseUtils.toInstant(parser);
                break;
            case PERIOD_END_FIELD:
                periodEnd = ParseUtils.toInstant(parser);
                break;
            case DETECTOR_FIELD:
                XContentParser.Token token = parser.currentToken();
                if (parser.currentToken().equals(XContentParser.Token.START_OBJECT)) {
                    detector = AnomalyDetector.parse(parser, detectorId);
                }
                break;
            default:
                break;
        }
    }
    return new AnomalyDetectorExecutionInput(detectorId, periodStart, periodEnd, detector);
}
 
Example 6
Source File: UserDefinedFunctionMetaData.java    From crate with Apache License 2.0 5 votes vote down vote up
private static String parseStringField(XContentParser parser) throws IOException {
    if (parser.nextToken() != XContentParser.Token.VALUE_STRING && parser.currentToken()
        != XContentParser.Token.VALUE_NULL) {
        throw new UnhandledServerException("failed to parse function");
    }
    return parser.textOrNull();
}
 
Example 7
Source File: IncludeExclude.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private Set<BytesRef> parseArrayToSet(XContentParser parser) throws IOException {
    final Set<BytesRef> set = new HashSet<>();
    if (parser.currentToken() != XContentParser.Token.START_ARRAY) {
        throw new ElasticsearchParseException("Missing start of array in include/exclude clause");
    }
    while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
        if (!parser.currentToken().isValue()) {
            throw new ElasticsearchParseException("Array elements in include/exclude clauses should be string values");
        }
        set.add(new BytesRef(parser.text()));
    }
    return set;
}
 
Example 8
Source File: JsonXContentGenerator.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void copyCurrentStructure(XContentParser parser) throws IOException {
    // the start of the parser
    if (parser.currentToken() == null) {
        parser.nextToken();
    }
    if (parser instanceof JsonXContentParser) {
        generator.copyCurrentStructure(((JsonXContentParser) parser).parser);
    } else {
        copyCurrentStructure(this, parser);
    }
}
 
Example 9
Source File: ImportCompressionParseElement.java    From elasticsearch-inout-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, ImportContext context)
        throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token.isValue()) {
        String lower = parser.text().toLowerCase();
        if (lower.equals("gzip")) {
            ((ImportContext) context).compression(true);
        } else if (!lower.isEmpty()) {
            throw new ImportParseException(context,
                    "Compression format '" + lower + "' unknown or not supported.");
        }
    }
}
 
Example 10
Source File: ProfileParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SearchContext context) throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token.isValue()) {
        context.request().setProfile(parser.booleanValue());
        //((DefaultSearchContext)context).setProfilers(new Profilers(context.searcher()));
    }
}
 
Example 11
Source File: Script.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected Script createSimpleScript(XContentParser parser) throws IOException {
    if (parser.currentToken() == XContentParser.Token.VALUE_STRING) {
        return new Script(parser.text());
    } else {
        throw new ScriptParseException("expected a string value for field [{}], but found [{}]", parser.currentName(),
                parser.currentToken());
    }
}
 
Example 12
Source File: ImportSettingsParseElement.java    From elasticsearch-inout-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, ImportContext context)
        throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token.isValue()) {
        ((ImportContext)context).settings(parser.booleanValue());
    }
}
 
Example 13
Source File: SQLArgsParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SQLXContentSourceContext context) throws Exception {
    XContentParser.Token token = parser.currentToken();

    if (token != XContentParser.Token.START_ARRAY) {
        throw new SQLParseSourceException(context, "Field [" + parser.currentName() + "] has an invalid value");
    }

    Object[] params = parseSubArray(context, parser);
    context.args(params);
}
 
Example 14
Source File: ExportMappingsParseElement.java    From elasticsearch-inout-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SearchContext context)
        throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token.isValue()) {
        ((ExportContext)context).mappings(parser.booleanValue());
    }
}
 
Example 15
Source File: TrackScoresParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SearchContext context) throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token.isValue()) {
        context.trackScores(parser.booleanValue());
    }
}
 
Example 16
Source File: FromParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SearchContext context) throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token.isValue()) {
        int from = parser.intValue();
        if (from < 0) {
            throw new SearchParseException(context, "from is set to [" + from + "] and is expected to be higher or equal to 0",
                    parser.getTokenLocation());
        }
        context.from(from);
    }
}
 
Example 17
Source File: JsonXContentGenerator.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Low level implementation detail of {@link XContentGenerator#copyCurrentStructure(XContentParser)}.
 */
private static void copyCurrentStructure(XContentGenerator destination, XContentParser parser) throws IOException {
    XContentParser.Token token = parser.currentToken();

    // Let's handle field-name separately first
    if (token == XContentParser.Token.FIELD_NAME) {
        destination.writeFieldName(parser.currentName());
        token = parser.nextToken();
        // fall-through to copy the associated value
    }

    switch (token) {
        case START_ARRAY:
            destination.writeStartArray();
            while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                copyCurrentStructure(destination, parser);
            }
            destination.writeEndArray();
            break;
        case START_OBJECT:
            destination.writeStartObject();
            while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
                copyCurrentStructure(destination, parser);
            }
            destination.writeEndObject();
            break;
        default: // others are simple:
            destination.copyCurrentEvent(parser);
    }
}
 
Example 18
Source File: ParseUtils.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
/**
 * Parse content parser to {@link java.time.Instant}.
 *
 * @param parser json based content parser
 * @return instance of {@link java.time.Instant}
 * @throws IOException IOException if content can't be parsed correctly
 */
public static Instant toInstant(XContentParser parser) throws IOException {
    if (parser.currentToken() == null || parser.currentToken() == XContentParser.Token.VALUE_NULL) {
        return null;
    }
    if (parser.currentToken().isValue()) {
        return Instant.ofEpochMilli(parser.longValue());
    }
    return null;
}
 
Example 19
Source File: TenantProperty.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public static TenantProperty fromXContent(XContentParser parser) throws IOException {
    Builder builder = new Builder();
    XContentParser.Token token = parser.currentToken();
    String currentFieldName = parser.currentName();
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if ("name".equalsIgnoreCase(currentFieldName)) {
                builder.tenantName = parser.text();
            }
        } else if (token == XContentParser.Token.VALUE_NUMBER) {
            if ("id".equalsIgnoreCase(currentFieldName)) {
                builder.tenantId = parser.longValue();
            } else if ("desire_node_num".equalsIgnoreCase(currentFieldName)) {
                builder.desireInstanceNum = parser.intValue();
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("nodes".equalsIgnoreCase(currentFieldName)) {
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    if (token == XContentParser.Token.START_OBJECT) {
                        String ipaddress = "";
                        int port = 0;
                        AllocatedNodeStatus allocatedNodeStatus = AllocatedNodeStatus.NORMAL;
                        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                            if (token == XContentParser.Token.FIELD_NAME) {
                                currentFieldName = parser.currentName();
                            } else if (token == XContentParser.Token.VALUE_STRING) {
                                if ("ip".equalsIgnoreCase(currentFieldName)) {
                                    ipaddress = parser.text();
                                } else if ("status".equalsIgnoreCase(currentFieldName)) {
                                    allocatedNodeStatus = AllocatedNodeStatus.valueOf(parser.text());
                                }
                            } else if (token == XContentParser.Token.VALUE_NUMBER) {
                                if ("port".equalsIgnoreCase(currentFieldName)) {
                                    port = parser.intValue();
                                }
                            }
                        }
                        AllocatedNodeInfo nodeId = new AllocatedNodeInfo(ipaddress, port, allocatedNodeStatus);
                        builder.addNode(nodeId);
                    }
                }
            }
        }
    }
    return builder.build();
}
 
Example 20
Source File: MappingMetaData.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private void innerParse(XContentParser parser, ParseContext context) throws IOException {
    if (!context.parsingStillNeeded()) {
        return;
    }

    XContentParser.Token token = parser.currentToken();
    if (token == null) {
        token = parser.nextToken();
    }
    if (token == XContentParser.Token.START_OBJECT) {
        token = parser.nextToken();
    }
    String idPart = context.idParsingStillNeeded() ? id().pathElements()[context.locationId] : null;
    String routingPart = context.routingParsingStillNeeded() ? routing().pathElements()[context.locationRouting] : null;
    String timestampPart = context.timestampParsingStillNeeded() ? timestamp().pathElements()[context.locationTimestamp] : null;
    String versionPart = context.versionParsingStillNeeded() ? version().pathElements()[context.locationVersion] : null;
    
    for (; token == XContentParser.Token.FIELD_NAME; token = parser.nextToken()) {
        // Must point to field name
        String fieldName = parser.currentName();
        // And then the value...
        token = parser.nextToken();
        boolean incLocationId = false;
        boolean incLocationRouting = false;
        boolean incLocationTimestamp = false;
        boolean incLocationVersion = false;
        if (context.idParsingStillNeeded() && fieldName.equals(idPart)) {
            if (context.locationId + 1 == id.pathElements().length) {
                if (!token.isValue()) {
                    throw new MapperParsingException("id field must be a value but was either an object or an array");
                }
                context.id = parser.textOrNull();
                context.idResolved = true;
            } else {
                incLocationId = true;
            }
        }
        if (context.routingParsingStillNeeded() && fieldName.equals(routingPart)) {
            if (context.locationRouting + 1 == routing.pathElements().length) {
                context.routing = parser.textOrNull();
                context.routingResolved = true;
            } else {
                incLocationRouting = true;
            }
        }
        if (context.timestampParsingStillNeeded() && fieldName.equals(timestampPart)) {
            if (context.locationTimestamp + 1 == timestamp.pathElements().length) {
                context.timestamp = parser.textOrNull();
                context.timestampResolved = true;
            } else {
                incLocationTimestamp = true;
            }
        }
        
        if (context.versionParsingStillNeeded() && fieldName.equals(versionPart)) {
            if (context.locationVersion + 1 == version.pathElements().length) {
                context.version = parser.textOrNull();
                context.versionResolved = true;
            } else {
                incLocationVersion = true;
            }
        }
        if (incLocationId || incLocationRouting || incLocationTimestamp || incLocationVersion) {
            if (token == XContentParser.Token.START_OBJECT) {
                context.locationId += incLocationId ? 1 : 0;
                context.locationRouting += incLocationRouting ? 1 : 0;
                context.locationTimestamp += incLocationTimestamp ? 1 : 0;
                context.locationVersion += incLocationVersion ? 1 : 0;
                innerParse(parser, context);
                context.locationId -= incLocationId ? 1 : 0;
                context.locationRouting -= incLocationRouting ? 1 : 0;
                context.locationTimestamp -= incLocationTimestamp ? 1 : 0;
            }
        } else {
            parser.skipChildren();
        }

        if (!context.parsingStillNeeded()) {
            return;
        }
    }
}