Search in sources :

Example 1 with Message

use of org.apache.hc.core5.http.Message in project cxf by apache.

the class AsyncHTTPConduit method setupConnection.

@Override
protected void setupConnection(Message message, Address address, HTTPClientPolicy csPolicy) throws IOException {
    if (factory.isShutdown()) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, address, csPolicy);
        return;
    }
    propagateJaxwsSpecTimeoutSettings(message, csPolicy);
    boolean addressChanged = false;
    // need to do some clean up work on the URI address
    URI uri = address.getURI();
    String uriString = uri.toString();
    if (uriString.startsWith("hc://")) {
        uriString = uriString.substring(5);
        addressChanged = true;
    } else if (uriString.startsWith("hc5://")) {
        uriString = uriString.substring(6);
        addressChanged = true;
    }
    if (addressChanged) {
        try {
            uri = new URI(uriString);
        } catch (URISyntaxException ex) {
            throw new MalformedURLException("unsupport uri: " + uriString);
        }
    }
    String s = uri.getScheme();
    if (!"http".equals(s) && !"https".equals(s)) {
        throw new MalformedURLException("unknown protocol: " + s);
    }
    Object o = message.getContextualProperty(USE_ASYNC);
    if (o == null) {
        o = factory.getUseAsyncPolicy();
    }
    switch(UseAsyncPolicy.getPolicy(o)) {
        case ALWAYS:
            o = true;
            break;
        case NEVER:
            o = false;
            break;
        case ASYNC_ONLY:
        default:
            o = !message.getExchange().isSynchronous();
            break;
    }
    // check tlsClientParameters from message header
    TLSClientParameters clientParameters = message.get(TLSClientParameters.class);
    if (clientParameters == null) {
        clientParameters = tlsClientParameters;
    }
    if ("https".equals(uri.getScheme()) && clientParameters != null && clientParameters.getSSLSocketFactory() != null) {
        // if they configured in an SSLSocketFactory, we cannot do anything
        // with it as the NIO based transport cannot use socket created from
        // the SSLSocketFactory.
        o = false;
    }
    if (!PropertyUtils.isTrue(o)) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, addressChanged ? new Address(uriString, uri) : address, csPolicy);
        return;
    }
    if (StringUtils.isEmpty(uri.getPath())) {
        // hc needs to have the path be "/"
        uri = uri.resolve("/");
    }
    message.put(USE_ASYNC, Boolean.TRUE);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Asynchronous connection to " + uri.toString() + " has been set up");
    }
    message.put("http.scheme", uri.getScheme());
    String httpRequestMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
    if (httpRequestMethod == null) {
        httpRequestMethod = "POST";
        message.put(Message.HTTP_REQUEST_METHOD, httpRequestMethod);
    }
    final CXFHttpRequest e = new CXFHttpRequest(httpRequestMethod, uri);
    final String contentType = (String) message.get(Message.CONTENT_TYPE);
    final MutableHttpEntity entity = new MutableHttpEntity(contentType, null, true) {

        public boolean isRepeatable() {
            return e.getOutputStream().retransmitable();
        }
    };
    e.setEntity(entity);
    final RequestConfig.Builder b = RequestConfig.custom().setConnectTimeout(Timeout.ofMilliseconds(csPolicy.getConnectionTimeout())).setResponseTimeout(Timeout.ofMilliseconds(csPolicy.getReceiveTimeout())).setConnectionRequestTimeout(Timeout.ofMilliseconds(csPolicy.getConnectionRequestTimeout()));
    final Proxy p = proxyFactory.createProxy(csPolicy, uri);
    if (p != null && p.type() != Proxy.Type.DIRECT) {
        InetSocketAddress isa = (InetSocketAddress) p.address();
        HttpHost proxy = new HttpHost(isa.getHostString(), isa.getPort());
        b.setProxy(proxy);
    }
    e.setConfig(b.build());
    message.put(CXFHttpRequest.class, e);
}
Also used : TLSClientParameters(org.apache.cxf.configuration.jsse.TLSClientParameters) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) MalformedURLException(java.net.MalformedURLException) InetSocketAddress(java.net.InetSocketAddress) Address(org.apache.cxf.transport.http.Address) InetSocketAddress(java.net.InetSocketAddress) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Proxy(java.net.Proxy) HttpHost(org.apache.hc.core5.http.HttpHost)

Example 2 with Message

use of org.apache.hc.core5.http.Message in project ksql by confluentinc.

