org.elasticsearch.common.xcontent.json.JsonXContent Java Examples

The following examples show how to use org.elasticsearch.common.xcontent.json.JsonXContent. 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: 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 #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: GeoUtils.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the value as a geopoint. The following types of values are supported:
 * <p>
 * Object: has to contain either lat and lon or geohash fields
 * <p>
 * String: expected to be in "latitude, longitude" format or a geohash
 * <p>
 * Array: two or more elements, the first element is longitude, the second is latitude, the rest is ignored if ignoreZValue is true
 */
public static GeoPoint parseGeoPoint(Object value, final boolean ignoreZValue) throws ElasticsearchParseException {
    try {
        XContentBuilder content = JsonXContent.contentBuilder();
        content.startObject();
        content.field("null_value", value);
        content.endObject();

        try (InputStream stream = BytesReference.bytes(content).streamInput();
             XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
                 NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, stream)) {
            parser.nextToken(); // start object
            parser.nextToken(); // field name
            parser.nextToken(); // field value
            return parseGeoPoint(parser, new GeoPoint(), ignoreZValue);
        }

    } catch (IOException ex) {
        throw new ElasticsearchParseException("error parsing geopoint", ex);
    }
}
 
Example #4
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 #5
Source File: BaseElasticSearchMapping.java    From ElasticUtils with MIT License 6 votes vote down vote up
public XContentBuilder internalGetMapping() throws IOException {

        // Configure the RootObjectMapper:
        RootObjectMapper.Builder rootObjectMapperBuilder = getRootObjectBuilder();

        // Populate the Settings:
        Settings.Builder settingsBuilder = getSettingsBuilder();

        // Build the Mapping:
        Mapping mapping = new Mapping(
                version,
                rootObjectMapperBuilder.build(new Mapper.BuilderContext(settingsBuilder.build(), new ContentPath())),
                getMetaDataFieldMappers(),
                getSourceTransforms(),
                getMetaData());

        // Turn it into JsonXContent:
        return mapping.toXContent(JsonXContent.contentBuilder().startObject(), ToXContent.EMPTY_PARAMS);
    }
 
Example #6
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 #7
Source File: UsersMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsersMetaDataWithoutAttributesToXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();

    UsersMetaData users = new UsersMetaData(UserDefinitions.SINGLE_USER_ONLY);
    users.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        Strings.toString(builder));
    parser.nextToken(); // start object
    UsersMetaData users2 = UsersMetaData.fromXContent(parser);
    assertEquals(users, users2);

    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #8
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 #9
Source File: StoredLtrModel.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    builder.field(NAME.getPreferredName(), name);
    builder.field(FEATURE_SET.getPreferredName());
    featureSet.toXContent(builder, params);
    builder.startObject(MODEL.getPreferredName());
    builder.field(LtrModelDefinition.MODEL_TYPE.getPreferredName(), rankingModelType);
    builder.field(LtrModelDefinition.MODEL_DEFINITION.getPreferredName());
    if (modelAsString) {
        builder.value(rankingModel);
    } else {
        try (XContentParser parser = JsonXContent.jsonXContent.createParser(EMPTY,
                LoggingDeprecationHandler.INSTANCE, rankingModel)
        ) {
            builder.copyCurrentStructure(parser);
        }
    }
    builder.field(LtrModelDefinition.FEATURE_NORMALIZERS.getPreferredName());
    this.parsedFtrNorms.toXContent(builder, params);
    builder.endObject();
    builder.endObject();
    return builder;
}
 
Example #10
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 #11
Source File: SampleIndexTestCase.java    From elasticsearch-carrot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Roundtrip to/from JSON.
 */
protected static void checkJsonSerialization(ClusteringActionResponse result) throws IOException {
   XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
   builder.startObject();
   result.toXContent(builder, ToXContent.EMPTY_PARAMS);
   builder.endObject();
   String json = Strings.toString(builder);

   try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
       DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json)) {
      Map<String, Object> mapAndClose = parser.map();
      Assertions.assertThat(mapAndClose)
          .as("json-result")
          .containsKey(Fields.CLUSTERS);
   }
}
 
Example #12
Source File: ViewsMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testViewsMetaDataToXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();

    ViewsMetaData views = createMetaData();
    views.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken(); // start object
    ViewsMetaData views2 = ViewsMetaData.fromXContent(parser);
    assertEquals(views, views2);

    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #13
