Java Code Examples for org.elasticsearch.common.xcontent.json.JsonXContent#contentBuilder()

The following examples show how to use org.elasticsearch.common.xcontent.json.JsonXContent#contentBuilder() . 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: RestActionReceiversTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testRestRowCountReceiver() throws Exception {
    RestRowCountReceiver receiver = new RestRowCountReceiver(JsonXContent.contentBuilder(), 0L, true);
    receiver.setNextRow(row);
    XContentBuilder actualBuilder = receiver.finishBuilder();

    ResultToXContentBuilder builder = ResultToXContentBuilder.builder(JsonXContent.contentBuilder());
    builder.cols(Collections.<ScopedSymbol>emptyList());
    builder.colTypes(Collections.<ScopedSymbol>emptyList());
    builder.startRows();
    builder.addRow(row, 0);
    builder.finishRows();
    builder.rowCount(1L);

    assertXContentBuilder(actualBuilder, builder.build());
}
 
Example 2
Source File: TransportSchemaUpdateAction.java    From crate with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static ClusterState updateTemplate(NamedXContentRegistry xContentRegistry,
                                   ClusterState currentState,
                                   String templateName,
                                   Map<String, Object> newMapping) throws Exception {
    IndexTemplateMetaData template = currentState.metaData().templates().get(templateName);
    if (template == null) {
        throw new ResourceNotFoundException("Template \"" + templateName + "\" for partitioned table is missing");
    }

    IndexTemplateMetaData.Builder templateBuilder = new IndexTemplateMetaData.Builder(template);
    for (ObjectObjectCursor<String, CompressedXContent> cursor : template.mappings()) {
        Map<String, Object> source = parseMapping(xContentRegistry, cursor.value.toString());
        mergeIntoSource(source, newMapping);
        try (XContentBuilder xContentBuilder = JsonXContent.contentBuilder()) {
            templateBuilder.putMapping(cursor.key, Strings.toString(xContentBuilder.map(source)));
        }
    }
    MetaData.Builder builder = MetaData.builder(currentState.metaData()).put(templateBuilder);
    return ClusterState.builder(currentState).metaData(builder).build();
}
 
Example 3
Source File: JsonType.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
protected byte[] encodeAsUTF8Text(@Nonnull Object value) {
    try {
        XContentBuilder builder = JsonXContent.contentBuilder();
        if (value instanceof List) {
            List values = ((List) value);
            builder.startArray();
            for (Object o : values) {
                builder.value(o);
            }
            builder.endArray();
        } else {
            builder.map((Map) value);
        }
        builder.close();
        return BytesReference.toBytes(BytesReference.bytes(builder));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
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 5
Source File: AbstractClient.java    From elasticshell with Apache License 2.0 6 votes vote down vote up
public JsonOutput availableNodes() throws Exception {
    ClusterStateResponse response = this.client.admin().cluster().state(new ClusterStateRequest()
            .filterBlocks(true).filterNodes(false).filterMetaData(true)
            .filterRoutingTable(true)).actionGet();

    XContentBuilder builder = JsonXContent.contentBuilder();
    builder.startObject();
    for (DiscoveryNode discoveryNode : response.getState().nodes()) {
        builder.startObject(discoveryNode.id());
        builder.field("name", discoveryNode.name());
        builder.endObject();
    }
    builder.endObject();

    return stringToJson.stringToJson(builder.string());
}
 
Example 6
Source File: ResponseUtil.java    From elasticsearch-auth with Apache License 2.0 6 votes vote down vote up
public static void send(final RestRequest request,
        final RestChannel channel, final RestStatus status,
        final String... args) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        builder.startObject();
        builder.field("status", status.getStatus());
        for (int i = 0; i < args.length; i += 2) {
            builder.field(args[i], args[i + 1]);
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(status, builder));
    } catch (final IOException e) {
        logger.error("Failed to send a response.", e);
        try {
            channel.sendResponse(new BytesRestResponse(channel, e));
        } catch (final IOException e1) {
            logger.error("Failed to send a failure response.", e1);
        }
    }
}
 
