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

The following examples show how to use org.elasticsearch.common.xcontent.json.JsonXContent. These examples are extracted from open source projects. 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 Project: crate   Source File: UsersPrivilegesMetaDataTest.java    License: 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 2
Source Project: Elasticsearch   Source File: ResponseUtil.java    License: 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 3
Source Project: crate   Source File: XContentTestUtilsTests.java    License: 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 4
Source Project: ElasticUtils   Source File: BaseElasticSearchMapping.java    License: 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 5
@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 6
Source Project: crate   Source File: ViewsMetaDataTest.java    License: 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 7
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 8
Source Project: shield-custom-realm-example   Source File: CustomRealmIT.java    License: 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 9
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 10
Source Project: crate   Source File: RestActionReceiversTest.java    License: 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 11
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 12
Source Project: crate   Source File: LicenseKeyTest.java    License: 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 13
Source Project: elasticsearch-taste   Source File: TasteActionRestAction.java    License: 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 14
Source Project: elasticsearch-rest-command   Source File: Search.java    License: 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 15
Source Project: crate   Source File: LicenseKeyTest.java    License: 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 16
@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 17
@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 18
Source Project: elasticsearch-helper   Source File: HttpSearchAction.java    License: 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 19
Source Project: elasticsearch-helper   Source File: HttpBulkAction.java    License: 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 20
Source Project: elasticsearch-carrot2   Source File: SampleIndexTestCase.java    License: 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 21
Source Project: elasticshell   Source File: AbstractClient.java    License: 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 22
Source Project: crate   Source File: GeoUtils.java    License: 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 23
Source Project: crate   Source File: JsonType.java    License: 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 24
Source Project: crate   Source File: UsersMetaDataTest.java    License: 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 25
Source Project: crate   Source File: TransportSchemaUpdateAction.java    License: 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 26
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 27
public String toPrettyString() {
    try {
        return Strings.toString(JsonXContent.contentBuilder().prettyPrint().map(getAsMap()));
    } catch (final IOException e) {
        throw ExceptionsHelper.convertToElastic(e);
    }
}
 
Example 28
Source Project: crate   Source File: UsersMetaDataTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUsersMetaDataFromLegacyXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // Generate legacy (v1) XContent of UsersMetaData
    // { "users": [ "Ford", "Arthur" ] }
    builder.startObject();
    builder.startArray("users");
    builder.value("Ford");
    builder.value("Arthur");
    builder.endArray();
    builder.endObject();

    HashMap<String, SecureHash> expectedUsers = new HashMap<>();
    expectedUsers.put("Ford", null);
    expectedUsers.put("Arthur", null);

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

    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example 29
Source Project: ProjectStudy   Source File: LowLevelRestController.java    License: MIT License 5 votes vote down vote up
/**
   * 分词分页查询列表
   *
   * @param page
* @param rows
* @param keyword
   * @return com.example.common.ResponseBean
   * @author wliduo[[email protected]]
   * @date 2019/8/9 15:32
   */
  @GetMapping("/book")
  public ResponseBean getBookList(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer rows,
                                  String keyword) {
      Request request = new Request("POST", new StringBuilder("/_search").toString());
      // 添加Json返回优化
      request.addParameter("pretty", "true");
      // 拼接查询Json
      IndexRequest indexRequest = new IndexRequest();
      XContentBuilder builder = null;
      Response response = null;
      String responseBody = null;
      try {
          builder = JsonXContent.contentBuilder()
                  .startObject()
                  .startObject("query")
                  .startObject("multi_match")
                  .field("query", keyword)
                  .array("fields", new String[]{"name", "desc"})
                  .endObject()
                  .endObject()
                  .startObject("sort")
                  .startObject("id")
                  .field("order", "desc")
                  .endObject()
                  .endObject()
                  .endObject();
          indexRequest.source(builder);
          // 设置请求体并指定ContentType,如果不指定会乱码
          request.setEntity(new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON));
          // 执行HTTP请求
          response = restClient.performRequest(request);
          responseBody = EntityUtils.toString(response.getEntity());
      } catch (IOException e) {
          return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null);
      }
      return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
  }
 
Example 30
Source Project: ProjectStudy   Source File: LowLevelRestController.java    License: MIT License 5 votes vote down vote up
/**
   * 分词分页查询列表
   *
   * @param page
* @param rows
* @param keyword
   * @return com.example.common.ResponseBean
   * @author wliduo[[email protected]]
   * @date 2019/8/9 15:32
   */
  @GetMapping("/book")
  public ResponseBean getBookList(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer rows,
                                  String keyword) {
      Request request = new Request("POST", new StringBuilder("/_search").toString());
      // 添加Json返回优化
      request.addParameter("pretty", "true");
      // 拼接查询Json
      IndexRequest indexRequest = new IndexRequest();
      XContentBuilder builder = null;
      Response response = null;
      String responseBody = null;
      try {
          builder = JsonXContent.contentBuilder()
                  .startObject()
                  .startObject("query")
                  .startObject("multi_match")
                  .field("query", keyword)
                  .array("fields", new String[]{"name", "desc"})
                  .endObject()
                  .endObject()
                  .startObject("sort")
                  .startObject("id")
                  .field("order", "desc")
                  .endObject()
                  .endObject()
                  .endObject();
          indexRequest.source(builder);
          // 设置请求体并指定ContentType,如果不指定会乱码
          request.setEntity(new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON));
          // 执行HTTP请求
          response = restClient.performRequest(request);
          responseBody = EntityUtils.toString(response.getEntity());
      } catch (IOException e) {
          return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null);
      }
      return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
  }