private static XContentParser createParser(String mediaType, String content) throws IOException { return XContentType.fromMediaTypeOrFormat(mediaType) // .xContent() // .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, content); }
private Map<String, String> convertSettingResponse(String settingResponse, String indexName) { ObjectMapper mapper = new ObjectMapper(); try { Settings settings = Settings.fromXContent(XContentType.JSON.xContent().createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, settingResponse)); String prefix = indexName + ".settings."; // Backwards compatibility. TODO Change to return Settings object. Map<String, String> result = new HashMap<String, String>(); Set<String> keySet = settings.keySet(); for (String key : keySet) { result.put(key.substring(prefix.length()), settings.get(key)); } return result; } catch (IOException e) { throw new ElasticsearchException("Could not map alias response : " + settingResponse, e); } }
@Override protected ConfigUpdateNodeResponse nodeOperation(final NodeConfigUpdateRequest request) { final Map<String, Settings> setn = configurationRepository.reloadConfiguration(Arrays.asList(request.request.getConfigTypes())); String licenseText = null; if(setn.get("config") != null) { licenseText = setn.get("config").get("searchguard.dynamic.license"); } if(licenseText != null && !licenseText.isEmpty()) { try { final SearchGuardLicense license = new SearchGuardLicense(XContentHelper.convertToMap(XContentType.JSON.xContent(), LicenseHelper.validateLicense(licenseText), true), clusterService); if(!license.isValid()) { logger.warn("License "+license.getUid()+" is invalid due to "+license.getMsgs()); //throw an exception here if loading of invalid license should be denied } } catch (Exception e) { logger.error("Invalid license",e); return new ConfigUpdateNodeResponse(clusterService.localNode(), new String[0], "Invalid license: "+e); } } backendRegistry.get().invalidateCache(); return new ConfigUpdateNodeResponse(clusterService.localNode(), setn.keySet().toArray(new String[0]), null); } }
public static Request multiSearch(MultiSearchRequest multiSearchRequest) throws IOException { Request request = new Request(HttpMethod.POST.name(), "/_msearch"); Params params = new Params(request); params.putParam("typed_keys", "true"); if (multiSearchRequest.maxConcurrentSearchRequests() != MultiSearchRequest.MAX_CONCURRENT_SEARCH_REQUESTS_DEFAULT) { params.putParam("max_concurrent_searches", Integer.toString(multiSearchRequest.maxConcurrentSearchRequests())); } XContent xContent = REQUEST_BODY_CONTENT_TYPE.xContent(); byte[] source = MultiSearchRequest.writeMultiLineFormat(multiSearchRequest, xContent); request.setEntity(new ByteArrayEntity(source, createContentType(xContent.type()))); return request; }
try { licenseText = LicenseHelper.validateLicense(licenseText); SearchGuardLicense retVal = new SearchGuardLicense(XContentHelper.convertToMap(XContentType.JSON.xContent(), licenseText, true), clusterService); effectiveLicense = retVal; return retVal;
final byte separator = bulkContentType.xContent().streamSeparator(); final ContentType requestContentType = createContentType(bulkContentType); DocWriteRequest.OpType opType = action.opType(); try (XContentBuilder metadata = XContentBuilder.builder(bulkContentType.xContent())) { metadata.startObject(); try (XContentBuilder builder = XContentBuilder.builder(bulkContentType.xContent())) { builder.copyCurrentStructure(parser); source = BytesReference.bytes(builder).toBytesRef();
@Override public String toString() { try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) { builder.startObject(); toXContent(builder, new MapParams(Collections.singletonMap("flat_settings", "true"))); builder.endObject(); return Strings.toString(builder); } catch (IOException e) { throw new UncheckedIOException(e); } }
/** * Parses the mappings (formatted as JSON) into a map */ public static Map<String, Object> parseMapping(NamedXContentRegistry xContentRegistry, String mappingSource) throws Exception { try (XContentParser parser = XContentType.JSON.xContent() .createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, mappingSource)) { return parser.map(); } }
/** * The template source definition. */ public PutIndexTemplateRequest source(String templateSource, XContentType xContentType) { return source(XContentHelper.convertToMap(xContentType.xContent(), templateSource, true)); }
private static List<String> parseableStringToList(String parsableString) { // fromXContent doesn't use named xcontent or deprecation. try (XContentParser xContentParser = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, parsableString)) { XContentParser.Token token = xContentParser.nextToken(); if (token != XContentParser.Token.START_ARRAY) { throw new IllegalArgumentException("expected START_ARRAY but got " + token); } ArrayList<String> list = new ArrayList<>(); while ((token = xContentParser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token != XContentParser.Token.VALUE_STRING) { throw new IllegalArgumentException("expected VALUE_STRING but got " + token); } list.add(xContentParser.text()); } return list; } catch (IOException e) { throw new IllegalArgumentException("failed to parse array", e); } }
/** * A parser for the contents of this request if there is a body, otherwise throws an {@link ElasticsearchParseException}. Use * {@link #applyContentParser(CheckedConsumer)} if you want to gracefully handle when the request doesn't have any contents. Use * {@link #contentOrSourceParamParser()} for requests that support specifying the request body in the {@code source} param. */ public final XContentParser contentParser() throws IOException { BytesReference content = requiredContent(); // will throw exception if body or content type missing return xContentType.get().xContent().createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, content.streamInput()); }
private Tuple<String, Map<String, Object>> extractMapping(String type, String source) throws MapperParsingException { Map<String, Object> root; try (XContentParser parser = XContentType.JSON.xContent() .createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, source)) { root = parser.mapOrdered(); } catch (Exception e) { throw new MapperParsingException("failed to parse mapping definition", e); } return extractMapping(type, root); }
private static BytesReference parseSourceBytes(XContentParser parser) throws IOException { try (XContentBuilder builder = XContentBuilder.builder(parser.contentType().xContent())) { // the original document gets slightly modified: whitespaces or // pretty printing are not preserved, // it all depends on the current builder settings builder.copyCurrentStructure(parser); return BytesReference.bytes(builder); } }
/** * 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()); } }
/** * Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided * {@link XContentType}. Wraps the output into a new anonymous object according to the value returned * by the {@link ToXContent#isFragment()} method returns. */ public static BytesReference toXContent(ToXContent toXContent, XContentType xContentType, Params params, boolean humanReadable) throws IOException { try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { builder.humanReadable(humanReadable); if (toXContent.isFragment()) { builder.startObject(); } toXContent.toXContent(builder, params); if (toXContent.isFragment()) { builder.endObject(); } return BytesReference.bytes(builder); } }
/** * A parser for the contents of this request if it has contents, otherwise a parser for the {@code source} parameter if there is one, * otherwise throws an {@link ElasticsearchParseException}. Use {@link #withContentOrSourceParamParserOrNull(CheckedConsumer)} instead * if you need to handle the absence request content gracefully. */ public final XContentParser contentOrSourceParamParser() throws IOException { Tuple<XContentType, BytesReference> tuple = contentOrSourceParam(); return tuple.v1().xContent().createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, tuple.v2().streamInput()); }
private static Script extractConditional(Map<String, Object> config) throws IOException { Object scriptSource = config.remove("if"); if (scriptSource != null) { try (XContentBuilder builder = XContentBuilder.builder(JsonXContent.jsonXContent) .map(normalizeScript(scriptSource)); InputStream stream = BytesReference.bytes(builder).streamInput(); XContentParser parser = XContentType.JSON.xContent().createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, stream)) { return Script.parse(parser); } } return null; }
private static String arrayToParsableString(List<String> array) { try { XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); builder.startArray(); for (String element : array) { builder.value(element); } builder.endArray(); return Strings.toString(builder); } catch (IOException ex) { throw new ElasticsearchException(ex); } }
/** * Call a consumer with the parser for the contents of this request if it has contents, otherwise with a parser for the {@code source} * parameter if there is one, otherwise with {@code null}. Use {@link #contentOrSourceParamParser()} if you should throw an exception * back to the user when there isn't request content. */ public final void withContentOrSourceParamParserOrNull(CheckedConsumer<XContentParser, IOException> withParser) throws IOException { if (hasContentOrSourceParam()) { Tuple<XContentType, BytesReference> tuple = contentOrSourceParam(); BytesReference content = tuple.v2(); XContentType xContentType = tuple.v1(); try (InputStream stream = content.streamInput(); XContentParser parser = xContentType.xContent() .createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, stream)) { withParser.accept(parser); } } else { withParser.accept(null); } }
/** * Parses a multi-line {@link RestRequest} body, instantiating a {@link SearchRequest} for each line and applying the given consumer. */ public static void parseMultiLineRequest(RestRequest request, IndicesOptions indicesOptions, boolean allowExplicitIndex, CheckedBiConsumer<SearchRequest, XContentParser, IOException> consumer) throws IOException { String[] indices = Strings.splitStringByCommaToArray(request.param("index")); String[] types = Strings.splitStringByCommaToArray(request.param("type")); String searchType = request.param("search_type"); String routing = request.param("routing"); final Tuple<XContentType, BytesReference> sourceTuple = request.contentOrSourceParam(); final XContent xContent = sourceTuple.v1().xContent(); final BytesReference data = sourceTuple.v2(); MultiSearchRequest.readMultiLineFormat(data, xContent, consumer, indices, indicesOptions, types, routing, searchType, request.getXContentRegistry(), allowExplicitIndex); }