the class SchemaRegistryTopicSchemaSupplier method notFound.

private static SchemaResult notFound(final Optional<String> topicName, final Optional<Integer> schemaId, final boolean isKey) {
    final String suffixMsg = "- Messages on the topic have not been serialized using a Confluent " + "Schema Registry supported serializer" + System.lineSeparator() + "\t-> See " + DocumentationLinks.SR_SERIALISER_DOC_URL + System.lineSeparator() + "- The schema is registered on a different instance of the Schema Registry" + System.lineSeparator() + "\t-> Use the REST API to list available subjects" + "\t" + DocumentationLinks.SR_REST_GETSUBJECTS_DOC_URL + System.lineSeparator() + "- You do not have permissions to access the Schema Registry." + System.lineSeparator() + "\t-> See " + DocumentationLinks.SCHEMA_REGISTRY_SECURITY_DOC_URL;
    final String schemaIdMsg = schemaId.map(integer -> "Schema Id: " + integer + System.lineSeparator()).orElse("");
    if (topicName.isPresent()) {
        final String subject = getSRSubject(topicName.get(), isKey);
        return SchemaResult.failure(new KsqlException("Schema for message " + (isKey ? "keys" : "values") + " on topic '" + topicName.get() + "'" + " does not exist in the Schema Registry." + System.lineSeparator() + "Subject: " + subject + System.lineSeparator() + schemaIdMsg + "Possible causes include:" + System.lineSeparator() + "- The topic itself does not exist" + System.lineSeparator() + "\t-> Use SHOW TOPICS; to check" + System.lineSeparator() + "- Messages on the topic are not serialized using a format Schema Registry supports" + System.lineSeparator() + "\t-> Use PRINT '" + topicName.get() + "' FROM BEGINNING; to verify" + System.lineSeparator() + suffixMsg));
    }
    return SchemaResult.failure(new KsqlException("Schema for message " + (isKey ? "keys" : "values") + " on schema id'" + schemaId.get() + " does not exist in the Schema Registry." + System.lineSeparator() + schemaIdMsg + "Possible causes include:" + System.lineSeparator() + "- Schema Id " + schemaId + System.lineSeparator() + suffixMsg));
}
Also used : SchemaTranslationPolicy(io.confluent.ksql.serde.SchemaTranslationPolicy) SchemaRegistryClient(io.confluent.kafka.schemaregistry.client.SchemaRegistryClient) FormatFactory(io.confluent.ksql.serde.FormatFactory) SchemaTranslator(io.confluent.ksql.serde.SchemaTranslator) CommonCreateConfigs(io.confluent.ksql.properties.with.CommonCreateConfigs) ParsedSchema(io.confluent.kafka.schemaregistry.ParsedSchema) Function(java.util.function.Function) SchemaTranslationPolicies(io.confluent.ksql.serde.SchemaTranslationPolicies) Objects(java.util.Objects) KsqlConstants.getSRSubject(io.confluent.ksql.util.KsqlConstants.getSRSubject) List(java.util.List) DocumentationLinks(io.confluent.ksql.links.DocumentationLinks) Format(io.confluent.ksql.serde.Format) SimpleColumn(io.confluent.ksql.schema.ksql.SimpleColumn) KsqlException(io.confluent.ksql.util.KsqlException) Optional(java.util.Optional) RestClientException(io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException) VisibleForTesting(com.google.common.annotations.VisibleForTesting) SerdeFeatures(io.confluent.ksql.serde.SerdeFeatures) FormatInfo(io.confluent.ksql.serde.FormatInfo) HttpStatus(org.apache.hc.core5.http.HttpStatus) KsqlException(io.confluent.ksql.util.KsqlException)

Example 3 with Message

use of org.apache.hc.core5.http.Message in project logbook by zalando.

the class AbstractHttpTest method shouldLogResponseWithBody.

