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);
}
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));
}
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!");
}
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();
}
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();
}
Aggregations