Search in sources :

Example 11 with XContentType

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class ShardSearchFailureTests method testFromXContent.

public void testFromXContent() throws IOException {
    ShardSearchFailure response = createTestItem();
    XContentType xContentType = randomFrom(XContentType.values());
    boolean humanReadable = randomBoolean();
    BytesReference originalBytes = toXContent(response, xContentType, humanReadable);
    ShardSearchFailure parsed;
    try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = ShardSearchFailure.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertEquals(response.index(), parsed.index());
    assertEquals(response.shard().getNodeId(), parsed.shard().getNodeId());
    assertEquals(response.shardId(), parsed.shardId());
    // we cannot compare the cause, because it will be wrapped in an outer ElasticSearchException
    // best effort: try to check that the original message appears somewhere in the rendered xContent
    String originalMsg = response.getCause().getMessage();
    assertEquals(parsed.getCause().getMessage(), "Elasticsearch exception [type=parsing_exception, reason=" + originalMsg + "]");
    String nestedMsg = response.getCause().getCause().getMessage();
    assertEquals(parsed.getCause().getCause().getMessage(), "Elasticsearch exception [type=illegal_argument_exception, reason=" + nestedMsg + "]");
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) XContentType(org.elasticsearch.common.xcontent.XContentType) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 12 with XContentType

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class Request method bulk.

static Request bulk(BulkRequest bulkRequest) throws IOException {
    Params parameters = Params.builder();
    parameters.withTimeout(bulkRequest.timeout());
    parameters.withRefreshPolicy(bulkRequest.getRefreshPolicy());
    // Bulk API only supports newline delimited JSON or Smile. Before executing
    // the bulk, we need to check that all requests have the same content-type
    // and this content-type is supported by the Bulk API.
    XContentType bulkContentType = null;
    for (int i = 0; i < bulkRequest.numberOfActions(); i++) {
        DocWriteRequest<?> request = bulkRequest.requests().get(i);
        DocWriteRequest.OpType opType = request.opType();
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            bulkContentType = enforceSameContentType((IndexRequest) request, bulkContentType);
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            UpdateRequest updateRequest = (UpdateRequest) request;
            if (updateRequest.doc() != null) {
                bulkContentType = enforceSameContentType(updateRequest.doc(), bulkContentType);
            }
            if (updateRequest.upsertRequest() != null) {
                bulkContentType = enforceSameContentType(updateRequest.upsertRequest(), bulkContentType);
            }
        }
    }
    if (bulkContentType == null) {
        bulkContentType = XContentType.JSON;
    }
    byte separator = bulkContentType.xContent().streamSeparator();
    ContentType requestContentType = ContentType.create(bulkContentType.mediaType());
    ByteArrayOutputStream content = new ByteArrayOutputStream();
    for (DocWriteRequest<?> request : bulkRequest.requests()) {
        DocWriteRequest.OpType opType = request.opType();
        try (XContentBuilder metadata = XContentBuilder.builder(bulkContentType.xContent())) {
            metadata.startObject();
            {
                metadata.startObject(opType.getLowercase());
                if (Strings.hasLength(request.index())) {
                    metadata.field("_index", request.index());
                }
                if (Strings.hasLength(request.type())) {
                    metadata.field("_type", request.type());
                }
                if (Strings.hasLength(request.id())) {
                    metadata.field("_id", request.id());
                }
                if (Strings.hasLength(request.routing())) {
                    metadata.field("_routing", request.routing());
                }
                if (Strings.hasLength(request.parent())) {
                    metadata.field("_parent", request.parent());
                }
                if (request.version() != Versions.MATCH_ANY) {
                    metadata.field("_version", request.version());
                }
                VersionType versionType = request.versionType();
                if (versionType != VersionType.INTERNAL) {
                    if (versionType == VersionType.EXTERNAL) {
                        metadata.field("_version_type", "external");
                    } else if (versionType == VersionType.EXTERNAL_GTE) {
                        metadata.field("_version_type", "external_gte");
                    } else if (versionType == VersionType.FORCE) {
                        metadata.field("_version_type", "force");
                    }
                }
                if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
                    IndexRequest indexRequest = (IndexRequest) request;
                    if (Strings.hasLength(indexRequest.getPipeline())) {
                        metadata.field("pipeline", indexRequest.getPipeline());
                    }
                } else if (opType == DocWriteRequest.OpType.UPDATE) {
                    UpdateRequest updateRequest = (UpdateRequest) request;
                    if (updateRequest.retryOnConflict() > 0) {
                        metadata.field("_retry_on_conflict", updateRequest.retryOnConflict());
                    }
                    if (updateRequest.fetchSource() != null) {
                        metadata.field("_source", updateRequest.fetchSource());
                    }
                }
                metadata.endObject();
            }
            metadata.endObject();
            BytesRef metadataSource = metadata.bytes().toBytesRef();
            content.write(metadataSource.bytes, metadataSource.offset, metadataSource.length);
            content.write(separator);
        }
        BytesRef source = null;
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            IndexRequest indexRequest = (IndexRequest) request;
            BytesReference indexSource = indexRequest.source();
            XContentType indexXContentType = indexRequest.getContentType();
            try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, indexSource, indexXContentType)) {
                try (XContentBuilder builder = XContentBuilder.builder(bulkContentType.xContent())) {
                    builder.copyCurrentStructure(parser);
                    source = builder.bytes().toBytesRef();
                }
            }
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            source = XContentHelper.toXContent((UpdateRequest) request, bulkContentType, false).toBytesRef();
        }
        if (source != null) {
            content.write(source.bytes, source.offset, source.length);
            content.write(separator);
        }
    }
    HttpEntity entity = new ByteArrayEntity(content.toByteArray(), 0, content.size(), requestContentType);
    return new Request(HttpPost.METHOD_NAME, "/_bulk", parameters.getParams(), entity);
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) XContentType(org.elasticsearch.common.xcontent.XContentType) ContentType(org.apache.http.entity.ContentType) HttpEntity(org.apache.http.HttpEntity) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) WriteRequest(org.elasticsearch.action.support.WriteRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) GetRequest(org.elasticsearch.action.get.GetRequest) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IndexRequest(org.elasticsearch.action.index.IndexRequest) VersionType(org.elasticsearch.index.VersionType) XContentType(org.elasticsearch.common.xcontent.XContentType) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) BytesRef(org.apache.lucene.util.BytesRef) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 13 with XContentType

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class Request method update.

