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

The following examples show how to use org.elasticsearch.common.xcontent.XContentBuilder#bytes() . 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: XmlFilter.java    From elasticsearch-xml with Apache License 2.0 6 votes vote down vote up
@Override
public BytesReference content() {
    if (isXml(request)) {
        XContentParser parser = null;
        try {
            BytesReference b = request.content();
            parser = XmlXContentFactory.xContent(XmlXContentType.XML).createParser(b);
            parser.nextToken();
            XContentBuilder builder = XContentFactory.jsonBuilder();
            builder.copyCurrentStructure(parser);
            return builder.bytes();
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (parser != null) {
                parser.close();
            }
        }
    }
    return request.content();
}
 
Example 2
Source File: MappingMetaData.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public MappingMetaData(CompressedXContent mapping) throws IOException {
    Map<String, Object> mappingMap;
    try (XContentParser parser = XContentHelper.createParser(mapping.compressedReference())) {
        mappingMap = parser.mapOrdered();
    }
    if (mappingMap.containsKey(MAPPING_VERSION)) {
        this.mappingVersion = (int)mappingMap.get(MAPPING_VERSION);
        mappingMap.remove(MAPPING_VERSION);
    } else {
        this.mappingVersion = 1;
    }
    XContentBuilder mappingBuilder = XContentFactory.jsonBuilder().map(mappingMap);
    this.source = new CompressedXContent(mappingBuilder.bytes());
    if (mappingMap.size() != 1) {
        throw new IllegalStateException("Can't derive type from mapping, no root type: " + mapping.string());
    }
    this.type = mappingMap.keySet().iterator().next();
    initMappers((Map<String, Object>) mappingMap.get(this.type));
}
 
Example 3
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 4
Source File: BytesRestResponse.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public BytesRestResponse(RestChannel channel, RestStatus status, Throwable t) throws IOException {
    this.status = status;
    if (channel.request().method() == RestRequest.Method.HEAD) {
        this.content = BytesArray.EMPTY;
        this.contentType = TEXT_CONTENT_TYPE;
    } else {
        XContentBuilder builder = convert(channel, status, t);
        this.content = builder.bytes();
        this.contentType = builder.contentType().restContentType();
    }
    if (t instanceof ElasticsearchException) {
        copyHeaders(((ElasticsearchException) t));
    }
}
 
Example 5
Source File: MappingMetaData.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public MappingMetaData(String type, Map<String, Object> mapping, long mappingVersion) throws IOException {
    this.type = type;
    this.mappingVersion = mappingVersion;
    XContentBuilder mappingBuilder = XContentFactory.jsonBuilder().map(mapping);
    this.source = new CompressedXContent(mappingBuilder.bytes());
    Map<String, Object> withoutType = mapping;
    if (mapping.size() == 1 && mapping.containsKey(type)) {
        withoutType = (Map<String, Object>) mapping.get(type);
    }
    initMappers(withoutType);
}
 
Example 6
Source File: ElasticsearchIntegrationTest.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
protected static BytesReference readXContent(final Reader reader, final XContentType contentType) throws IOException {
    XContentParser parser = null;
    try {
        parser = XContentFactory.xContent(contentType).createParser(NamedXContentRegistry.EMPTY, reader);
        parser.nextToken();
        final XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.copyCurrentStructure(parser);
        return builder.bytes();
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}
 
Example 7
Source File: ToXContentToBytes.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link org.elasticsearch.common.bytes.BytesReference}
 * containing the {@link ToXContent} output in binary format.
 * Builds the request as the provided <code>contentType</code>
 */
public final BytesReference buildAsBytes(XContentType contentType) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(contentType);
        toXContent(builder, ToXContent.EMPTY_PARAMS);
        return builder.bytes();
    } catch (Exception e) {
        throw new ElasticsearchException("Failed to build ToXContent", e);
    }
}
 
Example 8
Source File: CrateThrowableRestResponse.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public CrateThrowableRestResponse(RestChannel channel, Throwable t) throws IOException {
    status = (t instanceof ElasticsearchException) ?
            ((ElasticsearchException) t).status() :
            RestStatus.INTERNAL_SERVER_ERROR;
    if (channel.request().method() == RestRequest.Method.HEAD) {
        this.content = BytesArray.EMPTY;
        this.contentType = BytesRestResponse.TEXT_CONTENT_TYPE;
    } else {
        XContentBuilder builder = convert(channel, t);
        this.content = builder.bytes();
        this.contentType = builder.contentType().restContentType();
    }
}
 
Example 9
Source File: ValidateQueryRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public ValidateQueryRequest source(XContentBuilder builder) {
    this.source = builder.bytes();
    return this;
}
 
Example 10
Source File: TermsByQueryRequest.java    From siren-join with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * The query source to execute.
 */
