Search in sources :

Example 1 with RequestLine

use of org.apache.http.RequestLine in project elasticsearch by elastic.

the class RestHighLevelClientTests method testPerformRequestOnSuccess.

public void testPerformRequestOnSuccess() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenReturn(mockResponse);
    {
        Integer result = restHighLevelClient.performRequest(mainRequest, requestConverter, response -> response.getStatusLine().getStatusCode(), Collections.emptySet());
        assertEquals(restStatus.getStatus(), result.intValue());
    }
    {
        IOException ioe = expectThrows(IOException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> {
            throw new IllegalStateException();
        }, Collections.emptySet()));
        assertEquals("Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " + "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage());
    }
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Header(org.apache.http.Header) StatusLine(org.apache.http.StatusLine) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) ArgumentMatcher(org.mockito.ArgumentMatcher) RequestLine(org.apache.http.RequestLine) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Matchers.eq(org.mockito.Matchers.eq) ClusterName(org.elasticsearch.cluster.ClusterName) JsonParseException(com.fasterxml.jackson.core.JsonParseException) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Matchers.anyVararg(org.mockito.Matchers.anyVararg) ActionRequest(org.elasticsearch.action.ActionRequest) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) StringEntity(org.apache.http.entity.StringEntity) XContentHelper.toXContent(org.elasticsearch.common.xcontent.XContentHelper.toXContent) MainResponse(org.elasticsearch.action.main.MainResponse) CheckedFunction(org.elasticsearch.common.CheckedFunction) List(java.util.List) Version(org.elasticsearch.Version) ArrayEquals(org.mockito.internal.matchers.ArrayEquals) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException) Matchers.argThat(org.mockito.Matchers.argThat) RestStatus(org.elasticsearch.rest.RestStatus) Mockito.mock(org.mockito.Mockito.mock) XContentType(org.elasticsearch.common.xcontent.XContentType) BasicStatusLine(org.apache.http.message.BasicStatusLine) Matchers(org.mockito.Matchers) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.anyString(org.mockito.Matchers.anyString) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) Matchers.anyMapOf(org.mockito.Matchers.anyMapOf) SocketTimeoutException(java.net.SocketTimeoutException) Matchers.anyObject(org.mockito.Matchers.anyObject) ESTestCase(org.elasticsearch.test.ESTestCase) MainRequest(org.elasticsearch.action.main.MainRequest) Before(org.junit.Before) CborXContent(org.elasticsearch.common.xcontent.cbor.CborXContent) BasicRequestLine(org.apache.http.message.BasicRequestLine) SmileXContent(org.elasticsearch.common.xcontent.smile.SmileXContent) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) XContentParser(org.elasticsearch.common.xcontent.XContentParser) ProtocolVersion(org.apache.http.ProtocolVersion) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Build(org.elasticsearch.Build) VarargMatcher(org.mockito.internal.matchers.VarargMatcher) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) MainRequest(org.elasticsearch.action.main.MainRequest) ActionRequest(org.elasticsearch.action.ActionRequest) MainRequest(org.elasticsearch.action.main.MainRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) Matchers.anyString(org.mockito.Matchers.anyString) MainResponse(org.elasticsearch.action.main.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) RestStatus(org.elasticsearch.rest.RestStatus) HttpHost(org.apache.http.HttpHost)

Example 2 with RequestLine

use of org.apache.http.RequestLine in project elasticsearch by elastic.

the class SyncResponseListenerTests method mockResponse.

private static Response mockResponse() {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);
    return new Response(requestLine, new HttpHost("localhost", 9200), httpResponse);
}
Also used : BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) BasicRequestLine(org.apache.http.message.BasicRequestLine) RequestLine(org.apache.http.RequestLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) BasicRequestLine(org.apache.http.message.BasicRequestLine) HttpHost(org.apache.http.HttpHost) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine)

Example 3 with RequestLine

use of org.apache.http.RequestLine in project elasticsearch by elastic.

the class ResponseExceptionTests method testResponseException.

public void testResponseException() throws IOException {
    ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 500, "Internal Server Error");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);
    String responseBody = "{\"error\":{\"root_cause\": {}}}";
    boolean hasBody = getRandom().nextBoolean();
    if (hasBody) {
        HttpEntity entity;
        if (getRandom().nextBoolean()) {
            entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON);
        } else {
            //test a non repeatable entity
            entity = new InputStreamEntity(new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), ContentType.APPLICATION_JSON);
        }
        httpResponse.setEntity(entity);
    }
    RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion);
    HttpHost httpHost = new HttpHost("localhost", 9200);
    Response response = new Response(requestLine, httpHost, httpResponse);
    ResponseException responseException = new ResponseException(response);
    assertSame(response, responseException.getResponse());
    if (hasBody) {
        assertEquals(responseBody, EntityUtils.toString(responseException.getResponse().getEntity()));
    } else {
        assertNull(responseException.getResponse().getEntity());
    }
    String message = response.getRequestLine().getMethod() + " " + response.getHost() + response.getRequestLine().getUri() + ": " + response.getStatusLine().toString();
    if (hasBody) {
        message += "\n" + responseBody;
    }
    assertEquals(message, responseException.getMessage());
}
Also used : HttpEntity(org.apache.http.HttpEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine) InputStreamEntity(org.apache.http.entity.InputStreamEntity) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) StringEntity(org.apache.http.entity.StringEntity) BasicRequestLine(org.apache.http.message.BasicRequestLine) RequestLine(org.apache.http.RequestLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) BasicRequestLine(org.apache.http.message.BasicRequestLine) HttpHost(org.apache.http.HttpHost)