static Request update(UpdateRequest updateRequest) throws IOException {
    String endpoint = endpoint(updateRequest.index(), updateRequest.type(), updateRequest.id(), "_update");
    Params parameters = Params.builder();
    parameters.withRouting(updateRequest.routing());
    parameters.withParent(updateRequest.parent());
    parameters.withTimeout(updateRequest.timeout());
    parameters.withRefreshPolicy(updateRequest.getRefreshPolicy());
    parameters.withWaitForActiveShards(updateRequest.waitForActiveShards());
    parameters.withDocAsUpsert(updateRequest.docAsUpsert());
    parameters.withFetchSourceContext(updateRequest.fetchSource());
    parameters.withRetryOnConflict(updateRequest.retryOnConflict());
    parameters.withVersion(updateRequest.version());
    parameters.withVersionType(updateRequest.versionType());
    // The Java API allows update requests with different content types
    // set for the partial document and the upsert document. This client
    // only accepts update requests that have the same content types set
    // for both doc and upsert.
    XContentType xContentType = null;
    if (updateRequest.doc() != null) {
        xContentType = updateRequest.doc().getContentType();
    }
    if (updateRequest.upsertRequest() != null) {
        XContentType upsertContentType = updateRequest.upsertRequest().getContentType();
        if ((xContentType != null) && (xContentType != upsertContentType)) {
            throw new IllegalStateException("Update request cannot have different content types for doc [" + xContentType + "]" + " and upsert [" + upsertContentType + "] documents");
        } else {
            xContentType = upsertContentType;
        }
    }
    if (xContentType == null) {
        xContentType = Requests.INDEX_CONTENT_TYPE;
    }
    BytesRef source = XContentHelper.toXContent(updateRequest, xContentType, false).toBytesRef();
    HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, ContentType.create(xContentType.mediaType()));
    return new Request(HttpPost.METHOD_NAME, endpoint, parameters.getParams(), entity);
}
Also used : XContentType(org.elasticsearch.common.xcontent.XContentType) HttpEntity(org.apache.http.HttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) WriteRequest(org.elasticsearch.action.support.WriteRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) GetRequest(org.elasticsearch.action.get.GetRequest) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) BytesRef(org.apache.lucene.util.BytesRef)

