Java Code Examples for org.elasticsearch.common.xcontent.XContentHelper#createParser()

The following examples show how to use org.elasticsearch.common.xcontent.XContentHelper#createParser() . 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: BlobStoreRepository.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Reads snapshot index file
 * <p>
 * This file can be used by read-only repositories that are unable to list files in the repository
 *
 * @return list of snapshots in the repository
 * @throws IOException I/O errors
 */
protected List<SnapshotId> readSnapshotList() throws IOException {
    try (InputStream blob = snapshotsBlobContainer.readBlob(SNAPSHOTS_FILE)) {
        final byte[] data = ByteStreams.toByteArray(blob);
        ArrayList<SnapshotId> snapshots = new ArrayList<>();
        try (XContentParser parser = XContentHelper.createParser(new BytesArray(data))) {
            if (parser.nextToken() == XContentParser.Token.START_OBJECT) {
                if (parser.nextToken() == XContentParser.Token.FIELD_NAME) {
                    String currentFieldName = parser.currentName();
                    if ("snapshots".equals(currentFieldName)) {
                        if (parser.nextToken() == XContentParser.Token.START_ARRAY) {
                            while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                                snapshots.add(new SnapshotId(repositoryName, parser.text()));
                            }
                        }
                    }
                }
            }
        }
        return Collections.unmodifiableList(snapshots);
    }
}
 
Example 2
Source File: XContentTestUtilsTests.java    From crate with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testInsertIntoXContent() throws IOException {
    XContentBuilder builder = JsonXContent.contentBuilder();
    builder.startObject();
    builder.endObject();
    builder = XContentTestUtils.insertIntoXContent(XContentType.JSON.xContent(), BytesReference.bytes(builder),
            Collections.singletonList(""), () -> "inn.er1", () -> new HashMap<>());
    builder = XContentTestUtils.insertIntoXContent(XContentType.JSON.xContent(), BytesReference.bytes(builder),
            Collections.singletonList(""), () -> "field1", () -> "value1");
    builder = XContentTestUtils.insertIntoXContent(XContentType.JSON.xContent(), BytesReference.bytes(builder),
            Collections.singletonList("inn\\.er1"), () -> "inner2", () -> new HashMap<>());
    builder = XContentTestUtils.insertIntoXContent(XContentType.JSON.xContent(), BytesReference.bytes(builder),
            Collections.singletonList("inn\\.er1"), () -> "field2", () -> "value2");
    try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY,
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(builder), builder.contentType())) {
        Map<String, Object> map = parser.map();
        assertEquals(2, map.size());
        assertEquals("value1", map.get("field1"));
        assertThat(map.get("inn.er1"), instanceOf(Map.class));
        Map<String, Object> innerMap = (Map<String, Object>) map.get("inn.er1");
        assertEquals(2, innerMap.size());
        assertEquals("value2", innerMap.get("field2"));
        assertThat(innerMap.get("inner2"), instanceOf(Map.class));
        assertEquals(0, ((Map<String, Object>) innerMap.get("inner2")).size());
    }
}
 
Example 3
Source File: ChecksumBlobStoreFormat.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Reads blob with specified name without resolving the blobName using using {@link #blobName} method.
 *
 * @param blobContainer blob container
 * @param blobName blob name
 */
public T readBlob(BlobContainer blobContainer, String blobName) throws IOException {
    final BytesReference bytes = Streams.readFully(blobContainer.readBlob(blobName));
    final String resourceDesc = "ChecksumBlobStoreFormat.readBlob(blob=\"" + blobName + "\")";
    try (ByteArrayIndexInput indexInput =
             new ByteArrayIndexInput(resourceDesc, BytesReference.toBytes(bytes))) {
        CodecUtil.checksumEntireFile(indexInput);
        CodecUtil.checkHeader(indexInput, codec, VERSION, VERSION);
        long filePointer = indexInput.getFilePointer();
        long contentSize = indexInput.length() - CodecUtil.footerLength() - filePointer;
        try (XContentParser parser = XContentHelper.createParser(namedXContentRegistry, LoggingDeprecationHandler.INSTANCE,
                                                                 bytes.slice((int) filePointer, (int) contentSize), XContentType.SMILE)) {
            return reader.apply(parser);
        }
    } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
        // we trick this into a dedicated exception with the original stacktrace
        throw new CorruptStateException(ex);
    }
}
 