Source File: HttpBulkAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected BulkResponse createResponse(HttpInvocationContext<BulkRequest,BulkResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        long tookInMillis = map.containsKey("took") ? (Integer)map.get("took") : -1L;
        BulkItemResponse[] responses = parseItems((List<Map<String,?>>)map.get("items"));
        return new BulkResponse(responses, tookInMillis);
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example #14
Source File: HttpCreateIndexAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
protected CreateIndexResponse createResponse(HttpInvocationContext<CreateIndexRequest,CreateIndexResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        boolean acknowledged = map.containsKey("acknowledged") ? (Boolean)map.get("acknowledged") : false;
        return new CreateIndexResponse(acknowledged);
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example #15
Source File: UsersPrivilegesMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();

    usersPrivilegesMetaData.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        Strings.toString(builder)
    );
    parser.nextToken(); // start object
    UsersPrivilegesMetaData usersPrivilegesMetaData2 = UsersPrivilegesMetaData.fromXContent(parser);
    assertEquals(usersPrivilegesMetaData, usersPrivilegesMetaData2);

    // a metadata custom must consume its surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #16
Source File: LicenseKeyTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testLicenceKeyFromXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();
    builder.startObject(LicenseKey.WRITEABLE_TYPE)
        .field("license_key", LICENSE_KEY)
        .endObject();
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken(); // start object
    LicenseKey licenseKey2 = LicenseKey.fromXContent(parser);
    assertEquals(createLicenseKey(), licenseKey2);
    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #17
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 #18
Source File: Search.java    From elasticsearch-rest-command with The Unlicense 6 votes vote down vote up
private long executeCardinary(String field) throws IOException{
	
	SearchResponse cardResponse = cardSearch.setAggregations(
			JsonXContent.contentBuilder()
			.startObject()
               	.startObject("LIMIT")
               		.startObject("cardinality")
               			.field("field", field)
               		.endObject()
               	.endObject()
			).get();

	Cardinality limit = cardResponse.getAggregations().get("LIMIT");
	
	return limit.getValue();		
}
 
Example #19
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 #20
Source File: PathHierarchyTests.java    From elasticsearch-aggregation-pathhierarchy with MIT License 6 votes vote down vote up
public void testParser() throws Exception {
    // can create the factory with utf8 separator
    String separator = "夢";
    XContentParser stParser = createParser(JsonXContent.jsonXContent,
            "{\"field\":\"path\", \"separator\": \"" + separator + "\"}");
    XContentParser.Token token = stParser.nextToken();
    assertSame(XContentParser.Token.START_OBJECT, token);
    assertNotNull(PathHierarchyAggregationBuilder.parse("path_hierarchy", stParser));

    // can create the factory with an array of orders
    String orders = "[{\"_key\": \"asc\"}, {\"_count\": \"desc\"}]";
    stParser = createParser(JsonXContent.jsonXContent,
            "{\"field\":\"path\", \"order\": " + orders + "}");
    assertNotNull(PathHierarchyAggregationBuilder.parse("path_hierarchy", stParser));

}
 
Example #21
Source File: CustomRealmIT.java    From shield-custom-realm-example with Apache License 2.0 6 votes vote down vote up
public void testSettingsFiltering() throws Exception {
    Response response = getRestClient().performRequest("GET", "/_nodes/settings", Collections.emptyMap(), (HttpEntity) null,
        new BasicHeader(CustomRealm.USER_HEADER, randomFrom(KNOWN_USERS)),
        new BasicHeader(CustomRealm.PW_HEADER, PASSWORD));
    assertThat(response.getStatusLine().getStatusCode(), is(200));

    XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, response.getEntity().getContent());
    XContentParser.Token token;
    Settings settings = null;
    while ((token = parser.nextToken()) != null) {
        if (token == XContentParser.Token.FIELD_NAME && parser.currentName().equals("settings")) {
            parser.nextToken();
            XContentBuilder builder = XContentBuilder.builder(parser.contentType().xContent());
            settings = Settings.builder()
                    .loadFromSource(builder.copyCurrentStructure(parser).bytes().utf8ToString(), XContentType.JSON)
                    .build();
            break;
        }
    }
    assertThat(settings, notNullValue());

    logger.error("settings for shield.authc.realms.custom.users {}", settings.getGroups("shield.authc.realms.custom.users"));
    // custom is the name configured externally...
    assertTrue(settings.getGroups("shield.authc.realms.custom.users").isEmpty());
}
 