Example 14 with XContentType

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class MetaDataStateFormat method read.

/**
     * Reads the state from a given file and compares the expected version against the actual version of
     * the state.
     */
public final T read(NamedXContentRegistry namedXContentRegistry, Path file) throws IOException {
    try (Directory dir = newDirectory(file.getParent())) {
        try (IndexInput indexInput = dir.openInput(file.getFileName().toString(), IOContext.DEFAULT)) {
            // We checksum the entire file before we even go and parse it. If it's corrupted we barf right here.
            CodecUtil.checksumEntireFile(indexInput);
            final int fileVersion = CodecUtil.checkHeader(indexInput, STATE_FILE_CODEC, MIN_COMPATIBLE_STATE_FILE_VERSION, STATE_FILE_VERSION);
            final XContentType xContentType = XContentType.values()[indexInput.readInt()];
            if (fileVersion == STATE_FILE_VERSION_ES_2X_AND_BELOW) {
                // format version 0, wrote a version that always came from the content state file and was never used
                // version currently unused
                indexInput.readLong();
            }
            long filePointer = indexInput.getFilePointer();
            long contentSize = indexInput.length() - CodecUtil.footerLength() - filePointer;
            try (IndexInput slice = indexInput.slice("state_xcontent", filePointer, contentSize)) {
                try (XContentParser parser = XContentFactory.xContent(xContentType).createParser(namedXContentRegistry, new InputStreamIndexInput(slice, contentSize))) {
                    return fromXContent(parser);
                }
            }
        } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
            // we trick this into a dedicated exception with the original stacktrace
            throw new CorruptStateException(ex);
        }
    }
}
Also used : XContentType(org.elasticsearch.common.xcontent.XContentType) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) InputStreamIndexInput(org.elasticsearch.common.lucene.store.InputStreamIndexInput) IndexInput(org.apache.lucene.store.IndexInput) InputStreamIndexInput(org.elasticsearch.common.lucene.store.InputStreamIndexInput) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) XContentParser(org.elasticsearch.common.xcontent.XContentParser) Directory(org.apache.lucene.store.Directory) SimpleFSDirectory(org.apache.lucene.store.SimpleFSDirectory)

Example 15 with XContentType

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class JsonXContentGenerator method writeRawField.

@Override
public void writeRawField(String name, InputStream content) throws IOException {
    if (content.markSupported() == false) {
        // needed for the XContentFactory.xContentType call
        content = new BufferedInputStream(content);
    }
    XContentType contentType = XContentFactory.xContentType(content);
    if (contentType == null) {
        throw new IllegalArgumentException("Can't write raw bytes whose xcontent-type can't be guessed");
    }
    writeRawField(name, content, contentType);
}
Also used : XContentType(org.elasticsearch.common.xcontent.XContentType) BufferedInputStream(java.io.BufferedInputStream)

Aggregations

XContentType (org.elasticsearch.common.xcontent.XContentType)86 BytesReference (org.elasticsearch.common.bytes.BytesReference)50 XContentParser (org.elasticsearch.common.xcontent.XContentParser)45 Map (java.util.Map)20 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)20 HashMap (java.util.HashMap)14 IndexRequest (org.elasticsearch.action.index.IndexRequest)11 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)10 IOException (java.io.IOException)9 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)8 ArrayList (java.util.ArrayList)6 Collections.emptyMap (java.util.Collections.emptyMap)6 List (java.util.List)6 ElasticsearchException (org.elasticsearch.ElasticsearchException)6 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)6 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)6 Collections.singletonMap (java.util.Collections.singletonMap)5 HttpEntity (org.apache.http.HttpEntity)5 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)5 GetRequest (org.elasticsearch.action.get.GetRequest)5