Search in sources :

Example 31 with BytesRestResponse

use of org.opensearch.rest.BytesRestResponse in project OpenSearch by opensearch-project.

the class Netty4BadRequestTests method testBadParameterEncoding.

public void testBadParameterEncoding() throws Exception {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) {
            fail();
        }

        @Override
        public void dispatchBadRequest(RestChannel channel, ThreadContext threadContext, Throwable cause) {
            try {
                final Exception e = cause instanceof Exception ? (Exception) cause : new OpenSearchException(cause);
                channel.sendResponse(new BytesRestResponse(channel, RestStatus.BAD_REQUEST, e));
            } catch (final IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    };
    Settings settings = Settings.builder().put(HttpTransportSettings.SETTING_HTTP_PORT.getKey(), getPortRange()).build();
    try (HttpServerTransport httpServerTransport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), dispatcher, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), new SharedGroupFactory(Settings.EMPTY))) {
        httpServerTransport.start();
        final TransportAddress transportAddress = randomFrom(httpServerTransport.boundAddress().boundAddresses());
        try (Netty4HttpClient nettyHttpClient = new Netty4HttpClient()) {
            final Collection<FullHttpResponse> responses = nettyHttpClient.get(transportAddress.address(), "/_cluster/settings?pretty=%");
            try {
                assertThat(responses, hasSize(1));
                assertThat(responses.iterator().next().status().code(), equalTo(400));
                final Collection<String> responseBodies = Netty4HttpClient.returnHttpResponseBodies(responses);
                assertThat(responseBodies, hasSize(1));
                assertThat(responseBodies.iterator().next(), containsString("\"type\":\"bad_parameter_exception\""));
                assertThat(responseBodies.iterator().next(), containsString("\"reason\":\"java.lang.IllegalArgumentException: unterminated escape sequence at end of string: %\""));
            } finally {
                responses.forEach(ReferenceCounted::release);
            }
        }
    }
}
Also used : ClusterSettings(org.opensearch.common.settings.ClusterSettings) TransportAddress(org.opensearch.common.transport.TransportAddress) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) UncheckedIOException(java.io.UncheckedIOException) SharedGroupFactory(org.opensearch.transport.SharedGroupFactory) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Matchers.containsString(org.hamcrest.Matchers.containsString) HttpServerTransport(org.opensearch.http.HttpServerTransport) OpenSearchException(org.opensearch.OpenSearchException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) RestRequest(org.opensearch.rest.RestRequest) BytesRestResponse(org.opensearch.rest.BytesRestResponse) OpenSearchException(org.opensearch.OpenSearchException) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) HttpTransportSettings(org.opensearch.http.HttpTransportSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings) Settings(org.opensearch.common.settings.Settings) ReferenceCounted(io.netty.util.ReferenceCounted)

Example 32 with BytesRestResponse

use of org.opensearch.rest.BytesRestResponse in project OpenSearch by opensearch-project.

the class RestTable method buildTextPlainResponse.

public static RestResponse buildTextPlainResponse(Table table, RestChannel channel) throws IOException {
    RestRequest request = channel.request();
    boolean verbose = request.paramAsBoolean("v", false);
    List<DisplayHeader> headers = buildDisplayHeaders(table, request);
    int[] width = buildWidths(table, request, verbose, headers);
    BytesStream bytesOut = Streams.flushOnCloseStream(channel.bytesOutput());
    UTF8StreamWriter out = new UTF8StreamWriter().setOutput(bytesOut);
    int lastHeader = headers.size() - 1;
    if (verbose) {
        for (int col = 0; col < headers.size(); col++) {
            DisplayHeader header = headers.get(col);
            boolean isLastColumn = col == lastHeader;
            pad(new Table.Cell(header.display, table.findHeaderByName(header.name)), width[col], request, out, isLastColumn);
            if (!isLastColumn) {
                out.append(" ");
            }
        }
        out.append("\n");
    }
    List<Integer> rowOrder = getRowOrder(table, request);
    for (Integer row : rowOrder) {
        for (int col = 0; col < headers.size(); col++) {
            DisplayHeader header = headers.get(col);
            boolean isLastColumn = col == lastHeader;
            pad(table.getAsMap().get(header.name).get(row), width[col], request, out, isLastColumn);
            if (!isLastColumn) {
                out.append(" ");
            }
        }
        out.append("\n");
    }
    out.close();
    return new BytesRestResponse(RestStatus.OK, BytesRestResponse.TEXT_CONTENT_TYPE, bytesOut.bytes());
}
Also used : Table(org.opensearch.common.Table) BytesStream(org.opensearch.common.io.stream.BytesStream) RestRequest(org.opensearch.rest.RestRequest) UTF8StreamWriter(org.opensearch.common.io.UTF8StreamWriter) BytesRestResponse(org.opensearch.rest.BytesRestResponse)