@Test
void shouldLogResponseWithBody() throws IOException, ExecutionException, InterruptedException, ParseException {
    driver.addExpectation(onRequestTo("/").withMethod(POST), giveResponse("Hello, world!", "text/plain"));
    final ClassicHttpResponse response = sendAndReceive("Hello, world!");
    assertThat(response.getCode()).isEqualTo(200);
    assertThat(response.getEntity()).isNotNull();
    assertThat(EntityUtils.toString(response.getEntity())).isEqualTo("Hello, world!");
    final String message = captureResponse();
    assertThat(message).startsWith("Incoming Response:").contains("HTTP/1.1 200 OK", "Content-Type: text/plain", "Hello, world!");
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 4 with Message

use of org.apache.hc.core5.http.Message in project httpcomponents-core by apache.

the class ReactiveFullDuplexClientExample method main.

public static void main(final String[] args) throws Exception {
    String endpoint = "http://localhost:8080/echo";
    if (args.length >= 1) {
        endpoint = args[0];
    }
    // Create and start requester
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build()).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final Random random = new Random();
    final Flowable<ByteBuffer> publisher = Flowable.range(1, 100).map(ignored -> {
        final String str = random.nextDouble() + "\n";
        return ByteBuffer.wrap(str.getBytes(UTF_8));
    });
    final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(new URI(endpoint)).setEntity(new ReactiveEntityProducer(publisher, -1, ContentType.TEXT_PLAIN, null)).build();
    final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
    final Future<Void> responseComplete = requester.execute(requestProducer, consumer, Timeout.ofSeconds(30), null);
    final Message<HttpResponse, Publisher<ByteBuffer>> streamingResponse = consumer.getResponseFuture().get();
    System.out.println(streamingResponse.getHead());
    for (final Header header : streamingResponse.getHead().getHeaders()) {
        System.out.println(header);
    }
    System.out.println();
    Observable.fromPublisher(streamingResponse.getBody()).map(byteBuffer -> {
        final byte[] string = new byte[byteBuffer.remaining()];
        byteBuffer.get(string);
        return new String(string);
    }).materialize().forEach(System.out::println);
    responseComplete.get(1, TimeUnit.MINUTES);
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) Publisher(org.reactivestreams.Publisher) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer) Timeout(org.apache.hc.core5.util.Timeout) StatusLine(org.apache.hc.core5.http.message.StatusLine) ReactiveEntityProducer(org.apache.hc.core5.reactive.ReactiveEntityProducer) RequestLine(org.apache.hc.core5.http.message.RequestLine) Random(java.util.Random) Header(org.apache.hc.core5.http.Header) ReactiveResponseConsumer(org.apache.hc.core5.reactive.ReactiveResponseConsumer) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 5 with Message

use of org.apache.hc.core5.http.Message in project httpcomponents-core by apache.

the class H2RequestExecutionExample method main.

public static void main(final String[] args) throws Exception {
    // Create and start requester
    final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
    final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {

        @Override
        public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
            }
        }

        @Override
        public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
            }
        }

        @Override
        public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }

        @Override
        public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final HttpHost target = new HttpHost("nghttp2.org");
    final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
    final CountDownLatch latch = new CountDownLatch(requestUris.length);
    for (final String requestUri : requestUris) {
        final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
        final AsyncClientEndpoint clientEndpoint = future.get();
        clientEndpoint.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {

            @Override
            public void completed(final Message<HttpResponse, String> message) {
                clientEndpoint.releaseAndReuse();
                final HttpResponse response = message.getHead();
                final String body = message.getBody();
                System.out.println(requestUri + "->" + response.getCode());
                System.out.println(body);
                latch.countDown();
            }

            @Override
            public void failed(final Exception ex) {
                clientEndpoint.releaseAndDiscard();
                System.out.println(requestUri + "->" + ex);
                latch.countDown();
            }

            @Override
            public void cancelled() {
                clientEndpoint.releaseAndDiscard();
                System.out.println(requestUri + " cancelled");
                latch.countDown();
            }
        });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) HttpConnection(org.apache.hc.core5.http.HttpConnection) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) List(java.util.List) H2Config(org.apache.hc.core5.http2.config.H2Config) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Aggregations

HttpResponse (org.apache.hc.core5.http.HttpResponse)101 Message (org.apache.hc.core5.http.Message)98 InetSocketAddress (java.net.InetSocketAddress)93 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)90 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)87 Test (org.junit.Test)84 HttpRequest (org.apache.hc.core5.http.HttpRequest)56 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)47 HttpHost (org.apache.hc.core5.http.HttpHost)41 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)40 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)31 IOException (java.io.IOException)30 Header (org.apache.hc.core5.http.Header)30 StringAsyncEntityProducer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer)30 Test (org.junit.jupiter.api.Test)26 HttpException (org.apache.hc.core5.http.HttpException)24 InterruptedIOException (java.io.InterruptedIOException)22 ProtocolException (org.apache.hc.core5.http.ProtocolException)22 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)20 BasicResponseConsumer (org.apache.hc.core5.http.nio.support.BasicResponseConsumer)19