Example 4
Source File: SampleIndexTestCase.java    From elasticsearch-carrot2 with Apache License 2.0 6 votes vote down vote up
protected static Map<String, Object> checkHttpResponse(HttpResponse response) throws IOException {
   byte[] responseBytes = response.getEntity().getContent().readAllBytes();
   String responseString = new String(responseBytes, StandardCharsets.UTF_8);

   String responseDescription =
       "HTTP response status: " + response.getStatusLine().toString() + ", " +
           "HTTP body: " + responseString;

   Assertions.assertThat(response.getStatusLine().getStatusCode())
       .describedAs(responseDescription)
       .isEqualTo(HttpStatus.SC_OK);

   try (XContentParser parser = XContentHelper.createParser(
       NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
       new BytesArray(responseBytes),
       XContentType.fromMediaTypeOrFormat(response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()))) {
      Map<String, Object> map = parser.map();
      Assertions.assertThat(map)
          .describedAs(responseDescription)
          .doesNotContainKey("error");
      return map;
   }
}
 
Example 5
Source File: MappingMetaData.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public MappingMetaData(CompressedXContent mapping) throws IOException {
    Map<String, Object> mappingMap;
    try (XContentParser parser = XContentHelper.createParser(mapping.compressedReference())) {
        mappingMap = parser.mapOrdered();
    }
    if (mappingMap.containsKey(MAPPING_VERSION)) {
        this.mappingVersion = (int)mappingMap.get(MAPPING_VERSION);
        mappingMap.remove(MAPPING_VERSION);
    } else {
        this.mappingVersion = 1;
    }
    XContentBuilder mappingBuilder = XContentFactory.jsonBuilder().map(mappingMap);
    this.source = new CompressedXContent(mappingBuilder.bytes());
    if (mappingMap.size() != 1) {
        throw new IllegalStateException("Can't derive type from mapping, no root type: " + mapping.string());
    }
    this.type = mappingMap.keySet().iterator().next();
    initMappers((Map<String, Object>) mappingMap.get(this.type));
}
 
Example 6
Source File: RestSearchScrollAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static void buildFromContent(BytesReference content, SearchScrollRequest searchScrollRequest) {
    try (XContentParser parser = XContentHelper.createParser(content)) {
        if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
            throw new IllegalArgumentException("Malforrmed content, must start with an object");
        } else {
            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 ("scroll_id".equals(currentFieldName) && token == XContentParser.Token.VALUE_STRING) {
                    searchScrollRequest.scrollId(parser.text());
                } else if ("scroll".equals(currentFieldName) && token == XContentParser.Token.VALUE_STRING) {
                    searchScrollRequest.scroll(new Scroll(TimeValue.parseTimeValue(parser.text(), null, "scroll")));
                } else {
                    throw new IllegalArgumentException("Unknown parameter [" + currentFieldName + "] in request body or parameter is of the wrong type[" + token + "] ");
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Failed to parse request body", e);
    }
}
 
Example 7
Source File: RestClearScrollAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static void buildFromContent(BytesReference content, ClearScrollRequest clearScrollRequest) {
    try (XContentParser parser = XContentHelper.createParser(content)) {
        if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
            throw new IllegalArgumentException("Malformed content, must start with an object");
        } else {
            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 ("scroll_id".equals(currentFieldName) && token == XContentParser.Token.START_ARRAY) {
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException("scroll_id array element should only contain scroll_id");
                        }
                        clearScrollRequest.addScrollId(parser.text());
                    }
                } else {
                    throw new IllegalArgumentException("Unknown parameter [" + currentFieldName + "] in request body or parameter is of the wrong type[" + token + "] ");
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Failed to parse request body", e);
    }
}
 
Example 8
Source File: NestedInnerQueryParseSupport.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public Query getInnerFilter() throws IOException {
    if (filterParsed) {
        return innerFilter;
    } else {
        if (path == null) {
            throw new QueryParsingException(parseContext, "[nested] requires 'path' field");
        }
        if (!filterFound) {
            throw new QueryParsingException(parseContext, "[nested] requires either 'query' or 'filter' field");
        }

        setPathLevel();
        XContentParser old = parseContext.parser();
        try {
            XContentParser innerParser = XContentHelper.createParser(source);
            parseContext.parser(innerParser);
            innerFilter = parseContext.parseInnerFilter();
            filterParsed = true;
            return innerFilter;
        } finally {
            resetPathLevel();
            parseContext.parser(old);
        }
    }
}
 