Example #22
Source File: LicenseKeyTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testLicenceKeyToXContent() throws IOException {
    LicenseKey licenseKey = createLicenseKey();
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();
    licenseKey.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken(); // start object
    LicenseKey licenseKey2 = LicenseKey.fromXContent(parser);
    assertEquals(licenseKey, licenseKey2);
    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #23
Source File: HttpRefreshIndexAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
protected RefreshResponse createResponse(HttpInvocationContext<RefreshRequest,RefreshResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        logger.info("{}", map);
        //  RefreshResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
        return new RefreshResponse();
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example #24
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 #25
Source File: HttpSearchAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected SearchResponse createResponse(HttpInvocationContext<SearchRequest,SearchResponse> httpInvocationContext) throws IOException {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    logger.info("{}", httpResponse.getContent().toString(CharsetUtil.UTF_8));
    BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
    Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();

    logger.info("{}", map);

    InternalSearchResponse internalSearchResponse = parseInternalSearchResponse(map);
    String scrollId = (String)map.get(SCROLL_ID);
    int totalShards = 0;
    int successfulShards = 0;
    if (map.containsKey(SHARDS)) {
        Map<String,?> shards = (Map<String,?>)map.get(SHARDS);
        totalShards =  shards.containsKey(TOTAL) ? (Integer)shards.get(TOTAL) : -1;
        successfulShards =  shards.containsKey(SUCCESSFUL) ? (Integer)shards.get(SUCCESSFUL) : -1;
    }
    int tookInMillis = map.containsKey(TOOK) ? (Integer)map.get(TOOK) : -1;
    ShardSearchFailure[] shardFailures = parseShardFailures(map);
    return new SearchResponse(internalSearchResponse, scrollId, totalShards, successfulShards, tookInMillis, shardFailures);
}
 
Example #26
Source File: GeoPointClusteringParserTests.java    From elasticsearch-aggregation-geoclustering with Apache License 2.0 5 votes vote down vote up
public void testParseInValidZoom() throws Exception {
    int zoom = randomIntBetween(26, 99);
    XContentParser stParser = createParser(JsonXContent.jsonXContent,
            "{\"field\":\"my_loc\", \"zoom\":" + zoom + "}");
    XContentParser.Token token = stParser.nextToken();
    assertSame(XContentParser.Token.START_OBJECT, token);

    XContentParseException ex = expectThrows(XContentParseException.class,
            () -> GeoPointClusteringAggregationBuilder.parse("geo_point_clustering", stParser));
    assertThat(ex.getMessage(), containsString("[geo_point_clustering] failed to parse field [zoom]"));
}
 
Example #27
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static BytesReference convertStructuredMapToBytes(Map<String, Object> structuredMap) {
    try {
        return BytesReference.bytes(JsonXContent.contentBuilder().map(structuredMap));
    } catch (IOException e) {
        throw new ElasticsearchParseException("Failed to convert map", e);
    }
}
 
Example #28
Source File: UserDefinedFunctionsMetaDataTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataTypeStreaming() throws Exception {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    var type = new ArrayType<>(new ArrayType<>(DataTypes.STRING));
    UserDefinedFunctionMetaData.DataTypeXContent.toXContent(type, builder, ToXContent.EMPTY_PARAMS);
    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken();  // enter START_OBJECT
    ArrayType type2 = (ArrayType) UserDefinedFunctionMetaData.DataTypeXContent.fromXContent(parser);
    assertTrue(type.equals(type2));
}
 
Example #29
Source File: SqlHttpHandler.java    From crate with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<XContentBuilder> executeBulkRequest(Session session,
                                                              String stmt,
                                                              List<List<Object>> bulkArgs) {
    final long startTimeInNs = System.nanoTime();
    session.parse(UNNAMED, stmt, emptyList());
    final RestBulkRowCountReceiver.Result[] results = new RestBulkRowCountReceiver.Result[bulkArgs.size()];
    for (int i = 0; i < bulkArgs.size(); i++) {
        session.bind(UNNAMED, UNNAMED, bulkArgs.get(i), null);
        ResultReceiver resultReceiver = new RestBulkRowCountReceiver(results, i);
        session.execute(UNNAMED, 0, resultReceiver);
    }
    if (results.length > 0) {
        DescribeResult describeResult = session.describe('P', UNNAMED);
        if (describeResult.getFields() != null) {
            return CompletableFuture.failedFuture(new UnsupportedOperationException(
                        "Bulk operations for statements that return result sets is not supported"));
        }
    }
    return session.sync()
        .thenApply(ignored -> {
            try {
                return ResultToXContentBuilder.builder(JsonXContent.contentBuilder())
                    .cols(emptyList())
                    .duration(startTimeInNs)
                    .bulkRows(results)
                    .build();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
}
 
Example #30
Source File: BasicSearchResponse.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
public BasicSearchResponse toJson(OutputStream out) throws IOException {
    if (out == null) {
        return this;
    }
    if (searchResponse == null) {
        out.write(jsonErrorMessage("no response"));
        return this;
    }
    XContentBuilder jsonBuilder = new XContentBuilder(JsonXContent.jsonXContent, out);
    jsonBuilder.startObject();
    searchResponse.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS);
    jsonBuilder.endObject();
    jsonBuilder.close();
    return this;
}