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

The following examples show how to use org.elasticsearch.common.xcontent.XContentParser#skipChildren() . 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: ShapeFetchService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches the Shape with the given ID in the given type and index.
 *
 * @param getRequest GetRequest containing index, type and id
 * @param path      Name or path of the field in the Shape Document where the Shape itself is located
 * @return Shape with the given ID
 * @throws IOException Can be thrown while parsing the Shape Document and extracting the Shape
 */
public ShapeBuilder fetch(GetRequest getRequest,String path) throws IOException {
    getRequest.preference("_local");
    getRequest.operationThreaded(false);
    GetResponse response = client.get(getRequest).actionGet();
    if (!response.isExists()) {
        throw new IllegalArgumentException("Shape with ID [" + getRequest.id() + "] in type [" + getRequest.type() + "] not found");
    }

    String[] pathElements = Strings.splitStringToArray(path, '.');
    int currentPathSlot = 0;

    XContentParser parser = null;
    try {
        parser = XContentHelper.createParser(response.getSourceAsBytesRef());
        XContentParser.Token currentToken;
        while ((currentToken = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (currentToken == XContentParser.Token.FIELD_NAME) {
                if (pathElements[currentPathSlot].equals(parser.currentName())) {
                    parser.nextToken();
                    if (++currentPathSlot == pathElements.length) {
                        return ShapeBuilder.parse(parser);
                    }
                } else {
                    parser.nextToken();
                    parser.skipChildren();
                }
            }
        }
        throw new IllegalStateException("Shape with name [" + getRequest.id() + "] found but missing " + path + " field");
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}
 
Example 2
Source File: GeoJsonParser.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Recursive method which parses the arrays of coordinates used to define
 * Shapes
 *
 * @param parser
 *            Parser that will be read from
 * @return CoordinateNode representing the start of the coordinate tree
 * @throws IOException
 *             Thrown if an error occurs while reading from the
 *             XContentParser
 */
private static CoordinateNode parseCoordinates(XContentParser parser, boolean ignoreZValue) throws IOException {
    if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
        parser.skipChildren();
        parser.nextToken();
        throw new ElasticsearchParseException("coordinates cannot be specified as objects");
    }

    XContentParser.Token token = parser.nextToken();
    // Base cases
    if (token != XContentParser.Token.START_ARRAY &&
        token != XContentParser.Token.END_ARRAY &&
        token != XContentParser.Token.VALUE_NULL) {
        return new CoordinateNode(parseCoordinate(parser, ignoreZValue));
    } else if (token == XContentParser.Token.VALUE_NULL) {
        throw new IllegalArgumentException("coordinates cannot contain NULL values)");
    }

    List<CoordinateNode> nodes = new ArrayList<>();
    while (token != XContentParser.Token.END_ARRAY) {
        CoordinateNode node = parseCoordinates(parser, ignoreZValue);
        if (nodes.isEmpty() == false && nodes.get(0).numDimensions() != node.numDimensions()) {
            throw new ElasticsearchParseException("Exception parsing coordinates: number of dimensions do not match");
        }
        nodes.add(node);
        token = parser.nextToken();
    }

    return new CoordinateNode(nodes);
}
 
Example 3
Source File: ReplicationResponse.java    From crate with Apache License 2.0 5 votes vote down vote up
public static Failure fromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.currentToken();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);

    String shardIndex = null, nodeId = null;
    int shardId = -1;
    boolean primary = false;
    RestStatus status = null;
    ElasticsearchException reason = null;

    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 (INDEX.equals(currentFieldName)) {
                shardIndex = parser.text();
            } else if (SHARD.equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if (NODE.equals(currentFieldName)) {
                nodeId = parser.text();
            } else if (STATUS.equals(currentFieldName)) {
                status = RestStatus.valueOf(parser.text());
            } else if (PRIMARY.equals(currentFieldName)) {
                primary = parser.booleanValue();
            }
        } else if (token == XContentParser.Token.START_OBJECT) {
            if (REASON.equals(currentFieldName)) {
                reason = ElasticsearchException.fromXContent(parser);
            } else {
                parser.skipChildren(); // skip potential inner objects for forward compatibility
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            parser.skipChildren(); // skip potential inner arrays for forward compatibility
        }
    }
    return new Failure(new ShardId(shardIndex, IndexMetaData.INDEX_UUID_NA_VALUE, shardId), nodeId, reason, status, primary);
}
 
