Java Code Examples for org.elasticsearch.common.xcontent.XContentBuilder#close()

The following examples show how to use org.elasticsearch.common.xcontent.XContentBuilder#close() . 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: BlobStoreRepository.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Writes snapshot index file
 * <p>
 * This file can be used by read-only repositories that are unable to list files in the repository
 *
 * @param snapshots list of snapshot ids
 * @throws IOException I/O errors
 */
protected void writeSnapshotList(List<SnapshotId> snapshots) throws IOException {
    final BytesReference bRef;
    try(BytesStreamOutput bStream = new BytesStreamOutput()) {
        try(StreamOutput stream = new OutputStreamStreamOutput(bStream)) {
            XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON, stream);
            builder.startObject();
            builder.startArray("snapshots");
            for (SnapshotId snapshot : snapshots) {
                builder.value(snapshot.getSnapshot());
            }
            builder.endArray();
            builder.endObject();
            builder.close();
        }
        bRef = bStream.bytes();
    }
    if (snapshotsBlobContainer.blobExists(SNAPSHOTS_FILE)) {
        snapshotsBlobContainer.deleteBlob(SNAPSHOTS_FILE);
    }
    snapshotsBlobContainer.writeBlob(SNAPSHOTS_FILE, bRef);
}
 
Example 2
Source File: Alias.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
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: ArrayMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    /**
     * array mapping should look like:
     *
     * "fieldName": {
     *      "type": "array":
     *      "inner": {
     *          "type": "string"
     *          ...
     *      }
     * }
     *
     *
     * Use the innerMapper to generate the mapping for the inner type which will look like:
     *
     * "fieldName": {
     *      "type": "string",
     *      ...
     * }
     *
     * and then parse the contents of the object to set it into the "inner" field of the outer array type.
     */
    XContentBuilder innerBuilder = new XContentBuilder(builder.contentType().xContent(), new BytesStreamOutput(0));
    innerBuilder = innerMapper.toXContent(innerBuilder, params);
    innerBuilder.close();
    XContentParser parser = builder.contentType().xContent().createParser(innerBuilder.bytes());

    //noinspection StatementWithEmptyBody
    while ((parser.nextToken() != XContentParser.Token.START_OBJECT)) {
        // consume tokens until start of object
    }
    Map<String, Object> innerMap = parser.mapOrdered();

    builder.startObject(simpleName());
    builder.field("type", contentType());
    builder.field(INNER, innerMap);
    return builder.endObject();
}
 
Example 5
Source File: PercolatorQueriesRegistry.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
Query parsePercolatorDocument(String id, BytesReference source) {
    String type = null;
    BytesReference querySource = null;
    try (XContentParser sourceParser = XContentHelper.createParser(source)) {
        String currentFieldName = null;
        XContentParser.Token token = sourceParser.nextToken(); // move the START_OBJECT
        if (token != XContentParser.Token.START_OBJECT) {
            throw new ElasticsearchException("failed to parse query [" + id + "], not starting with OBJECT");
        }
        while ((token = sourceParser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = sourceParser.currentName();
            } else if (token == XContentParser.Token.START_OBJECT) {
                if ("query".equals(currentFieldName)) {
                    if (type != null) {
                        return parseQuery(type, sourceParser);
                    } else {
                        XContentBuilder builder = XContentFactory.contentBuilder(sourceParser.contentType());
                        builder.copyCurrentStructure(sourceParser);
                        querySource = builder.bytes();
                        builder.close();
                    }
                } else {
                    sourceParser.skipChildren();
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                sourceParser.skipChildren();
            } else if (token.isValue()) {
                if ("type".equals(currentFieldName)) {
                    type = sourceParser.text();
                }
            }
        }
        try (XContentParser queryParser = XContentHelper.createParser(querySource)) {
            return parseQuery(type, queryParser);
        }
    } catch (Exception e) {
        throw new PercolatorException(shardId().index(), "failed to parse query [" + id + "]", e);
    }
}
 
Example 6
Source File: AliasAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public AliasAction filter(QueryBuilder queryBuilder) {
    if (queryBuilder == null) {
        this.filter = null;
        return this;
    }
    try {
        XContentBuilder builder = XContentFactory.jsonBuilder();
        queryBuilder.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);
    }
}
 
Example 7
Source File: LoggingSearchExtBuilderTests.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
public void testToXCtontent() throws IOException {
    LoggingSearchExtBuilder ext1 = buildTestExt();
    XContentBuilder builder = XContentFactory.jsonBuilder();
    ext1.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.close();
    assertEquals(getTestExtAsString(), Strings.toString(builder));
}
 
Example 8
Source File: ElasticEventsController.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/reports/eventSearch", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public void eventSearch(final HttpEntity<String> httpEntity,
		final HttpServletResponse response) throws IOException {
	long start = System.currentTimeMillis();
	String jsonRequest = httpEntity.getBody();
	final SearchRequest searchRequest = new SearchRequest(indexName);
	try {
		searchRequest.source(jsonRequest);
		searchRequest.types("event");
		SearchResponse r = clientTpl
				.executeWithClient(new ClientCallback<SearchResponse>() {
					@Override
					public SearchResponse execute(final Client client) {
						return client.search(searchRequest).actionGet();
					}
				});
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		OutputStream responseStream = response.getOutputStream();
		XContentBuilder builder = XContentFactory
				.jsonBuilder(responseStream);
		builder.startObject();
		r.toXContent(builder, ToXContent.EMPTY_PARAMS);
		builder.endObject();
		builder.close();
		responseStream.close();
	} finally {
		logger.debug("Executed search in {}ms: {}",
				System.currentTimeMillis() - start, jsonRequest);
	}
}
 
Example 9
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;
}
 
Example 10
Source File: BasicGetResponse.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
public BasicGetResponse toJson(OutputStream out) throws IOException {
    if (out == null) {
        return this;
    }
    if (getResponse == null) {
        out.write(jsonErrorMessage("no response yet"));
        return this;
    }
    XContentBuilder jsonBuilder = new XContentBuilder(JsonXContent.jsonXContent, out);
    getResponse.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS);
    jsonBuilder.close();
    return this;
}
 
Example 11
Source File: SampleIndexTestCase.java    From elasticsearch-carrot2 with Apache License 2.0 5 votes vote down vote up
protected byte[] jsonResourceAs(String resourceName, XContentType toType) throws IOException {
   byte[] bytes = resource(resourceName);
   XContentParser parser = XContentFactory.xContent(XContentType.JSON)
       .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, bytes);

   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   XContentBuilder builder = XContentFactory.contentBuilder(toType, baos).copyCurrentStructure(parser);
   builder.close();

   return baos.toByteArray();
}
 
Example 12
Source File: BytesReference.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Convert an {@link XContentBuilder} into a BytesReference. This method closes the builder,
 * so no further fields may be added.
 */
public static BytesReference bytes(XContentBuilder xContentBuilder) {
    xContentBuilder.close();
    OutputStream stream = xContentBuilder.getOutputStream();
    if (stream instanceof ByteArrayOutputStream) {
        return new BytesArray(((ByteArrayOutputStream) stream).toByteArray());
    } else {
        return ((BytesStream) stream).bytes();
    }
}