@Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.startArray(Fields.RESPONSES); for (Item item : items) { if (item.isFailure()) { builder.startObject(); ElasticsearchException.generateFailureXContent(builder, params, item.getFailure(), true); builder.endObject(); } else { item.getResponse().toXContent(builder, params); } } builder.endArray(); builder.endObject(); return builder; }
/** * Renders the provided instance in XContent * * @param instance * the instance to render * @param contentType * the content type to render to */ protected XContentBuilder toXContent(T instance, XContentType contentType) throws IOException { XContentBuilder builder = XContentFactory.contentBuilder(contentType); if (randomBoolean()) { builder.prettyPrint(); } if (instance.isFragment()) { builder.startObject(); } instance.toXContent(builder, ToXContent.EMPTY_PARAMS); if (instance.isFragment()) { builder.endObject(); } return builder; }
public void testCheckpointsAdvance() throws Exception { try (ReplicationGroup shards = createGroup(randomInt(3))) { shards.startPrimary(); int numDocs = 0; int startedShards; do { numDocs += shards.indexDocs(randomInt(20)); startedShards = shards.startReplicas(randomIntBetween(1, 2)); } while (startedShards > 0); if (numDocs == 0 || randomBoolean()) { // in the case we have no indexing, we simulate the background global checkpoint sync shards.getPrimary().updateGlobalCheckpointOnPrimary(); } for (IndexShard shard : shards) { final SeqNoStats shardStats = shard.seqNoStats(); final ShardRouting shardRouting = shard.routingEntry(); logger.debug("seq_no stats for {}: {}", shardRouting, XContentHelper.toString(shardStats, new ToXContent.MapParams(Collections.singletonMap("pretty", "false")))); assertThat(shardRouting + " local checkpoint mismatch", shardStats.getLocalCheckpoint(), equalTo(numDocs - 1L)); assertThat(shardRouting + " global checkpoint mismatch", shardStats.getGlobalCheckpoint(), equalTo(numDocs - 1L)); assertThat(shardRouting + " max seq no mismatch", shardStats.getMaxSeqNo(), equalTo(numDocs - 1L)); } } }
@Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder = builder.startObject() .field(NAME.getPreferredName(), getName()) .field(REASON.getPreferredName(), getReason()) .timeValueField(TIME_NANOS.getPreferredName(), TIME.getPreferredName(), getTime(), TimeUnit.NANOSECONDS); if (!children.isEmpty()) { builder = builder.startArray(CHILDREN.getPreferredName()); for (CollectorResult child : children) { builder = child.toXContent(builder, params); } builder = builder.endArray(); } builder = builder.endObject(); return builder; }
/** * Sets query contexts for completion * @param queryContexts named query contexts * see {@link org.elasticsearch.search.suggest.completion.context.CategoryQueryContext} * and {@link org.elasticsearch.search.suggest.completion.context.GeoQueryContext} */ public CompletionSuggestionBuilder contexts(Map<String, List<? extends ToXContent>> queryContexts) { Objects.requireNonNull(queryContexts, "contexts must not be null"); try { XContentBuilder contentBuilder = XContentFactory.jsonBuilder(); contentBuilder.startObject(); for (Map.Entry<String, List<? extends ToXContent>> contextEntry : queryContexts.entrySet()) { contentBuilder.startArray(contextEntry.getKey()); for (ToXContent queryContext : contextEntry.getValue()) { queryContext.toXContent(contentBuilder, EMPTY_PARAMS); } contentBuilder.endArray(); } contentBuilder.endObject(); return contexts(contentBuilder); } catch (IOException e) { throw new IllegalArgumentException(e); } }
/** * Test that creates new shape from a random test shape and checks both for equality */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { SB testShape = createTestShapeBuilder(); XContentBuilder contentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { contentBuilder.prettyPrint(); } XContentBuilder builder = testShape.toXContent(contentBuilder, ToXContent.EMPTY_PARAMS); XContentBuilder shuffled = shuffleXContent(builder); XContentParser shapeParser = createParser(shuffled); shapeParser.nextToken(); ShapeBuilder parsedShape = ShapeBuilder.parse(shapeParser); assertNotSame(testShape, parsedShape); assertEquals(testShape, parsedShape); assertEquals(testShape.hashCode(), parsedShape.hashCode()); } }
private static XContentBuilder build(RestChannel channel, RestStatus status, Exception e) throws IOException { ToXContent.Params params = channel.request(); if (params.paramAsBoolean("error_trace", !REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT)) { params = new ToXContent.DelegatingMapParams(singletonMap(REST_EXCEPTION_SKIP_STACK_TRACE, "false"), params); } else if (e != null) { Supplier<?> messageSupplier = () -> new ParameterizedMessage("path: {}, params: {}", channel.request().rawPath(), channel.request().params()); if (status.getStatus() < 500) { SUPPRESSED_ERROR_LOGGER.debug(messageSupplier, e); } else { SUPPRESSED_ERROR_LOGGER.warn(messageSupplier, e); } } XContentBuilder builder = channel.newErrorBuilder().startObject(); ElasticsearchException.generateFailureXContent(builder, params, e, channel.detailedErrorsEnabled()); builder.field(STATUS, status.getStatus()); builder.endObject(); return builder; }
private XContentBuilder renderResponse(ClusterState state, boolean renderDefaults, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.startObject("persistent"); state.metaData().persistentSettings().toXContent(builder, params); builder.endObject(); builder.startObject("transient"); state.metaData().transientSettings().toXContent(builder, params); builder.endObject(); if (renderDefaults) { builder.startObject("defaults"); settingsFilter.filter(clusterSettings.diff(state.metaData().settings(), this.settings)).toXContent(builder, params); builder.endObject(); } builder.endObject(); return builder; }
public static void toXContent(AliasMetaData aliasMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(aliasMetaData.alias()); boolean binary = params.paramAsBoolean("binary", false); if (aliasMetaData.filter() != null) { if (binary) { builder.field("filter", aliasMetaData.filter.compressed()); } else { builder.field("filter", XContentHelper.convertToMap(new BytesArray(aliasMetaData.filter().uncompressed()), true).v2()); } } if (aliasMetaData.indexRouting() != null) { builder.field("index_routing", aliasMetaData.indexRouting()); } if (aliasMetaData.searchRouting() != null) { builder.field("search_routing", aliasMetaData.searchRouting()); } builder.endObject(); }
@Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder = builder.startObject() .field(NAME.getPreferredName(), getName()) .field(REASON.getPreferredName(), getReason()) .field(TIME.getPreferredName(), String.format(Locale.US, "%.10gms", (double) (getTime() / 1000000.0))); if (!children.isEmpty()) { builder = builder.startArray(CHILDREN.getPreferredName()); for (CollectorResult child : children) { builder = child.toXContent(builder, params); } builder = builder.endArray(); } builder = builder.endObject(); return builder; }
/** * Serializes file info into JSON * * @param file file info * @param builder XContent builder * @param params parameters */ public static void toXContent(FileInfo file, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field(Fields.NAME, file.name); builder.field(Fields.PHYSICAL_NAME, file.metadata.name()); builder.field(Fields.LENGTH, file.metadata.length()); if (file.metadata.checksum() != null) { builder.field(Fields.CHECKSUM, file.metadata.checksum()); } if (file.partSize != null) { builder.field(Fields.PART_SIZE, file.partSize.bytes()); } if (file.metadata.writtenBy() != null) { builder.field(Fields.WRITTEN_BY, file.metadata.writtenBy()); } if (file.metadata.hash() != null && file.metadata().hash().length > 0) { builder.field(Fields.META_HASH, file.metadata.hash()); } builder.endObject(); }
/** * Associates a filter to the alias */ public Alias filter(QueryBuilder filterBuilder) { if (filterBuilder == null) { this.filter = null; return this; } try { XContentBuilder builder = XContentFactory.jsonBuilder(); filterBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.close(); this.filter = builder.string(); return this; } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to build json for alias request", e); } }
@Override public String explain() { try { XContentBuilder firstBuilder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint(); this.firstSearchRequest.request().source().toXContent(firstBuilder, ToXContent.EMPTY_PARAMS); XContentBuilder secondBuilder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint(); this.secondSearchRequest.request().source().toXContent(secondBuilder, ToXContent.EMPTY_PARAMS); String explained = String.format("performing %s on :\n left query:\n%s\n right query:\n%s", this.relation.name,firstBuilder.string(), secondBuilder.string()); return explained; } catch (IOException e) { e.printStackTrace(); } return null; }
private void compareJsonOutput(ToXContent param1, ToXContent param2) throws IOException { if (param1 == null) { assertNull(param2); return; } ToXContent.Params params = ToXContent.EMPTY_PARAMS; XContentBuilder param1Builder = jsonBuilder(); param1Builder.startObject(); param1.toXContent(param1Builder, params); param1Builder.endObject(); XContentBuilder param2Builder = jsonBuilder(); param2Builder.startObject(); param2.toXContent(param2Builder, params); param2Builder.endObject(); assertThat(param1Builder.string(), equalTo(param2Builder.string())); }
public void testXContentRoundTrip() throws IOException { /* * Note that this round trip isn't 100% perfect - status will always be read as RawTaskStatus. Since this test uses RawTaskStatus * as the status we randomly generate then we can assert the round trip with .equals. */ TaskResult result = randomTaskResult(); TaskResult read; try (XContentBuilder builder = XContentBuilder.builder(randomFrom(XContentType.values()).xContent())) { result.toXContent(builder, ToXContent.EMPTY_PARAMS); try (XContentBuilder shuffled = shuffleXContent(builder); XContentParser parser = createParser(shuffled)) { read = TaskResult.PARSER.apply(parser, null); } } catch (IOException e) { throw new IOException("Error processing [" + result + "]", e); } assertEquals(result, read); }
/** * creates random suggestion builder, renders it to xContent and back to new * instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { SB suggestionBuilder = randomTestBuilder(); XContentBuilder xContentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { xContentBuilder.prettyPrint(); } xContentBuilder.startObject(); suggestionBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); xContentBuilder.endObject(); XContentBuilder shuffled = shuffleXContent(xContentBuilder, shuffleProtectedFields()); XContentParser parser = createParser(shuffled); // we need to skip the start object and the name, those will be parsed by outer SuggestBuilder parser.nextToken(); SuggestionBuilder<?> secondSuggestionBuilder = SuggestionBuilder.fromXContent(parser); assertNotSame(suggestionBuilder, secondSuggestionBuilder); assertEquals(suggestionBuilder, secondSuggestionBuilder); assertEquals(suggestionBuilder.hashCode(), secondSuggestionBuilder.hashCode()); } }
/** * creates random suggestion builder, renders it to xContent and back to new instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_RUNS; runs++) { SuggestBuilder suggestBuilder = randomSuggestBuilder(); XContentBuilder xContentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { xContentBuilder.prettyPrint(); } suggestBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); XContentParser parser = createParser(xContentBuilder); SuggestBuilder secondSuggestBuilder = SuggestBuilder.fromXContent(parser); assertNotSame(suggestBuilder, secondSuggestBuilder); assertEquals(suggestBuilder, secondSuggestBuilder); assertEquals(suggestBuilder.hashCode(), secondSuggestBuilder.hashCode()); } }
/** * Test that creates new smoothing model from a random test smoothing model and checks both for equality */ public void testFromXContent() throws IOException { SmoothingModel testModel = createTestModel(); XContentBuilder contentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { contentBuilder.prettyPrint(); } contentBuilder.startObject(); testModel.innerToXContent(contentBuilder, ToXContent.EMPTY_PARAMS); contentBuilder.endObject(); XContentParser parser = createParser(shuffleXContent(contentBuilder)); parser.nextToken(); // go to start token, real parsing would do that in the outer element parser SmoothingModel parsedModel = fromXContent(parser); assertNotSame(testModel, parsedModel); assertEquals(testModel, parsedModel); assertEquals(testModel.hashCode(), parsedModel.hashCode()); }
/** * creates random candidate generator, renders it to xContent and back to new instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_RUNS; runs++) { DirectCandidateGeneratorBuilder generator = randomCandidateGenerator(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } generator.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentParser parser = createParser(shuffleXContent(builder)); parser.nextToken(); DirectCandidateGeneratorBuilder secondGenerator = DirectCandidateGeneratorBuilder.PARSER.apply(parser, null); assertNotSame(generator, secondGenerator); assertEquals(generator, secondGenerator); assertEquals(generator.hashCode(), secondGenerator.hashCode()); } }
@Override protected XContentBuilder innerToXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject("fuzzy"); if (fuzziness != Fuzziness.ONE) { fuzziness.toXContent(builder, params); } if (fuzzyTranspositions != XFuzzySuggester.DEFAULT_TRANSPOSITIONS) { builder.field("transpositions", fuzzyTranspositions); } if (fuzzyMinLength != XFuzzySuggester.DEFAULT_MIN_FUZZY_LENGTH) { builder.field("min_length", fuzzyMinLength); } if (fuzzyPrefixLength != XFuzzySuggester.DEFAULT_NON_FUZZY_PREFIX) { builder.field("prefix_length", fuzzyPrefixLength); } if (unicodeAware != XFuzzySuggester.DEFAULT_UNICODE_AWARE) { builder.field("unicode_aware", unicodeAware); } builder.endObject(); return builder; }
public void testToXContent() throws IOException { HighlightField field = new HighlightField("foo", new Text[] { new Text("bar"), new Text("baz") }); XContentBuilder builder = JsonXContent.contentBuilder(); builder.prettyPrint(); builder.startObject(); field.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); assertEquals( "{\n" + " \"foo\" : [\n" + " \"bar\",\n" + " \"baz\"\n" + " ]\n" + "}", builder.string()); field = new HighlightField("foo", null); builder = JsonXContent.contentBuilder(); builder.prettyPrint(); builder.startObject(); field.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); assertEquals( "{\n" + " \"foo\" : null\n" + "}", builder.string()); }
private ClusterAllocationExplanation runExplain(boolean primary, String nodeId, boolean includeYesDecisions, boolean includeDiskInfo) throws Exception { ClusterAllocationExplanation explanation = client().admin().cluster().prepareAllocationExplain() .setIndex("idx").setShard(0).setPrimary(primary) .setIncludeYesDecisions(includeYesDecisions) .setIncludeDiskInfo(includeDiskInfo) .setCurrentNode(nodeId) .get().getExplanation(); if (logger.isDebugEnabled()) { XContentBuilder builder = JsonXContent.contentBuilder(); builder.prettyPrint(); builder.humanReadable(true); logger.debug("--> explain json output: \n{}", explanation.toXContent(builder, ToXContent.EMPTY_PARAMS).string()); } return explanation; }
/** * creates random rescorer, renders it to xContent and back to new instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { RescoreBuilder<?> rescoreBuilder = randomRescoreBuilder(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } rescoreBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentBuilder shuffled = shuffleXContent(builder); XContentParser parser = createParser(shuffled); QueryParseContext context = new QueryParseContext(parser); parser.nextToken(); RescoreBuilder<?> secondRescoreBuilder = RescoreBuilder.parseFromXContent(context); assertNotSame(rescoreBuilder, secondRescoreBuilder); assertEquals(rescoreBuilder, secondRescoreBuilder); assertEquals(rescoreBuilder.hashCode(), secondRescoreBuilder.hashCode()); } }
private static BytesReference queryForRemote(Map<String, Object> source) throws IOException { XContentBuilder builder = JsonXContent.contentBuilder().prettyPrint(); Object query = source.remove("query"); if (query == null) { return matchAllQuery().toXContent(builder, ToXContent.EMPTY_PARAMS).bytes(); } if (!(query instanceof Map)) { throw new IllegalArgumentException("Expected [query] to be an object but was [" + query + "]"); } @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) query; return builder.map(map).bytes(); }
@Override public RestResponse buildResponse(BulkByScrollResponse response, XContentBuilder builder) throws Exception { builder.startObject(); response.toXContent(builder, new ToXContent.DelegatingMapParams(params, channel.request())); builder.endObject(); return new BytesRestResponse(getStatus(response), builder); }
public void testXContentRepresentationOfUnlimitedRequestsPerSecond() throws IOException { XContentBuilder builder = JsonXContent.contentBuilder(); BulkByScrollTask.Status status = new BulkByScrollTask.Status(null, 0, 0, 0, 0, 0, 0, 0, 0, 0, timeValueMillis(0), Float.POSITIVE_INFINITY, null, timeValueMillis(0)); status.toXContent(builder, ToXContent.EMPTY_PARAMS); assertThat(builder.string(), containsString("\"requests_per_second\":-1")); }
protected static XContentBuilder toXContent(QueryBuilder query, XContentType contentType) throws IOException { XContentBuilder builder = XContentFactory.contentBuilder(contentType); if (randomBoolean()) { builder.prettyPrint(); } query.toXContent(builder, ToXContent.EMPTY_PARAMS); return builder; }
public void testAtomicWrite() throws Exception { final BlobStore blobStore = createTestBlobStore(); final BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath()); String testString = randomAsciiOfLength(randomInt(10000)); final CountDownLatch block = new CountDownLatch(1); final CountDownLatch unblock = new CountDownLatch(1); final BlobObj blobObj = new BlobObj(testString) { @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { super.toXContent(builder, params); // Block before finishing writing try { block.countDown(); unblock.await(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } return builder; } }; final ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent, xContentRegistry(), randomBoolean(), randomBoolean() ? XContentType.SMILE : XContentType.JSON); ExecutorService threadPool = Executors.newFixedThreadPool(1); try { Future<Void> future = threadPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { checksumFormat.writeAtomic(blobObj, blobContainer, "test-blob"); return null; } }); block.await(5, TimeUnit.SECONDS); assertFalse(blobContainer.blobExists("test-blob")); unblock.countDown(); future.get(); assertTrue(blobContainer.blobExists("test-blob")); } finally { threadPool.shutdown(); } }
/** * Assert that two objects are equals, calling {@link ToXContent#toXContent(XContentBuilder, ToXContent.Params)} to print out their * differences if they aren't equal. */ public static <T extends ToXContent> void assertEqualsWithErrorMessageFromXContent(T expected, T actual) { if (Objects.equals(expected, actual)) { return; } if (expected == null) { throw new AssertionError("Expected null be actual was [" + actual.toString() + "]"); } if (actual == null) { throw new AssertionError("Didn't expect null but actual was [null]"); } try (XContentBuilder actualJson = JsonXContent.contentBuilder(); XContentBuilder expectedJson = JsonXContent.contentBuilder()) { actualJson.startObject(); actual.toXContent(actualJson, ToXContent.EMPTY_PARAMS); actualJson.endObject(); expectedJson.startObject(); expected.toXContent(expectedJson, ToXContent.EMPTY_PARAMS); expectedJson.endObject(); NotEqualMessageBuilder message = new NotEqualMessageBuilder(); message.compareMaps( XContentHelper.convertToMap(actualJson.bytes(), false).v2(), XContentHelper.convertToMap(expectedJson.bytes(), false).v2()); throw new AssertionError("Didn't match expected value:\n" + message); } catch (IOException e) { throw new AssertionError("IOException while building failure message", e); } }
/** * Renders the provided instance in XContent * * @param instance * the instance to render * @param contentType * the content type to render to */ protected static <T extends ToXContent> XContentBuilder toXContent(T instance, XContentType contentType) throws IOException { XContentBuilder builder = XContentFactory.contentBuilder(contentType); if (randomBoolean()) { builder.prettyPrint(); } instance.toXContent(builder, ToXContent.EMPTY_PARAMS); return builder; }
public void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field(Fields.REPOSITORY, entry.snapshotId().getRepository()); builder.field(Fields.SNAPSHOT, entry.snapshotId().getSnapshot()); builder.field(Fields.INCLUDE_GLOBAL_STATE, entry.includeGlobalState()); builder.field(Fields.STATE, entry.state()); builder.startArray(Fields.INDICES); { for (String index : entry.indices()) { builder.value(index); } } builder.endArray(); builder.timeValueField(Fields.START_TIME_MILLIS, Fields.START_TIME, entry.startTime()); builder.startArray(Fields.SHARDS); { for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards.entrySet()) { ShardId shardId = shardEntry.getKey(); ShardSnapshotStatus status = shardEntry.getValue(); builder.startObject(); { builder.field(Fields.INDEX, shardId.getIndex()); builder.field(Fields.SHARD, shardId.getId()); builder.field(Fields.STATE, status.state()); builder.field(Fields.NODE, status.nodeId()); } builder.endObject(); } } builder.endArray(); builder.endObject(); }
@Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(Fields.QUERY_CACHE); builder.byteSizeField(Fields.MEMORY_SIZE_IN_BYTES, Fields.MEMORY_SIZE, ramBytesUsed); builder.field(Fields.TOTAL_COUNT, getTotalCount()); builder.field(Fields.HIT_COUNT, getHitCount()); builder.field(Fields.MISS_COUNT, getMissCount()); builder.field(Fields.CACHE_SIZE, getCacheSize()); builder.field(Fields.CACHE_COUNT, getCacheCount()); builder.field(Fields.EVICTIONS, getEvictions()); builder.endObject(); return builder; }
@Override public String toString() { try { return toXContent(JsonXContent.contentBuilder(), ToXContent.EMPTY_PARAMS).string(); } catch (IOException e) { return super.toString(); } }
private static BytesReference toXContent(ToXContent result) throws IOException { try (XContentBuilder builder = XContentFactory.contentBuilder(Requests.INDEX_CONTENT_TYPE)) { // Elasticsearch's Response object never emit starting or ending objects. Most other implementers of ToXContent do.... builder.startObject(); result.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); return builder.bytes(); } }
private static BytesReference toXContent(Exception error) throws IOException { try (XContentBuilder builder = XContentFactory.contentBuilder(Requests.INDEX_CONTENT_TYPE)) { builder.startObject(); ElasticsearchException.generateThrowableXContent(builder, ToXContent.EMPTY_PARAMS, error); builder.endObject(); return builder.bytes(); } }
/** * Writes the snapshots metadata and the related indices metadata to x-content, omitting the * incompatible snapshots. */ public XContentBuilder snapshotsToXContent(final XContentBuilder builder, final ToXContent.Params params) throws IOException { builder.startObject(); // write the snapshots list builder.startArray(SNAPSHOTS); for (final SnapshotId snapshot : getSnapshotIds()) { snapshot.toXContent(builder, params); } builder.endArray(); // write the indices map builder.startObject(INDICES); for (final IndexId indexId : getIndices().values()) { builder.startObject(indexId.getName()); builder.field(INDEX_ID, indexId.getId()); builder.startArray(SNAPSHOTS); Set<SnapshotId> snapshotIds = indexSnapshots.get(indexId); assert snapshotIds != null; for (final SnapshotId snapshotId : snapshotIds) { snapshotId.toXContent(builder, params); } builder.endArray(); builder.endObject(); } builder.endObject(); builder.endObject(); return builder; }
/** * Writes the incompatible snapshot ids to x-content. */ public XContentBuilder incompatibleSnapshotsToXContent(final XContentBuilder builder, final ToXContent.Params params) throws IOException { builder.startObject(); // write the incompatible snapshots list builder.startArray(INCOMPATIBLE_SNAPSHOTS); for (final SnapshotId snapshot : getIncompatibleSnapshotIds()) { snapshot.toXContent(builder, params); } builder.endArray(); builder.endObject(); return builder; }
public void testXContent() throws IOException { final String name = randomAsciiOfLengthBetween(4, 15); final String uuid = UUIDs.randomBase64UUID(); final Index original = new Index(name, uuid); final XContentBuilder builder = JsonXContent.contentBuilder(); original.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentParser parser = createParser(JsonXContent.jsonXContent, builder.bytes()); parser.nextToken(); // the beginning of the parser assertThat(Index.fromXContent(parser), equalTo(original)); }
public void testSerialization() throws IOException { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", "boolean").endObject().endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = parser.parse("type", new CompressedXContent(mapping)); FieldMapper mapper = defaultMapper.mappers().getMapper("field"); XContentBuilder builder = XContentFactory.jsonBuilder().startObject(); mapper.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); assertEquals("{\"field\":{\"type\":\"boolean\"}}", builder.string()); // now change some parameters mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field") .field("type", "boolean") .field("doc_values", "false") .field("null_value", true) .endObject().endObject() .endObject().endObject().string(); defaultMapper = parser.parse("type", new CompressedXContent(mapping)); mapper = defaultMapper.mappers().getMapper("field"); builder = XContentFactory.jsonBuilder().startObject(); mapper.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); assertEquals("{\"field\":{\"type\":\"boolean\",\"doc_values\":false,\"null_value\":true}}", builder.string()); }