Example 4
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
    );
}
 
Example 5
Source File: AnomalyResult.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
public static AnomalyResult parse(XContentParser parser) throws IOException {
    String detectorId = null;
    Double anomalyScore = null;
    Double anomalyGrade = null;
    Double confidence = null;
    List<FeatureData> featureData = new ArrayList<>();
    Instant dataStartTime = null;
    Instant dataEndTime = null;
    Instant executionStartTime = null;
    Instant executionEndTime = null;
    String error = 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 DETECTOR_ID_FIELD:
                detectorId = parser.text();
                break;
            case ANOMALY_SCORE_FIELD:
                anomalyScore = parser.doubleValue();
                break;
            case ANOMALY_GRADE_FIELD:
                anomalyGrade = parser.doubleValue();
                break;
            case CONFIDENCE_FIELD:
                confidence = parser.doubleValue();
                break;
            case FEATURE_DATA_FIELD:
                ensureExpectedToken(XContentParser.Token.START_ARRAY, parser.currentToken(), parser::getTokenLocation);
                while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                    featureData.add(FeatureData.parse(parser));
                }
                break;
            case DATA_START_TIME_FIELD:
                dataStartTime = ParseUtils.toInstant(parser);
                break;
            case DATA_END_TIME_FIELD:
                dataEndTime = ParseUtils.toInstant(parser);
                break;
            case EXECUTION_START_TIME_FIELD:
                executionStartTime = ParseUtils.toInstant(parser);
                break;
            case EXECUTION_END_TIME_FIELD:
                executionEndTime = ParseUtils.toInstant(parser);
                break;
            case ERROR_FIELD:
                error = parser.text();
                break;
            default:
                parser.skipChildren();
                break;
        }
    }
    return new AnomalyResult(
        detectorId,
        anomalyScore,
        anomalyGrade,
        confidence,
        featureData,
        dataStartTime,
        dataEndTime,
        executionStartTime,
        executionEndTime,
        error
    );
}
 
Example 6
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;
        }
    }
}
 
Example 7
Source File: ShapeBuilder.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Parse the geometry specified by the source document and return a ShapeBuilder instance used to
 * build the actual geometry
 * @param parser - parse utility object including source document
 * @param shapeMapper - field mapper needed for index specific parameters
 * @return ShapeBuilder - a builder instance used to create the geometry
 */
