public static XContentBuilder restContentBuilder(RestRequest request, @Nullable BytesReference autoDetectSource) throws IOException { XContentType contentType = XContentType.fromRestContentType(request.param("format", request.header("Content-Type"))); if (contentType == null) { // try and guess it from the auto detect source if (autoDetectSource != null) { contentType = XContentFactory.xContentType(autoDetectSource); } } if (contentType == null) { // default to JSON contentType = XContentType.JSON; } XContentBuilder builder = new XContentBuilder(XContentFactory.xContent(contentType), new BytesStreamOutput()); if (request.paramAsBoolean("pretty", false)) { builder.prettyPrint().lfAtEnd(); } builder.humanReadable(request.paramAsBoolean("human", builder.humanReadable())); String casing = request.param("case"); if (casing != null && "camelCase".equals(casing)) { builder.fieldCaseConversion(XContentBuilder.FieldCaseConversion.CAMELCASE); } else { // we expect all REST interfaces to write results in underscore casing, so // no need for double casing builder.fieldCaseConversion(XContentBuilder.FieldCaseConversion.NONE); } return builder; }
private static BytesReference readXContent(final Reader reader, final XContentType xContentType) throws IOException { BytesReference retVal; XContentParser parser = null; try { parser = XContentFactory.xContent(xContentType).createParser(NamedXContentRegistry.EMPTY, SearchGuardDeprecationHandler.INSTANCE, reader); parser.nextToken(); final XContentBuilder builder = XContentFactory.jsonBuilder(); builder.copyCurrentStructure(parser); retVal = BytesReference.bytes(builder); } finally { if (parser != null) { parser.close(); } } //validate Settings.builder().loadFromStream("dummy.json", new ByteArrayInputStream(BytesReference.toBytes(retVal)), true).build(); return retVal; }
/** * Creates a parser based on the bytes provided * @deprecated use {@link #createParser(NamedXContentRegistry, DeprecationHandler, BytesReference, XContentType)} * to avoid content type auto-detection */ @Deprecated public static XContentParser createParser(NamedXContentRegistry xContentRegistry, DeprecationHandler deprecationHandler, BytesReference bytes) throws IOException { Compressor compressor = CompressorFactory.compressor(bytes); if (compressor != null) { InputStream compressedInput = compressor.streamInput(bytes.streamInput()); if (compressedInput.markSupported() == false) { compressedInput = new BufferedInputStream(compressedInput); } final XContentType contentType = XContentFactory.xContentType(compressedInput); return XContentFactory.xContent(contentType).createParser(xContentRegistry, deprecationHandler, compressedInput); } else { return XContentFactory.xContent(xContentType(bytes)).createParser(xContentRegistry, deprecationHandler, bytes.streamInput()); } }
public static BytesReference readXContent(final Reader reader, final XContentType xContentType) throws IOException { BytesReference retVal; XContentParser parser = null; try { parser = XContentFactory.xContent(xContentType).createParser(NamedXContentRegistry.EMPTY, SearchGuardDeprecationHandler.INSTANCE, reader); parser.nextToken(); final XContentBuilder builder = XContentFactory.jsonBuilder(); builder.copyCurrentStructure(parser); retVal = BytesReference.bytes(builder); } finally { if (parser != null) { parser.close(); } } //validate Settings.builder().loadFromStream("dummy.json", new ByteArrayInputStream(BytesReference.toBytes(retVal)), true).build(); return retVal; }
/** * Converts the given bytes into a map that is optionally ordered. The provided {@link XContentType} must be non-null. */ public static Tuple<XContentType, Map<String, Object>> convertToMap(BytesReference bytes, boolean ordered, XContentType xContentType) throws ElasticsearchParseException { try { final XContentType contentType; InputStream input; Compressor compressor = CompressorFactory.compressor(bytes); if (compressor != null) { InputStream compressedStreamInput = compressor.streamInput(bytes.streamInput()); if (compressedStreamInput.markSupported() == false) { compressedStreamInput = new BufferedInputStream(compressedStreamInput); } input = compressedStreamInput; } else { input = bytes.streamInput(); } contentType = xContentType != null ? xContentType : XContentFactory.xContentType(input); try (InputStream stream = input) { return new Tuple<>(Objects.requireNonNull(contentType), convertToMap(XContentFactory.xContent(contentType), stream, ordered)); } } catch (IOException e) { throw new ElasticsearchParseException("Failed to parse content to map", e); } }
public static BytesReference readYamlContentFromString(final String yaml) { XContentParser parser = null; try { parser = XContentFactory.xContent(XContentType.YAML).createParser(NamedXContentRegistry.EMPTY, SearchGuardDeprecationHandler.INSTANCE, new StringReader(yaml)); parser.nextToken(); final XContentBuilder builder = XContentFactory.jsonBuilder(); builder.copyCurrentStructure(parser); return BytesReference.bytes(builder); } catch (Exception e) { throw new RuntimeException(e); } finally { if (parser != null) { try { parser.close(); } catch (IOException e) { //ignore } } } } }
public static BytesReference readYamlContent(final String file) { XContentParser parser = null; try { parser = XContentFactory.xContent(XContentType.YAML).createParser(NamedXContentRegistry.EMPTY, SearchGuardDeprecationHandler.INSTANCE, new StringReader(loadFile(file))); parser.nextToken(); final XContentBuilder builder = XContentFactory.jsonBuilder(); builder.copyCurrentStructure(parser); return BytesReference.bytes(builder); } catch (Exception e) { throw new RuntimeException(e); } finally { if (parser != null) { try { parser.close(); } catch (IOException e) { //ignore } } } }
ctx = XContentFactory.xContent(XContentType.JSON).createParser("{}").mapAndClose(); } catch (Exception e) {
/** * Loads settings from the actual string content that represents them using {@link #fromXContent(XContentParser)} */ public Builder loadFromSource(String source, XContentType xContentType) { try (XContentParser parser = XContentFactory.xContent(xContentType) .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) { this.put(fromXContent(parser, true, true)); } catch (Exception e) { throw new SettingsException("Failed to load settings from [" + source + "]", e); } return this; }
/** * Validates an alias filter by parsing it using the * provided {@link org.elasticsearch.index.query.QueryShardContext} * @throws IllegalArgumentException if the filter is not valid */ public void validateAliasFilter(String alias, byte[] filter, QueryShardContext queryShardContext, NamedXContentRegistry xContentRegistry) { assert queryShardContext != null; try (XContentParser parser = XContentFactory.xContent(filter) .createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, filter)) { validateAliasFilter(parser, queryShardContext); } catch (Exception e) { throw new IllegalArgumentException("failed to parse filter for alias [" + alias + "]", e); } }
/** * Validates an alias filter by parsing it using the * provided {@link org.elasticsearch.index.query.QueryShardContext} * @throws IllegalArgumentException if the filter is not valid */ public void validateAliasFilter(String alias, String filter, QueryShardContext queryShardContext, NamedXContentRegistry xContentRegistry) { assert queryShardContext != null; try (XContentParser parser = XContentFactory.xContent(filter) .createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, filter)) { validateAliasFilter(parser, queryShardContext); } catch (Exception e) { throw new IllegalArgumentException("failed to parse filter for alias [" + alias + "]", e); } }
public Builder filter(String filter) { if (!Strings.hasLength(filter)) { this.filter = null; return this; } return filter(XContentHelper.convertToMap(XContentFactory.xContent(filter), filter, true)); }
public Builder putMapping(String type, String source) throws IOException { putMapping(new MappingMetaData(type, XContentHelper.convertToMap(XContentFactory.xContent(source), source, true))); return this; }
@Override protected ScoreFunction doToFunction(QueryShardContext context) throws IOException { AbstractDistanceScoreFunction scoreFunction; // EMPTY is safe because parseVariable doesn't use namedObject try (InputStream stream = functionBytes.streamInput(); XContentParser parser = XContentFactory.xContent(XContentHelper.xContentType(functionBytes)) .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, stream)) { scoreFunction = parseVariable(fieldName, parser, context, multiValueMode); } return scoreFunction; }
/** * Creates a parser for the bytes using the supplied content-type */ public static XContentParser createParser(NamedXContentRegistry xContentRegistry, DeprecationHandler deprecationHandler, BytesReference bytes, XContentType xContentType) throws IOException { Objects.requireNonNull(xContentType); Compressor compressor = CompressorFactory.compressor(bytes); if (compressor != null) { InputStream compressedInput = compressor.streamInput(bytes.streamInput()); if (compressedInput.markSupported() == false) { compressedInput = new BufferedInputStream(compressedInput); } return XContentFactory.xContent(xContentType).createParser(xContentRegistry, deprecationHandler, compressedInput); } else { return xContentType.xContent().createParser(xContentRegistry, deprecationHandler, bytes.streamInput()); } }
public static String convertToJson(BytesReference bytes, boolean reformatJson, boolean prettyPrint, XContentType xContentType) throws IOException { Objects.requireNonNull(xContentType); if (xContentType == XContentType.JSON && !reformatJson) { return bytes.utf8ToString(); } // It is safe to use EMPTY here because this never uses namedObject try (InputStream stream = bytes.streamInput(); XContentParser parser = XContentFactory.xContent(xContentType).createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, stream)) { parser.nextToken(); XContentBuilder builder = XContentFactory.jsonBuilder(); if (prettyPrint) { builder.prettyPrint(); } builder.copyCurrentStructure(parser); return Strings.toString(builder); } }
public AliasFilter buildAliasFilter(ClusterState state, String index, String... expressions) { /* Being static, parseAliasFilter doesn't have access to whatever guts it needs to parse a query. Instead of passing in a bunch * of dependencies we pass in a function that can perform the parsing. */ CheckedFunction<byte[], QueryBuilder, IOException> filterParser = bytes -> { try (XContentParser parser = XContentFactory.xContent(bytes) .createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, bytes)) { return parseInnerQueryBuilder(parser); } }; String[] aliases = indexNameExpressionResolver.filteringAliases(state, index, expressions); IndexMetaData indexMetaData = state.metaData().index(index); return new AliasFilter(ShardSearchRequest.parseAliasFilter(filterParser, indexMetaData, aliases), aliases); }
/** * Allows to partially validate an alias, without knowing which index it'll get applied to. * Useful with index templates containing aliases. Checks also that it is possible to parse * the alias filter via {@link org.elasticsearch.common.xcontent.XContentParser}, * without validating it as a filter though. * @throws IllegalArgumentException if the alias is not valid */ public void validateAliasStandalone(Alias alias) { validateAliasStandalone(alias.name(), alias.indexRouting()); if (Strings.hasLength(alias.filter())) { try { XContentHelper.convertToMap(XContentFactory.xContent(alias.filter()), alias.filter(), false); } catch (Exception e) { throw new IllegalArgumentException("failed to parse filter for alias [" + alias.name() + "]", e); } } }
@Override protected QueryBuilder doRewrite(QueryRewriteContext context) throws IOException { try (XContentParser qSourceParser = XContentFactory.xContent(source) .createParser(context.getXContentRegistry(), LoggingDeprecationHandler.INSTANCE, source)) { final QueryBuilder queryBuilder = parseInnerQueryBuilder(qSourceParser).rewrite(context); if (boost() != DEFAULT_BOOST || queryName() != null) { final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); boolQueryBuilder.must(queryBuilder); return boolQueryBuilder; } return queryBuilder; } }