Search in sources :

Example 6 with XContent

use of org.opensearch.common.xcontent.XContent in project OpenSearch by opensearch-project.

the class OpenSearchExceptionTests method testFromXContentWithHeadersAndMetadata.

public void testFromXContentWithHeadersAndMetadata() throws IOException {
    RoutingMissingException routing = new RoutingMissingException("_test", "_id");
    OpenSearchException baz = new OpenSearchException("baz", routing);
    baz.addHeader("baz_0", "baz0");
    baz.addMetadata("opensearch.baz_1", "baz1");
    baz.addHeader("baz_2", "baz2");
    baz.addMetadata("opensearch.baz_3", "baz3");
    OpenSearchException bar = new OpenSearchException("bar", baz);
    bar.addMetadata("opensearch.bar_0", "bar0");
    bar.addHeader("bar_1", "bar1");
    bar.addMetadata("opensearch.bar_2", "bar2");
    OpenSearchException foo = new OpenSearchException("foo", bar);
    foo.addMetadata("opensearch.foo_0", "foo0");
    foo.addHeader("foo_1", "foo1");
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    XContentBuilder builder = XContentBuilder.builder(xContent).startObject().value(foo).endObject();
    builder = shuffleXContent(builder);
    OpenSearchException parsed;
    try (XContentParser parser = createParser(builder)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = OpenSearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertNotNull(parsed);
    assertEquals(parsed.getMessage(), "OpenSearch exception [type=exception, reason=foo]");
    assertThat(parsed.getHeaderKeys(), hasSize(1));
    assertThat(parsed.getHeader("foo_1"), hasItem("foo1"));
    assertThat(parsed.getMetadataKeys(), hasSize(1));
    assertThat(parsed.getMetadata("opensearch.foo_0"), hasItem("foo0"));
    OpenSearchException cause = (OpenSearchException) parsed.getCause();
    assertEquals(cause.getMessage(), "OpenSearch exception [type=exception, reason=bar]");
    assertThat(cause.getHeaderKeys(), hasSize(1));
    assertThat(cause.getHeader("bar_1"), hasItem("bar1"));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("opensearch.bar_0"), hasItem("bar0"));
    assertThat(cause.getMetadata("opensearch.bar_2"), hasItem("bar2"));
    cause = (OpenSearchException) cause.getCause();
    assertEquals(cause.getMessage(), "OpenSearch exception [type=exception, reason=baz]");
    assertThat(cause.getHeaderKeys(), hasSize(2));
    assertThat(cause.getHeader("baz_0"), hasItem("baz0"));
    assertThat(cause.getHeader("baz_2"), hasItem("baz2"));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("opensearch.baz_1"), hasItem("baz1"));
    assertThat(cause.getMetadata("opensearch.baz_3"), hasItem("baz3"));
    cause = (OpenSearchException) cause.getCause();
    assertEquals(cause.getMessage(), "OpenSearch exception [type=routing_missing_exception, reason=routing is required for [_test]/[_id]]");
    assertThat(cause.getHeaderKeys(), hasSize(0));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("opensearch.index"), hasItem("_test"));
    assertThat(cause.getMetadata("opensearch.index_uuid"), hasItem("_na_"));
}
Also used : ToXContent(org.opensearch.common.xcontent.ToXContent) XContent(org.opensearch.common.xcontent.XContent) RoutingMissingException(org.opensearch.action.RoutingMissingException) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 7 with XContent

use of org.opensearch.common.xcontent.XContent in project OpenSearch by opensearch-project.

the class OpenSearchExceptionTests method testThrowableToAndFromXContent.

public void testThrowableToAndFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    final Tuple<Throwable, OpenSearchException> exceptions = randomExceptions();
    final Throwable throwable = exceptions.v1();
    final OpenSearchException expected = exceptions.v2();
    int suppressedCount = randomBoolean() ? 0 : between(1, 5);
    for (int i = 0; i < suppressedCount; i++) {
        final Tuple<Throwable, OpenSearchException> suppressed = randomExceptions();
        throwable.addSuppressed(suppressed.v1());
        expected.addSuppressed(suppressed.v2());
    }
    BytesReference throwableBytes = toShuffledXContent((builder, params) -> {
        OpenSearchException.generateThrowableXContent(builder, params, throwable);
        return builder;
    }, xContent.type(), ToXContent.EMPTY_PARAMS, randomBoolean());
    OpenSearchException parsedException;
    try (XContentParser parser = createParser(xContent, throwableBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsedException = OpenSearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertDeepEquals(expected, parsedException);
    if (suppressedCount > 0) {
        XContentBuilder builder = XContentBuilder.builder(xContent);
        builder.startObject();
        OpenSearchException.generateThrowableXContent(builder, ToXContent.EMPTY_PARAMS, throwable);
        builder.endObject();
        throwableBytes = BytesReference.bytes(builder);
        try (XContentParser parser = createParser(xContent, throwableBytes)) {
            assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
            List<String> keys = new ArrayList<>(parser.mapOrdered().keySet());
            assertEquals("last index should be [suppressed]", "suppressed", keys.get(keys.size() - 1));
        }
    }
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) ToXContent(org.opensearch.common.xcontent.ToXContent) XContent(org.opensearch.common.xcontent.XContent) ArrayList(java.util.ArrayList) XContentParser(org.opensearch.common.xcontent.XContentParser) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder)