public static ShapeBuilder parse(XContentParser parser, GeoShapeFieldMapper shapeMapper) throws IOException {
    if (parser.currentToken() == XContentParser.Token.VALUE_NULL) {
        return null;
    } else if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
        throw new ElasticsearchParseException("shape must be an object consisting of type and coordinates");
    }

    GeoShapeType shapeType = null;
    Distance radius = null;
    CoordinateNode node = null;
    GeometryCollectionBuilder geometryCollections = null;

    Orientation requestedOrientation = (shapeMapper == null) ? Orientation.RIGHT : shapeMapper.fieldType().orientation();
    boolean coerce = (shapeMapper == null) ? GeoShapeFieldMapper.Defaults.COERCE.value() : shapeMapper.coerce().value();

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

            if (FIELD_TYPE.equals(fieldName)) {
                parser.nextToken();
                shapeType = GeoShapeType.forName(parser.text());
            } else if (FIELD_COORDINATES.equals(fieldName)) {
                parser.nextToken();
                node = parseCoordinates(parser);
            } else if (FIELD_GEOMETRIES.equals(fieldName)) {
                parser.nextToken();
                geometryCollections = parseGeometries(parser, shapeMapper);
            } else if (CircleBuilder.FIELD_RADIUS.equals(fieldName)) {
                parser.nextToken();
                radius = Distance.parseDistance(parser.text());
            } else if (FIELD_ORIENTATION.equals(fieldName)) {
                parser.nextToken();
                requestedOrientation = orientationFromString(parser.text());
            } else {
                parser.nextToken();
                parser.skipChildren();
            }
        }
    }

    if (shapeType == null) {
        throw new ElasticsearchParseException("shape type not included");
    } else if (node == null && GeoShapeType.GEOMETRYCOLLECTION != shapeType) {
        throw new ElasticsearchParseException("coordinates not included");
    } else if (geometryCollections == null && GeoShapeType.GEOMETRYCOLLECTION == shapeType) {
        throw new ElasticsearchParseException("geometries not included");
    } else if (radius != null && GeoShapeType.CIRCLE != shapeType) {
        throw new ElasticsearchParseException("field [{}] is supported for [{}] only", CircleBuilder.FIELD_RADIUS, CircleBuilder.TYPE);
    }

    switch (shapeType) {
        case POINT: return parsePoint(node);
        case MULTIPOINT: return parseMultiPoint(node);
        case LINESTRING: return parseLineString(node);
        case MULTILINESTRING: return parseMultiLine(node);
        case POLYGON: return parsePolygon(node, requestedOrientation, coerce);
        case MULTIPOLYGON: return parseMultiPolygon(node, requestedOrientation, coerce);
        case CIRCLE: return parseCircle(node, radius);
        case ENVELOPE: return parseEnvelope(node, requestedOrientation);
        case GEOMETRYCOLLECTION: return geometryCollections;
        default:
            throw new ElasticsearchParseException("shape type [{}] not included", shapeType);
    }
}
 
Example 8
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 9
Source File: AliasMetaData.java    From crate with Apache License 2.0 4 votes vote down vote up
public static AliasMetaData fromXContent(XContentParser parser) throws IOException {
    Builder builder = new Builder(parser.currentName());

    String currentFieldName = null;
    XContentParser.Token token = parser.nextToken();
    if (token == null) {
        // no data...
        return builder.build();
    }
    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 ("filter".equals(currentFieldName)) {
                Map<String, Object> filter = parser.mapOrdered();
                builder.filter(filter);
            } else {
                parser.skipChildren();
            }
        } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) {
            if ("filter".equals(currentFieldName)) {
                builder.filter(new CompressedXContent(parser.binaryValue()));
            }
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if ("routing".equals(currentFieldName)) {
                builder.routing(parser.text());
            } else if ("index_routing".equals(currentFieldName) || "indexRouting".equals(currentFieldName)) {
                builder.indexRouting(parser.text());
            } else if ("search_routing".equals(currentFieldName) || "searchRouting".equals(currentFieldName)) {
                builder.searchRouting(parser.text());
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            parser.skipChildren();
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("is_write_index".equals(currentFieldName)) {
                builder.writeIndex(parser.booleanValue());
            }
        }
    }
    return builder.build();
}
 