Example 4 with RequestLine

use of org.apache.http.RequestLine in project robovm by robovm.

the class HttpRequestParser method parseHead.

protected HttpMessage parseHead(final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException {
    this.lineBuf.clear();
    int i = sessionBuffer.readLine(this.lineBuf);
    if (i == -1) {
        throw new ConnectionClosedException("Client closed connection");
    }
    ParserCursor cursor = new ParserCursor(0, this.lineBuf.length());
    RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor);
    return this.requestFactory.newHttpRequest(requestline);
}
Also used : ParserCursor(org.apache.http.message.ParserCursor) RequestLine(org.apache.http.RequestLine) ConnectionClosedException(org.apache.http.ConnectionClosedException)

Example 5 with RequestLine

use of org.apache.http.RequestLine in project indy by Commonjava.

the class ProxyResponseWriter method handleEvent.

@Override
public void handleEvent(final ConduitStreamSinkChannel channel) {
    HttpConduitWrapper http = new HttpConduitWrapper(channel, httpRequest, contentController, cacheProvider);
    if (httpRequest == null) {
        if (error != null) {
            logger.debug("handling error from request reader: " + error.getMessage(), error);
            handleError(error, http);
        } else {
            logger.debug("invalid state (no error or request) from request reader. Sending 400.");
            try {
                http.writeStatus(ApplicationStatus.BAD_REQUEST);
            } catch (final IOException e) {
                logger.error("Failed to write BAD REQUEST for missing HTTP first-line to response channel.", e);
            }
        }
        return;
    }
    // TODO: Can we handle this?
    final String oldThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName("PROXY-" + httpRequest.getRequestLine().toString());
    channel.getCloseSetter().set((sinkChannel) -> {
        logger.debug("sink channel closing.");
        Thread.currentThread().setName(oldThreadName);
    });
    logger.info("\n\n\n>>>>>>> Handle write\n\n\n\n\n");
    if (error == null) {
        try {
            final UserPass proxyUserPass = UserPass.parse(ApplicationHeader.proxy_authorization, httpRequest, null);
            logger.debug("Proxy UserPass: {}\nConfig secured? {}\nConfig tracking type: {}", proxyUserPass, config.isSecured(), config.getTrackingType());
            if (proxyUserPass == null && (config.isSecured() || TrackingType.ALWAYS == config.getTrackingType())) {
                http.writeStatus(ApplicationStatus.PROXY_AUTHENTICATION_REQUIRED);
                http.writeHeader(ApplicationHeader.proxy_authenticate, String.format(PROXY_AUTHENTICATE_FORMAT, config.getProxyRealm()));
            } else {
                RequestLine requestLine = httpRequest.getRequestLine();
                String method = requestLine.getMethod().toUpperCase();
                switch(method) {
                    case GET_METHOD:
                    case HEAD_METHOD:
                        {
                            if (proxyUserPass != null) {
                                logger.debug("Passing BASIC authentication credentials to Keycloak bearer-token translation authenticator");
                                if (!proxyAuthenticator.authenticate(proxyUserPass, http)) {
                                    break;
                                }
                            }
                            final URL url = new URL(requestLine.getUri());
                            final RemoteRepository repo = getRepository(url);
                            transfer(http, repo, url.getPath(), GET_METHOD.equals(method), proxyUserPass);
                            break;
                        }
                    case OPTIONS_METHOD:
                        {
                            http.writeStatus(ApplicationStatus.OK);
                            http.writeHeader(ApplicationHeader.allow, ALLOW_HEADER_VALUE);
                            break;
                        }
                    default:
                        {
                            http.writeStatus(ApplicationStatus.METHOD_NOT_ALLOWED);
                        }
                }
            }
            logger.info("Response complete.");
        } catch (final Throwable e) {
            error = e;
        }
    }
    if (error != null) {
        handleError(error, http);
    }
    try {
        http.close();
    } catch (final IOException e) {
        logger.error("Failed to flush/shutdown response.", e);
    }
}
Also used : RequestLine(org.apache.http.RequestLine) HttpConduitWrapper(org.commonjava.indy.httprox.util.HttpConduitWrapper) UserPass(org.commonjava.indy.subsys.http.util.UserPass) RemoteRepository(org.commonjava.indy.model.core.RemoteRepository) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

RequestLine (org.apache.http.RequestLine)27 IOException (java.io.IOException)9 HttpHost (org.apache.http.HttpHost)9 HttpEntity (org.apache.http.HttpEntity)7 ProtocolVersion (org.apache.http.ProtocolVersion)7 StatusLine (org.apache.http.StatusLine)6 BasicRequestLine (org.apache.http.message.BasicRequestLine)6 HttpRequest (org.apache.http.HttpRequest)5 HttpException (org.apache.http.HttpException)4 HttpResponse (org.apache.http.HttpResponse)4 ConnectionClosedException (org.apache.http.ConnectionClosedException)3 Header (org.apache.http.Header)3 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)3 StringEntity (org.apache.http.entity.StringEntity)3 BasicHttpEntityEnclosingRequest (org.apache.http.message.BasicHttpEntityEnclosingRequest)3 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)3 BasicStatusLine (org.apache.http.message.BasicStatusLine)3 Before (org.junit.Before)3 Matchers.anyString (org.mockito.Matchers.anyString)3 SocketTimeoutException (java.net.SocketTimeoutException)2