Example 9
Source File: TranslogRecoveryPerformer.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private static Engine.DeleteByQuery prepareDeleteByQuery(IndexQueryParserService queryParserService, MapperService mapperService, IndexAliasesService indexAliasesService, IndexCache indexCache, BytesReference source, @Nullable String[] filteringAliases, Engine.Operation.Origin origin, String... types) {
    long startTime = System.nanoTime();
    if (types == null) {
        types = Strings.EMPTY_ARRAY;
    }
    Query query;
    try {
        query = queryParserService.parseQuery(source).query();
    } catch (QueryParsingException ex) {
        // for BWC we try to parse directly the query since pre 1.0.0.Beta2 we didn't require a top level query field
        if (queryParserService.getIndexCreatedVersion().onOrBefore(Version.V_1_0_0_Beta2)) {
            try {
                XContentParser parser = XContentHelper.createParser(source);
                ParsedQuery parse = queryParserService.parse(parser);
                query = parse.query();
            } catch (Throwable t) {
                ex.addSuppressed(t);
                throw ex;
            }
        } else {
            throw ex;
        }
    }
    Query searchFilter = mapperService.searchFilter(types);
    if (searchFilter != null) {
        query = Queries.filtered(query, searchFilter);
    }

    Query aliasFilter = indexAliasesService.aliasFilter(filteringAliases);
    BitSetProducer parentFilter = mapperService.hasNested() ? indexCache.bitsetFilterCache().getBitSetProducer(Queries.newNonNestedFilter()) : null;
    return new Engine.DeleteByQuery(query, source, filteringAliases, aliasFilter, parentFilter, origin, startTime, types);
}
 
Example 10
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 11
Source File: PercolatorQueriesRegistry.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
Query parsePercolatorDocument(String id, BytesReference source) {
    String type = null;
    BytesReference querySource = null;
    try (XContentParser sourceParser = XContentHelper.createParser(source)) {
        String currentFieldName = null;
        XContentParser.Token token = sourceParser.nextToken(); // move the START_OBJECT
        if (token != XContentParser.Token.START_OBJECT) {
            throw new ElasticsearchException("failed to parse query [" + id + "], not starting with OBJECT");
        }
        while ((token = sourceParser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = sourceParser.currentName();
            } else if (token == XContentParser.Token.START_OBJECT) {
                if ("query".equals(currentFieldName)) {
                    if (type != null) {
                        return parseQuery(type, sourceParser);
                    } else {
                        XContentBuilder builder = XContentFactory.contentBuilder(sourceParser.contentType());
                        builder.copyCurrentStructure(sourceParser);
                        querySource = builder.bytes();
                        builder.close();
                    }
                } else {
                    sourceParser.skipChildren();
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                sourceParser.skipChildren();
            } else if (token.isValue()) {
                if ("type".equals(currentFieldName)) {
                    type = sourceParser.text();
                }
            }
        }
        try (XContentParser queryParser = XContentHelper.createParser(querySource)) {
            return parseQuery(type, queryParser);
        }
    } catch (Exception e) {
        throw new PercolatorException(shardId().index(), "failed to parse query [" + id + "]", e);
    }
}
 
Example 12
Source File: ConfigurationLoader.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
private Settings toSettings(final BytesReference ref, final String type) {
    if (ref == null || ref.length() == 0) {
        return null;
    }
    
    XContentParser parser = null;

    try {
        parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, ref, XContentType.JSON);
        parser.nextToken();
        parser.nextToken();
     
        if(!type.equals((parser.currentName()))) {
            return null;
        }
        
        parser.nextToken();
        
        return Settings.builder().put(new JsonSettingsLoader(true).load(parser.binaryValue())).build();
    } catch (final IOException e) {
        throw ExceptionsHelper.convertToElastic(e);
    } finally {
        if(parser != null) {
            parser.close();
        }
    }
}
 