Example 10
Source File: GeoJsonParser.java    From crate with Apache License 2.0 4 votes vote down vote up
protected static ShapeBuilder parse(XContentParser parser, GeoShapeFieldMapper shapeMapper)
    throws IOException {
    GeoShapeType shapeType = null;
    DistanceUnit.Distance radius = null;
    CoordinateNode coordinateNode = null;
    GeometryCollectionBuilder geometryCollections = null;

    ShapeBuilder.Orientation requestedOrientation =
        (shapeMapper == null) ? ShapeBuilder.Orientation.RIGHT : shapeMapper.fieldType().orientation();
    final Explicit<Boolean> coerce = (shapeMapper == null) ? GeoShapeFieldMapper.Defaults.COERCE : shapeMapper.coerce();
    final Explicit<Boolean> ignoreZValue = (shapeMapper == null) ? GeoShapeFieldMapper.Defaults.IGNORE_Z_VALUE : shapeMapper.ignoreZValue();

    String malformedException = null;

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

                if (ShapeParser.FIELD_TYPE.match(fieldName, parser.getDeprecationHandler())) {
                    parser.nextToken();
                    final GeoShapeType type = GeoShapeType.forName(parser.text());
                    if (shapeType != null && shapeType.equals(type) == false) {
                        malformedException = ShapeParser.FIELD_TYPE + " already parsed as ["
                            + shapeType + "] cannot redefine as [" + type + "]";
                    } else {
                        shapeType = type;
                    }
                } else if (ShapeParser.FIELD_COORDINATES.match(fieldName, parser.getDeprecationHandler())) {
                    parser.nextToken();
                    CoordinateNode tempNode = parseCoordinates(parser, ignoreZValue.value());
                    if (coordinateNode != null && tempNode.numDimensions() != coordinateNode.numDimensions()) {
                        throw new ElasticsearchParseException("Exception parsing coordinates: " +
                            "number of dimensions do not match");
                    }
                    coordinateNode = tempNode;
                } else if (ShapeParser.FIELD_GEOMETRIES.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType == null) {
                        shapeType = GeoShapeType.GEOMETRYCOLLECTION;
                    } else if (shapeType.equals(GeoShapeType.GEOMETRYCOLLECTION) == false) {
                        malformedException = "cannot have [" + ShapeParser.FIELD_GEOMETRIES + "] with type set to ["
                            + shapeType + "]";
                    }
                    parser.nextToken();
                    geometryCollections = parseGeometries(parser, shapeMapper);
                } else if (CircleBuilder.FIELD_RADIUS.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType == null) {
                        shapeType = GeoShapeType.CIRCLE;
                    } else if (shapeType.equals(GeoShapeType.CIRCLE) == false) {
                        malformedException = "cannot have [" + CircleBuilder.FIELD_RADIUS + "] with type set to ["
                            + shapeType + "]";
                    }
                    parser.nextToken();
                    radius = DistanceUnit.Distance.parseDistance(parser.text());
                } else if (ShapeParser.FIELD_ORIENTATION.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType != null
                        && (shapeType.equals(GeoShapeType.POLYGON) || shapeType.equals(GeoShapeType.MULTIPOLYGON)) == false) {
                        malformedException = "cannot have [" + ShapeParser.FIELD_ORIENTATION + "] with type set to [" + shapeType + "]";
                    }
                    parser.nextToken();
                    requestedOrientation = ShapeBuilder.Orientation.fromString(parser.text());
                } else {
                    parser.nextToken();
                    parser.skipChildren();
                }
            }
        }
    } catch (Exception ex) {
        // Skip all other fields until the end of the object
        while (parser.currentToken() != XContentParser.Token.END_OBJECT && parser.currentToken() != null) {
            parser.nextToken();
            parser.skipChildren();
        }
        throw ex;
    }

    if (malformedException != null) {
        throw new ElasticsearchParseException(malformedException);
    } else if (shapeType == null) {
        throw new ElasticsearchParseException("shape type not included");
    } else if (coordinateNode == null && GeoShapeType.GEOMETRYCOLLECTION != shapeType) {
        throw new ElasticsearchParseException("coordinates not included");
    } else if (geometryCollections == null && GeoShapeType.GEOMETRYCOLLECTION == shapeType) {
        throw new ElasticsearchParseException("geometries not included");
    } else if (radius != null && GeoShapeType.CIRCLE != shapeType) {
        throw new ElasticsearchParseException("field [{}] is supported for [{}] only", CircleBuilder.FIELD_RADIUS,
            CircleBuilder.TYPE);
    }

    if (shapeType.equals(GeoShapeType.GEOMETRYCOLLECTION)) {
        return geometryCollections;
    }

    return shapeType.getBuilder(coordinateNode, radius, requestedOrientation, coerce.value());
}
 
Example 11
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);
}