Example 8 with XContent

use of org.opensearch.common.xcontent.XContent in project OpenSearch by opensearch-project.

the class OpenSearchExceptionTests method testFromXContent.

public void testFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    XContentBuilder builder = XContentBuilder.builder(xContent).startObject().field("type", "foo").field("reason", "something went wrong").field("stack_trace", "...").endObject();
    builder = shuffleXContent(builder);
    OpenSearchException parsed;
    try (XContentParser parser = createParser(xContent, BytesReference.bytes(builder))) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = OpenSearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertNotNull(parsed);
    assertEquals(parsed.getMessage(), "OpenSearch exception [type=foo, reason=something went wrong, stack_trace=...]");
}
Also used : ToXContent(org.opensearch.common.xcontent.ToXContent) XContent(org.opensearch.common.xcontent.XContent) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 9 with XContent

use of org.opensearch.common.xcontent.XContent in project OpenSearch by opensearch-project.

the class OpenSearchExceptionTests method testFailureToAndFromXContentWithDetails.

public void testFailureToAndFromXContentWithDetails() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    Exception failure;
    Throwable failureCause;
    OpenSearchException expected;
    OpenSearchException expectedCause;
    OpenSearchException suppressed;
    switch(randomIntBetween(0, 6)) {
        case // Simple opensearch exception without cause
        0:
            failure = new NoNodeAvailableException("A");
            expected = new OpenSearchException("OpenSearch exception [type=no_node_available_exception, reason=A]");
            expected.addSuppressed(new OpenSearchException("OpenSearch exception [type=no_node_available_exception, reason=A]"));
            break;
        case // Simple opensearch exception with headers (other metadata of type number are not parsed)
        1:
            failure = new ParsingException(3, 2, "B", null);
            ((OpenSearchException) failure).addHeader("header_name", "0", "1");
            expected = new OpenSearchException("OpenSearch exception [type=parsing_exception, reason=B]");
            expected.addHeader("header_name", "0", "1");
            suppressed = new OpenSearchException("OpenSearch exception [type=parsing_exception, reason=B]");
            suppressed.addHeader("header_name", "0", "1");
            expected.addSuppressed(suppressed);
            break;
        case // OpenSearch exception with a cause, headers and parsable metadata
        2:
            failureCause = new NullPointerException("var is null");
            failure = new ScriptException("C", failureCause, singletonList("stack"), "test", "painless");
            ((OpenSearchException) failure).addHeader("script_name", "my_script");
            expectedCause = new OpenSearchException("OpenSearch exception [type=null_pointer_exception, reason=var is null]");
            expected = new OpenSearchException("OpenSearch exception [type=script_exception, reason=C]", expectedCause);
            expected.addHeader("script_name", "my_script");
            expected.addMetadata("opensearch.lang", "painless");
            expected.addMetadata("opensearch.script", "test");
            expected.addMetadata("opensearch.script_stack", "stack");
            suppressed = new OpenSearchException("OpenSearch exception [type=script_exception, reason=C]");
            suppressed.addHeader("script_name", "my_script");
            suppressed.addMetadata("opensearch.lang", "painless");
            suppressed.addMetadata("opensearch.script", "test");
            suppressed.addMetadata("opensearch.script_stack", "stack");
            expected.addSuppressed(suppressed);
            break;
        case // JDK exception without cause
        3:
            failure = new IllegalStateException("D");
            expected = new OpenSearchException("OpenSearch exception [type=illegal_state_exception, reason=D]");
            suppressed = new OpenSearchException("OpenSearch exception [type=illegal_state_exception, reason=D]");
            expected.addSuppressed(suppressed);
            break;
        case // JDK exception with cause
        4:
            failureCause = new RoutingMissingException("idx", "id");
            failure = new RuntimeException("E", failureCause);
            expectedCause = new OpenSearchException("OpenSearch exception [type=routing_missing_exception, " + "reason=routing is required for [idx]/[id]]");
            expectedCause.addMetadata("opensearch.index", "idx");
            expectedCause.addMetadata("opensearch.index_uuid", "_na_");
            expected = new OpenSearchException("OpenSearch exception [type=runtime_exception, reason=E]", expectedCause);
            suppressed = new OpenSearchException("OpenSearch exception [type=runtime_exception, reason=E]");
            expected.addSuppressed(suppressed);
            break;
        case // Wrapped exception with cause
        5:
            failureCause = new FileAlreadyExistsException("File exists");
            failure = new BroadcastShardOperationFailedException(new ShardId("_index", "_uuid", 5), "F", failureCause);
            expected = new OpenSearchException("OpenSearch exception [type=file_already_exists_exception, reason=File exists]");
            suppressed = new OpenSearchException("OpenSearch exception [type=file_already_exists_exception, reason=File exists]");
            expected.addSuppressed(suppressed);
            break;
        case // SearchPhaseExecutionException with cause and multiple failures
        6:
            DiscoveryNode node = new DiscoveryNode("node_g", buildNewFakeTransportAddress(), Version.CURRENT);
            failureCause = new NodeClosedException(node);
            failureCause = new NoShardAvailableActionException(new ShardId("_index_g", "_uuid_g", 6), "node_g", failureCause);
            ShardSearchFailure[] shardFailures = new ShardSearchFailure[] { new ShardSearchFailure(new ParsingException(0, 0, "Parsing g", null), new SearchShardTarget("node_g", new ShardId(new Index("_index_g", "_uuid_g"), 61), null, OriginalIndices.NONE)), new ShardSearchFailure(new RepositoryException("repository_g", "Repo"), new SearchShardTarget("node_g", new ShardId(new Index("_index_g", "_uuid_g"), 62), null, OriginalIndices.NONE)), new ShardSearchFailure(new SearchContextMissingException(new ShardSearchContextId(UUIDs.randomBase64UUID(), 0L)), null) };
            failure = new SearchPhaseExecutionException("phase_g", "G", failureCause, shardFailures);
            expectedCause = new OpenSearchException("OpenSearch exception [type=node_closed_exception, " + "reason=node closed " + node + "]");
            expectedCause = new OpenSearchException("OpenSearch exception [type=no_shard_available_action_exception, " + "reason=node_g]", expectedCause);
            expectedCause.addMetadata("opensearch.index", "_index_g");
            expectedCause.addMetadata("opensearch.index_uuid", "_uuid_g");
            expectedCause.addMetadata("opensearch.shard", "6");
            expected = new OpenSearchException("OpenSearch exception [type=search_phase_execution_exception, " + "reason=G]", expectedCause);
            expected.addMetadata("opensearch.phase", "phase_g");
            expected.addSuppressed(new OpenSearchException("OpenSearch exception [type=parsing_exception, reason=Parsing g]"));
            expected.addSuppressed(new OpenSearchException("OpenSearch exception [type=repository_exception, " + "reason=[repository_g] Repo]"));
            expected.addSuppressed(new OpenSearchException("OpenSearch exception [type=search_context_missing_exception, " + "reason=No search context found for id [0]]"));
            break;
        default:
            throw new UnsupportedOperationException("Failed to generate randomized failure");
    }
    Exception finalFailure = failure;
    BytesReference failureBytes = toShuffledXContent((builder, params) -> {
        OpenSearchException.generateFailureXContent(builder, params, finalFailure, true);
        return builder;
    }, xContent.type(), ToXContent.EMPTY_PARAMS, randomBoolean());
    try (XContentParser parser = createParser(xContent, failureBytes)) {
        failureBytes = BytesReference.bytes(shuffleXContent(parser, randomBoolean()));
    }
    OpenSearchException parsedFailure;
    try (XContentParser parser = createParser(xContent, failureBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
        parsedFailure = OpenSearchException.failureFromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
        assertNull(parser.nextToken());
    }
    assertDeepEquals(expected, parsedFailure);
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) SearchPhaseExecutionException(org.opensearch.action.search.SearchPhaseExecutionException) Index(org.opensearch.index.Index) ShardId(org.opensearch.index.shard.ShardId) ScriptException(org.opensearch.script.ScriptException) ToXContent(org.opensearch.common.xcontent.ToXContent) XContent(org.opensearch.common.xcontent.XContent) ParsingException(org.opensearch.common.ParsingException) NodeClosedException(org.opensearch.node.NodeClosedException) BroadcastShardOperationFailedException(org.opensearch.action.support.broadcast.BroadcastShardOperationFailedException) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) RoutingMissingException(org.opensearch.action.RoutingMissingException) BytesReference(org.opensearch.common.bytes.BytesReference) SearchContextMissingException(org.opensearch.search.SearchContextMissingException) RepositoryException(org.opensearch.repositories.RepositoryException) NoNodeAvailableException(org.opensearch.client.transport.NoNodeAvailableException) IndexShardRecoveringException(org.opensearch.index.shard.IndexShardRecoveringException) NoNodeAvailableException(org.opensearch.client.transport.NoNodeAvailableException) ScriptException(org.opensearch.script.ScriptException) NodeClosedException(org.opensearch.node.NodeClosedException) BroadcastShardOperationFailedException(org.opensearch.action.support.broadcast.BroadcastShardOperationFailedException) ParsingException(org.opensearch.common.ParsingException) RepositoryException(org.opensearch.repositories.RepositoryException) RemoteTransportException(org.opensearch.transport.RemoteTransportException) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) QueryShardException(org.opensearch.index.query.QueryShardException) SearchParseException(org.opensearch.search.SearchParseException) SearchContextMissingException(org.opensearch.search.SearchContextMissingException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) RoutingMissingException(org.opensearch.action.RoutingMissingException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) SearchPhaseExecutionException(org.opensearch.action.search.SearchPhaseExecutionException) XContentParseException(org.opensearch.common.xcontent.XContentParseException) NoShardAvailableActionException(org.opensearch.action.NoShardAvailableActionException) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) NoShardAvailableActionException(org.opensearch.action.NoShardAvailableActionException) SearchShardTarget(org.opensearch.search.SearchShardTarget) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 10 with XContent