Example 13
Source File: SampleIndexTestCase.java    From elasticsearch-carrot2 with Apache License 2.0 5 votes vote down vote up
protected static void expectErrorResponseWithMessage(HttpResponse response,
                                                     int expectedStatus,
                                                     String messageSubstring) throws IOException {
   byte[] responseBytes = response.getEntity().getContent().readAllBytes();
   String responseString = new String(responseBytes, StandardCharsets.UTF_8);
   String responseDescription =
       "HTTP response status: " + response.getStatusLine().toString() + ", " +
           "HTTP body: " + responseString;

   Assertions.assertThat(response.getStatusLine().getStatusCode())
       .describedAs(responseDescription)
       .isEqualTo(expectedStatus);

   XContentType xContentType = XContentType.fromMediaTypeOrFormat(
       response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
   try (XContentParser parser = XContentHelper.createParser(
       NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
       new BytesArray(responseBytes), xContentType)) {
      Map<String, Object> responseJson = parser.mapOrdered();

      Assertions.assertThat(responseJson)
          .describedAs(responseString)
          .containsKey("error");

      Assertions.assertThat(responseJson.get("error").toString())
          .describedAs(responseString)
          .contains(messageSubstring);
   }
}
 
Example 14
Source File: NestedInnerQueryParseSupport.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public Query getInnerQuery() throws IOException {
    if (queryParsed) {
        return innerQuery;
    } else {
        if (path == null) {
            throw new QueryParsingException(parseContext, "[nested] requires 'path' field");
        }
        if (!queryFound) {
            throw new QueryParsingException(parseContext, "[nested] requires either 'query' or 'filter' field");
        }

        XContentParser old = parseContext.parser();
        try {
            XContentParser innerParser = XContentHelper.createParser(source);
            parseContext.parser(innerParser);
            setPathLevel();
            try {
                innerQuery = parseContext.parseInnerQuery();
            } finally {
                resetPathLevel();
            }
            queryParsed = true;
            return innerQuery;
        } finally {
            parseContext.parser(old);
        }
    }
}
 
Example 15
Source File: CreateIndexRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public CreateIndexRequest aliases(BytesReference source) {
    // EMPTY is safe here because we never call namedObject
    try (XContentParser parser = XContentHelper
            .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) {
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch (IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example 16
Source File: PutIndexTemplateRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public PutIndexTemplateRequest aliases(BytesReference source) {
    // EMPTY is safe here because we never call namedObject
    try (XContentParser parser = XContentHelper
            .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) {
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch (IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example 17
Source File: RestAnalyzeAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public static void buildFromContent(BytesReference content, AnalyzeRequest analyzeRequest, ParseFieldMatcher parseFieldMatcher) {
    try (XContentParser parser = XContentHelper.createParser(content)) {
        if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
            throw new IllegalArgumentException("Malforrmed content, must start with an object");
        } else {
            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 (parseFieldMatcher.match(currentFieldName, Fields.TEXT) && token == XContentParser.Token.VALUE_STRING) {
                    analyzeRequest.text(parser.text());
                } else if (parseFieldMatcher.match(currentFieldName, Fields.TEXT) && token == XContentParser.Token.START_ARRAY) {
                    List<String> texts = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException(currentFieldName + " array element should only contain text");
                        }
                        texts.add(parser.text());
                    }
                    analyzeRequest.text(texts.toArray(new String[texts.size()]));
                } else if (parseFieldMatcher.match(currentFieldName, Fields.ANALYZER) && token == XContentParser.Token.VALUE_STRING) {
                    analyzeRequest.analyzer(parser.text());
                } else if (parseFieldMatcher.match(currentFieldName, Fields.FIELD) && token == XContentParser.Token.VALUE_STRING) {
                    analyzeRequest.field(parser.text());
                } else if (parseFieldMatcher.match(currentFieldName, Fields.TOKENIZER) && token == XContentParser.Token.VALUE_STRING) {
                    analyzeRequest.tokenizer(parser.text());
                } else if (parseFieldMatcher.match(currentFieldName, Fields.TOKEN_FILTERS) && token == XContentParser.Token.START_ARRAY) {
                    List<String> filters = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException(currentFieldName + " array element should only contain token filter's name");
                        }
                        filters.add(parser.text());
                    }
                    analyzeRequest.tokenFilters(filters.toArray(new String[filters.size()]));
                } else if (parseFieldMatcher.match(currentFieldName, Fields.CHAR_FILTERS) && token == XContentParser.Token.START_ARRAY) {
                    List<String> charFilters = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException(currentFieldName + " array element should only contain char filter's name");
                        }
                        charFilters.add(parser.text());
                    }
                    analyzeRequest.charFilters(charFilters.toArray(new String[charFilters.size()]));
                } else if (parseFieldMatcher.match(currentFieldName, Fields.EXPLAIN)) {
                    if (parser.isBooleanValue()) {
                        analyzeRequest.explain(parser.booleanValue());
                    } else {
                        throw new IllegalArgumentException(currentFieldName + " must be either 'true' or 'false'");
                    }
                } else if (parseFieldMatcher.match(currentFieldName, Fields.ATTRIBUTES) && token == XContentParser.Token.START_ARRAY){
                    List<String> attributes = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException(currentFieldName + " array element should only contain attribute name");
                        }
                        attributes.add(parser.text());
                    }
                    analyzeRequest.attributes(attributes.toArray(new String[attributes.size()]));
                } else {
                    throw new IllegalArgumentException("Unknown parameter [" + currentFieldName + "] in request body or parameter is of the wrong type[" + token + "] ");
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Failed to parse request body", e);
    }
}
 