Example 33 with BytesRestResponse

use of org.opensearch.rest.BytesRestResponse in project OpenSearch by opensearch-project.

the class RestGetFieldMappingAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final String[] fields = Strings.splitStringByCommaToArray(request.param("fields"));
    GetFieldMappingsRequest getMappingsRequest = new GetFieldMappingsRequest();
    getMappingsRequest.indices(indices).fields(fields).includeDefaults(request.paramAsBoolean("include_defaults", false));
    getMappingsRequest.indicesOptions(IndicesOptions.fromRequest(request, getMappingsRequest.indicesOptions()));
    if (request.hasParam("local")) {
        deprecationLogger.deprecate("get_field_mapping_local", "Use [local] in get field mapping requests is deprecated. " + "The parameter will be removed in the next major version");
    }
    getMappingsRequest.local(request.paramAsBoolean("local", getMappingsRequest.local()));
    return channel -> client.admin().indices().getFieldMappings(getMappingsRequest, new RestBuilderListener<GetFieldMappingsResponse>(channel) {

        @Override
        public RestResponse buildResponse(GetFieldMappingsResponse response, XContentBuilder builder) throws Exception {
            Map<String, Map<String, FieldMappingMetadata>> mappingsByIndex = response.mappings();
            RestStatus status = OK;
            if (mappingsByIndex.isEmpty() && fields.length > 0) {
                status = NOT_FOUND;
            }
            response.toXContent(builder, request);
            return new BytesRestResponse(status, builder);
        }
    });
}
Also used : OK(org.opensearch.rest.RestStatus.OK) NodeClient(org.opensearch.client.node.NodeClient) Collections.unmodifiableList(java.util.Collections.unmodifiableList) GET(org.opensearch.rest.RestRequest.Method.GET) RestRequest(org.opensearch.rest.RestRequest) GetFieldMappingsRequest(org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest) IOException(java.io.IOException) FieldMappingMetadata(org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetadata) IndicesOptions(org.opensearch.action.support.IndicesOptions) RestStatus(org.opensearch.rest.RestStatus) BytesRestResponse(org.opensearch.rest.BytesRestResponse) RestResponse(org.opensearch.rest.RestResponse) Strings(org.opensearch.common.Strings) DeprecationLogger(org.opensearch.common.logging.DeprecationLogger) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) NOT_FOUND(org.opensearch.rest.RestStatus.NOT_FOUND) RestBuilderListener(org.opensearch.rest.action.RestBuilderListener) List(java.util.List) Logger(org.apache.logging.log4j.Logger) GetFieldMappingsResponse(org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) BaseRestHandler(org.opensearch.rest.BaseRestHandler) LogManager(org.apache.logging.log4j.LogManager) BytesRestResponse(org.opensearch.rest.BytesRestResponse) RestResponse(org.opensearch.rest.RestResponse) GetFieldMappingsRequest(org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest) GetFieldMappingsResponse(org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse) IOException(java.io.IOException) RestStatus(org.opensearch.rest.RestStatus) FieldMappingMetadata(org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetadata) BytesRestResponse(org.opensearch.rest.BytesRestResponse) Map(java.util.Map) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder)

Example 34 with BytesRestResponse

use of org.opensearch.rest.BytesRestResponse in project OpenSearch by opensearch-project.