Example 7
Source File: RestDataAction.java    From elasticsearch-dataformat with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request, final RestChannel channel, final String file) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        final String pretty = request.param("pretty");
        if (pretty != null && !"false".equalsIgnoreCase(pretty)) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", true);
        builder.field("file", file);
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final IOException e) {
        throw new ElasticsearchException("Failed to create a resposne.", e);
    }
}
 
Example 8
Source File: TasteActionRestAction.java    From elasticsearch-taste with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request,
        final RestChannel channel, final Map<String, Object> params,
        final boolean acknowledged) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        if (request.hasParam("pretty")) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", acknowledged);
        if (params != null) {
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                builder.field(entry.getKey(), entry.getValue());
            }
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final Exception e) {
        sendErrorResponse(channel, e);
    }
}
 
Example 9
Source File: ReindexRestAction.java    From elasticsearch-reindexing with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request,
        final RestChannel channel, final Map<String, Object> params) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        if (request.hasParam("pretty")) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", true);
        if (params != null) {
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                builder.field(entry.getKey(), entry.getValue());
            }
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final Exception e) {
        sendErrorResponse(channel, e);
    }
}
 
Example 10
Source File: LinearRankerParserTests.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
public void testParse() throws IOException {
    XContentBuilder builder = JsonXContent.contentBuilder();
    StoredFeatureSet set = LtrTestUtils.randomFeatureSet();
    float[] expectedWeights = new float[set.size()];
    builder.startObject();
    for (int i = 0; i < set.size(); i++) {
        float weight = random().nextFloat();
        expectedWeights[i] = weight;
        builder.field(set.feature(i).name(), weight);
    }
    builder.endObject();
    String json = Strings.toString(builder);
    LinearRankerParser parser = new LinearRankerParser();
    LinearRanker ranker = parser.parse(set, json);
    DenseFeatureVector v = ranker.newFeatureVector(null);
    LinearRankerTests.fillRandomWeights(v.scores);
    LinearRanker expectedRanker = new LinearRanker(expectedWeights);
    Assert.assertEquals(expectedRanker.score(v), ranker.score(v), Math.ulp(expectedRanker.score(v)));
}
 
Example 11
Source File: ResponseUtil.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static void send(final RestChannel channel, final RestStatus status, final String message) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        builder.startObject()
                .field("status", status.getStatus())
                .field("message", message).endObject();
        BytesRestResponse bytesRestResponse = new BytesRestResponse(status, builder);
        if (status == RestStatus.UNAUTHORIZED) {
            bytesRestResponse.addHeader("WWW-authenticate", "Basic realm=\"Elasticsearch Authentication\"");
        }
        channel.sendResponse(bytesRestResponse);
    } catch (final IOException e) {
        logger.error("Failed to send a response.", e);
        try {
            channel.sendResponse(new BytesRestResponse(channel, e));
        } catch (final IOException e1) {
            logger.error("Failed to send a failure response.", e1);
        }
    }
}
 
Example 12
Source File: LtrTestUtils.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
public static StoredLtrModel randomLinearModel(String name, StoredFeatureSet set) throws IOException {
    XContentBuilder builder = JsonXContent.contentBuilder();
    builder.startObject();
    for (int i = 0; i < set.size(); i++) {
        builder.field(set.feature(i).name(), random().nextFloat());
    }
    builder.endObject();
    return new StoredLtrModel(name, set, LinearRankerParser.TYPE, Strings.toString(builder), false, randomFtrNorms(set));
}
 
Example 13
Source File: LinearRankerParserTests.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
public static String generateRandomModelString(FeatureSet set) throws IOException {
    XContentBuilder builder = JsonXContent.contentBuilder();
    builder.startObject();
    for (int i = 0; i < set.size(); i++) {
        builder.field(set.feature(i).name(), random().nextFloat());
    }
    builder.endObject().close();
    return Strings.toString(builder);
}
 