use of org.opensearch.common.xcontent.XContent in project OpenSearch by opensearch-project.

the class OpenSearchExceptionTests method testFromXContentWithIgnoredMetadataAndHeaders.

/**
 * Test that some values like arrays of numbers are ignored when parsing back
 * an exception.
 */
public void testFromXContentWithIgnoredMetadataAndHeaders() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    // The exception content to parse is built using a XContentBuilder
    // because the current Java API does not allow to add metadata/headers
    // of other types than list of strings.
    BytesReference originalBytes;
    try (XContentBuilder builder = XContentBuilder.builder(xContent)) {
        builder.startObject().field("metadata_int", 1).array("metadata_array_of_ints", new int[] { 8, 13, 21 }).field("reason", "Custom reason").array("metadata_array_of_boolean", new boolean[] { false, false }).startArray("metadata_array_of_objects").startObject().field("object_array_one", "value_one").endObject().startObject().field("object_array_two", "value_two").endObject().endArray().field("type", "custom_exception").field("metadata_long", 1L).array("metadata_array_of_longs", new long[] { 2L, 3L, 5L }).field("metadata_other", "some metadata").startObject("header").field("header_string", "some header").array("header_array_of_strings", new String[] { "foo", "bar", "baz" }).endObject().startObject("metadata_object").field("object_field", "value").endObject().endObject();
        try (XContentBuilder shuffledBuilder = shuffleXContent(builder)) {
            originalBytes = BytesReference.bytes(shuffledBuilder);
        }
    }
    OpenSearchException parsedException;
    try (XContentParser parser = createParser(xContent, originalBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsedException = OpenSearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertNotNull(parsedException);
    assertEquals("OpenSearch exception [type=custom_exception, reason=Custom reason]", parsedException.getMessage());
    assertEquals(2, parsedException.getHeaderKeys().size());
    assertThat(parsedException.getHeader("header_string"), hasItem("some header"));
    assertThat(parsedException.getHeader("header_array_of_strings"), hasItems("foo", "bar", "baz"));
    assertEquals(1, parsedException.getMetadataKeys().size());
    assertThat(parsedException.getMetadata("opensearch.metadata_other"), hasItem("some metadata"));
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) ToXContent(org.opensearch.common.xcontent.ToXContent) XContent(org.opensearch.common.xcontent.XContent) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentParser(org.opensearch.common.xcontent.XContentParser)

Aggregations

XContent (org.opensearch.common.xcontent.XContent)24 XContentParser (org.opensearch.common.xcontent.XContentParser)19 ToXContent (org.opensearch.common.xcontent.ToXContent)16 BytesReference (org.opensearch.common.bytes.BytesReference)12 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)10 IOException (java.io.IOException)7 XContentType (org.opensearch.common.xcontent.XContentType)5 RoutingMissingException (org.opensearch.action.RoutingMissingException)4 ParsingException (org.opensearch.common.ParsingException)4 DeleteRequest (org.opensearch.action.delete.DeleteRequest)3 IndexRequest (org.opensearch.action.index.IndexRequest)3 UpdateRequest (org.opensearch.action.update.UpdateRequest)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Set (java.util.Set)2 NByteArrayEntity (org.apache.http.nio.entity.NByteArrayEntity)2 DocWriteRequest (org.opensearch.action.DocWriteRequest)2 ClusterHealthRequest (org.opensearch.action.admin.cluster.health.ClusterHealthRequest)2 DeleteStoredScriptRequest (org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest)2 GetStoredScriptRequest (org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest)2