the class RestGetSourceAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final GetRequest getRequest = new GetRequest(request.param("index"), request.param("id"));
    getRequest.refresh(request.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.routing(request.param("routing"));
    getRequest.preference(request.param("preference"));
    getRequest.realtime(request.paramAsBoolean("realtime", getRequest.realtime()));
    getRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));
    return channel -> {
        if (getRequest.fetchSourceContext() != null && !getRequest.fetchSourceContext().fetchSource()) {
            final ActionRequestValidationException validationError = new ActionRequestValidationException();
            validationError.addValidationError("fetching source can not be disabled");
            channel.sendResponse(new BytesRestResponse(channel, validationError));
        } else {
            client.get(getRequest, new RestGetSourceResponseListener(channel, request));
        }
    };
}
Also used : OK(org.opensearch.rest.RestStatus.OK) NodeClient(org.opensearch.client.node.NodeClient) BytesReference(org.opensearch.common.bytes.BytesReference) Collections.unmodifiableList(java.util.Collections.unmodifiableList) GET(org.opensearch.rest.RestRequest.Method.GET) RestRequest(org.opensearch.rest.RestRequest) GetRequest(org.opensearch.action.get.GetRequest) IOException(java.io.IOException) ResourceNotFoundException(org.opensearch.ResourceNotFoundException) BytesRestResponse(org.opensearch.rest.BytesRestResponse) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) RestResponse(org.opensearch.rest.RestResponse) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) List(java.util.List) RestChannel(org.opensearch.rest.RestChannel) Arrays.asList(java.util.Arrays.asList) BaseRestHandler(org.opensearch.rest.BaseRestHandler) HEAD(org.opensearch.rest.RestRequest.Method.HEAD) GetResponse(org.opensearch.action.get.GetResponse) RestResponseListener(org.opensearch.rest.action.RestResponseListener) FetchSourceContext(org.opensearch.search.fetch.subphase.FetchSourceContext) InputStream(java.io.InputStream) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) GetRequest(org.opensearch.action.get.GetRequest) BytesRestResponse(org.opensearch.rest.BytesRestResponse)

Example 35 with BytesRestResponse

use of org.opensearch.rest.BytesRestResponse in project OpenSearch by opensearch-project.

the class ExampleCatAction method doCatRequest.

@Override
protected RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) {
    final String message = request.param("message", "Hello from Cat Example action");
    Table table = getTableWithHeader(request);
    table.startRow();
    table.addCell(message);
    table.endRow();
    return channel -> {
        try {
            channel.sendResponse(RestTable.buildResponse(table, channel));
        } catch (final Exception e) {
            channel.sendResponse(new BytesRestResponse(channel, e));
        }
    };
}
Also used : POST(org.opensearch.rest.RestRequest.Method.POST) RestTable(org.opensearch.rest.action.cat.RestTable) List(java.util.List) NodeClient(org.opensearch.client.node.NodeClient) Collections.unmodifiableList(java.util.Collections.unmodifiableList) GET(org.opensearch.rest.RestRequest.Method.GET) RestRequest(org.opensearch.rest.RestRequest) Arrays.asList(java.util.Arrays.asList) AbstractCatAction(org.opensearch.rest.action.cat.AbstractCatAction) Table(org.opensearch.common.Table) BytesRestResponse(org.opensearch.rest.BytesRestResponse) RestTable(org.opensearch.rest.action.cat.RestTable) Table(org.opensearch.common.Table) BytesRestResponse(org.opensearch.rest.BytesRestResponse)

Aggregations

BytesRestResponse (org.opensearch.rest.BytesRestResponse)67 RestRequest (org.opensearch.rest.RestRequest)39 IOException (java.io.IOException)35 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)35 List (java.util.List)21 NodeClient (org.opensearch.client.node.NodeClient)20 RestStatus (org.opensearch.rest.RestStatus)20 BaseRestHandler (org.opensearch.rest.BaseRestHandler)19 RestChannel (org.opensearch.rest.RestChannel)19 FakeRestRequest (org.opensearch.test.rest.FakeRestRequest)17 RestResponse (org.opensearch.rest.RestResponse)15 GET (org.opensearch.rest.RestRequest.Method.GET)13 Arrays.asList (java.util.Arrays.asList)12 Collections.unmodifiableList (java.util.Collections.unmodifiableList)12 TransportAddress (org.opensearch.common.transport.TransportAddress)11 BytesReference (org.opensearch.common.bytes.BytesReference)10 Settings (org.opensearch.common.settings.Settings)10 RestBuilderListener (org.opensearch.rest.action.RestBuilderListener)10 User (org.opensearch.security.user.User)10 ThreadContext (org.opensearch.common.util.concurrent.ThreadContext)9