Example 18
Source File: RestExtendedAnalyzeAction.java    From elasticsearch-extended-analyze with Apache License 2.0 4 votes vote down vote up
public static void buildFromContent(BytesReference content, ExtendedAnalyzeRequest analyzeRequest) throws IllegalArgumentException {
    try (XContentParser parser = XContentHelper.createParser(content)) {
        if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
            throw new IllegalArgumentException("Malformed content, must start with an object");
        } else {
            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 ("text".equals(currentFieldName) && token == XContentParser.Token.VALUE_STRING) {
                    analyzeRequest.text(parser.text());
                } else if ("text".equals(currentFieldName) && token == XContentParser.Token.START_ARRAY) {
                    List<String> texts = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException(currentFieldName + " array element should only contain text");
                        }
                        texts.add(parser.text());
                    }
                    analyzeRequest.text(texts.toArray(Strings.EMPTY_ARRAY));
                } else if ("analyzer".equals(currentFieldName) && token == XContentParser.Token.VALUE_STRING) {
                    analyzeRequest.analyzer(parser.text());
                } else if ("field".equals(currentFieldName) && token == XContentParser.Token.VALUE_STRING) {
                    analyzeRequest.field(parser.text());
                } else if ("tokenizer".equals(currentFieldName) && token == XContentParser.Token.VALUE_STRING) {
                    analyzeRequest.tokenizer(parser.text());
                } else if (("token_filters".equals(currentFieldName) || "filters".equals(currentFieldName)) && token == XContentParser.Token.START_ARRAY) {
                    List<String> filters = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException(currentFieldName + " array element should only contain token filter's name");
                        }
                        filters.add(parser.text());
                    }
                    analyzeRequest.tokenFilters(filters.toArray(Strings.EMPTY_ARRAY));
                } else if ("char_filters".equals(currentFieldName) && token == XContentParser.Token.START_ARRAY) {
                    List<String> charFilters = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException(currentFieldName + " array element should only contain char filter's name");
                        }
                        charFilters.add(parser.text());
                    }
                    analyzeRequest.tokenFilters(charFilters.toArray(Strings.EMPTY_ARRAY));
                } else if ("attributes".equals(currentFieldName) && token == XContentParser.Token.START_ARRAY){
                    List<String> attributes = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if (token.isValue() == false) {
                            throw new IllegalArgumentException(currentFieldName + " array element should only contain attribute name");
                        }
                        attributes.add(parser.text());
                    }
                    analyzeRequest.attributes(attributes.toArray(Strings.EMPTY_ARRAY));
                } else if ("use_short_attr".equals(currentFieldName) && token == XContentParser.Token.VALUE_BOOLEAN) {
                    analyzeRequest.shortAttributeName(parser.booleanValue());
                } else {
                    throw new IllegalArgumentException("Unknown parameter [" + currentFieldName + "] in request body or parameter is of the wrong type[" + token + "] ");
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Failed to parse request body", e);
    }
}
 
Example 19
Source File: RestHandlerUtils.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
public static XContentParser createXContentParser(RestChannel channel, BytesReference bytesReference) throws IOException {
    return XContentHelper
        .createParser(channel.request().getXContentRegistry(), LoggingDeprecationHandler.INSTANCE, bytesReference, XContentType.JSON);
}
 
Example 20
Source File: XContentTestUtilsTests.java    From crate with Apache License 2.0 4 votes vote down vote up
public void testGetInsertPaths() throws IOException {
    XContentBuilder builder = JsonXContent.contentBuilder();
    builder.startObject();
    {
        builder.field("field1", "value");
        builder.startArray("list1");
        {
            builder.value(0);
            builder.value(1);
            builder.startObject();
            builder.endObject();
            builder.value(3);
            builder.startObject();
            builder.endObject();
        }
        builder.endArray();
        builder.startObject("inner1");
        {
            builder.field("inner1field1", "value");
            builder.startObject("inn.er2");
            {
                builder.field("inner2field1", "value");
            }
            builder.endObject();
        }
        builder.endObject();
    }
    builder.endObject();

    try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY,
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(builder), builder.contentType())) {
        parser.nextToken();
        List<String> insertPaths = XContentTestUtils.getInsertPaths(parser, new Stack<>());
        assertEquals(5, insertPaths.size());
        assertThat(insertPaths, hasItem(equalTo("")));
        assertThat(insertPaths, hasItem(equalTo("list1.2")));
        assertThat(insertPaths, hasItem(equalTo("list1.4")));
        assertThat(insertPaths, hasItem(equalTo("inner1")));
        assertThat(insertPaths, hasItem(equalTo("inner1.inn\\.er2")));
    }
}