Example 14
Source File: StoredLtrModel.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
private void parseModel(XContentParser parser) throws IOException {
        if (parser.currentToken() == XContentParser.Token.VALUE_STRING) {
            modelAsString = true;
            definition = parser.text();
        } else {
            try (XContentBuilder builder = JsonXContent.contentBuilder()) {
                builder.copyCurrentStructure(parser);
                modelAsString = false;
                definition = Strings.toString(builder);
            }
        }
}
 
Example 15
Source File: Strings.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link String} that is the json representation of the provided
 * {@link ToXContent}.
 */
public static String toString(ToXContent toXContent) {
    try {
        XContentBuilder builder = JsonXContent.contentBuilder();
        toXContent.toXContent(builder, ToXContent.EMPTY_PARAMS);
        return builder.string();
    } catch (IOException e) {
        throw new AssertionError("Cannot happen", e);
    }
}
 
Example 16
Source File: XContentFactory.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a binary content builder for the provided content type.
 */
public static XContentBuilder contentBuilder(XContentType type) throws IOException {
    if (type == XContentType.JSON) {
        return JsonXContent.contentBuilder();
    } else if (type == XContentType.SMILE) {
        return SmileXContent.contentBuilder();
    } else if (type == XContentType.YAML) {
        return YamlXContent.contentBuilder();
    }
    throw new IllegalArgumentException("No matching content type for " + type);
}
 
Example 17
Source File: Strings.java    From crate with Apache License 2.0 5 votes vote down vote up
private static XContentBuilder createBuilder(boolean pretty, boolean human) throws IOException {
    XContentBuilder builder = JsonXContent.contentBuilder();
    if (pretty) {
        builder.prettyPrint();
    }
    if (human) {
        builder.humanReadable(true);
    }
    return builder;
}
 
Example 18
Source File: RepositoryDataTests.java    From crate with Apache License 2.0 5 votes vote down vote up
public void testXContent() throws IOException {
    RepositoryData repositoryData = generateRandomRepoData();
    XContentBuilder builder = JsonXContent.contentBuilder();
    repositoryData.snapshotsToXContent(builder, true);
    try (XContentParser parser = createParser(JsonXContent.JSON_XCONTENT, BytesReference.bytes(builder))) {
        long gen = (long) randomIntBetween(0, 500);
        RepositoryData fromXContent = RepositoryData.snapshotsFromXContent(parser, gen);
        assertEquals(repositoryData, fromXContent);
        assertEquals(gen, fromXContent.getGenId());
    }
}
 
Example 19
Source File: SqlHttpHandler.java    From crate with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<XContentBuilder> executeSimpleRequest(Session session,
                                                                String stmt,
                                                                List<Object> args,
                                                                boolean includeTypes) throws IOException {
    long startTimeInNs = System.nanoTime();
    session.parse(UNNAMED, stmt, emptyList());
    session.bind(UNNAMED, UNNAMED, args == null ? emptyList() : args, null);
    DescribeResult description = session.describe('P', UNNAMED);
    List<Symbol> resultFields = description.getFields();
    ResultReceiver<XContentBuilder> resultReceiver;
    if (resultFields == null) {
        resultReceiver = new RestRowCountReceiver(JsonXContent.contentBuilder(), startTimeInNs, includeTypes);
    } else {
        CircuitBreaker breaker = circuitBreakerProvider.apply(HierarchyCircuitBreakerService.QUERY);
        RamAccounting ramAccounting = new BlockBasedRamAccounting(
            b -> breaker.addEstimateBytesAndMaybeBreak(b, "http-result"),
            MAX_BLOCK_SIZE_IN_BYTES);
        resultReceiver = new RestResultSetReceiver(
            JsonXContent.contentBuilder(),
            resultFields,
            startTimeInNs,
            new RowAccountingWithEstimators(
                Symbols.typeView(resultFields),
                ramAccounting
            ),
            includeTypes
        );
        resultReceiver.completionFuture().whenComplete((result, error) -> ramAccounting.close());
    }
    session.execute(UNNAMED, 0, resultReceiver);
    return session.sync()
        .thenCompose(ignored -> resultReceiver.completionFuture());
}
 
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")));
    }
}