public TermsByQueryRequest query(XContentBuilder builder) {
  this.querySource = builder == null ? null : builder.bytes();
  return this;
}
 
Example 11
Source File: SearchRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public SearchRequest extraSource(XContentBuilder builder) {
    this.extraSource = builder.bytes();
    return this;
}
 
Example 12
Source File: SearchRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public SearchRequest source(XContentBuilder builder) {
    this.source = builder.bytes();
    return this;
}
 
Example 13
Source File: PutIndexedScriptRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the content source to index.
 */
public PutIndexedScriptRequest source(XContentBuilder sourceBuilder) {
    source = sourceBuilder.bytes();
    return this;
}
 
Example 14
Source File: PercolateSourceBuilder.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the document to be percolated.
 */
public DocBuilder setDoc(XContentBuilder doc) {
    this.doc = doc.bytes();
    return this;
}
 
Example 15
Source File: PercolateRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Raw version of {@link #source(PercolateSourceBuilder)}
 */
public PercolateRequest source(XContentBuilder documentBuilder) {
    source = documentBuilder.bytes();
    return this;
}
 
Example 16
Source File: CountRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public CountRequest source(XContentBuilder builder) {
    this.source = builder.bytes();
    return this;
}
 
Example 17
Source File: ExistsRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public ExistsRequest source(XContentBuilder builder) {
    this.source = builder.bytes();
    return this;
}
 
Example 18
Source File: BytesRestResponse.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new response based on {@link XContentBuilder}.
 */
public BytesRestResponse(RestStatus status, XContentBuilder builder) {
    this(status, builder.contentType().restContentType(), builder.bytes());
}
 
Example 19
Source File: TransportShardUpsertAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Prepares an update request by converting it into an index request.
 * <p/>
 * TODO: detect a NOOP and return an update response if true
 */
@SuppressWarnings("unchecked")
private SourceAndVersion prepareUpdate(DocTableInfo tableInfo,
                                       ShardUpsertRequest request,
                                       ShardUpsertRequest.Item item,
                                       IndexShard indexShard) throws ElasticsearchException {
    final GetResult getResult = indexShard.getService().get(request.type(), item.id(),
            new String[]{RoutingFieldMapper.NAME, ParentFieldMapper.NAME, TTLFieldMapper.NAME},
            true, Versions.MATCH_ANY, VersionType.INTERNAL, FetchSourceContext.FETCH_SOURCE, false);

    if (!getResult.isExists()) {
        throw new DocumentMissingException(new ShardId(request.index(), request.shardId().id()), request.type(), item.id());
    }

    if (getResult.internalSourceRef() == null) {
        // no source, we can't do nothing, through a failure...
        throw new DocumentSourceMissingException(new ShardId(request.index(), request.shardId().id()), request.type(), item.id());
    }

    if (item.version() != Versions.MATCH_ANY && item.version() != getResult.getVersion()) {
        throw new VersionConflictEngineException(
                indexShard.shardId(), Constants.DEFAULT_MAPPING_TYPE, item.id(), getResult.getVersion(), item.version());
    }

    Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(getResult.internalSourceRef(), true);
    final Map<String, Object> updatedSourceAsMap;
    final XContentType updateSourceContentType = sourceAndContent.v1();

    updatedSourceAsMap = sourceAndContent.v2();

    SymbolToFieldExtractorContext ctx = new SymbolToFieldExtractorContext(functions, item.insertValues());

    Map<String, Object> pathsToUpdate = new LinkedHashMap<>();
    Map<String, Object> updatedGeneratedColumns = new LinkedHashMap<>();
    for (int i = 0; i < request.updateColumns().length; i++) {
        /**
         * NOTE: mapping isn't applied. So if an Insert was done using the ES Rest Endpoint
         * the data might be returned in the wrong format (date as string instead of long)
         */
        String columnPath = request.updateColumns()[i];
        Object value = SYMBOL_TO_FIELD_EXTRACTOR.convert(item.updateAssignments()[i], ctx).apply(getResult);
        ReferenceInfo referenceInfo = tableInfo.getReferenceInfo(ColumnIdent.fromPath(columnPath));
        if (referenceInfo instanceof GeneratedReferenceInfo) {
            updatedGeneratedColumns.put(columnPath, value);

        } else {
            pathsToUpdate.put(columnPath, value);
        }
    }

    processGeneratedColumns(tableInfo, pathsToUpdate, updatedGeneratedColumns, request.validateGeneratedColumns(), getResult);

    updateSourceByPaths(updatedSourceAsMap, pathsToUpdate);

    try {
        XContentBuilder builder = XContentFactory.contentBuilder(updateSourceContentType);
        builder.map(updatedSourceAsMap);
        return new SourceAndVersion(builder.bytes(), getResult.getVersion());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + updatedSourceAsMap + "]", e);
    }
}