use of io.undertow.client.ClientConnection in project light-rest-4j by networknt.
the class ValidatorHandlerTest method testDeleteWithHeader.
@Test
public void testDeleteWithHeader() throws Exception {
final Http2Client client = Http2Client.getInstance();
final CountDownLatch latch = new CountDownLatch(1);
final ClientConnection connection;
try {
connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
} catch (Exception e) {
throw new ClientException(e);
}
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
try {
ClientRequest request = new ClientRequest().setPath("/v2/pet/111").setMethod(Methods.DELETE);
request.getRequestHeaders().put(new HttpString("api_key"), "key");
connection.sendRequest(request, client.createClientCallback(reference, latch));
latch.await();
} catch (Exception e) {
logger.error("Exception: ", e);
throw new ClientException(e);
} finally {
IoUtils.safeClose(connection);
}
int statusCode = reference.get().getResponseCode();
String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
Assert.assertEquals(200, statusCode);
if (statusCode == 200) {
Assert.assertNotNull(body);
Assert.assertEquals("deletePet", body);
}
}
use of io.undertow.client.ClientConnection in project light-rest-4j by networknt.
the class ValidatorHandlerTest method testValidPost.
@Test
public void testValidPost() throws Exception {
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
final Http2Client client = Http2Client.getInstance();
final CountDownLatch latch = new CountDownLatch(1);
final ClientConnection connection;
try {
connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
} catch (Exception e) {
throw new ClientException(e);
}
try {
String post = "{\"id\":0,\"category\":{\"id\":0,\"name\":\"string\"},\"name\":\"doggie\",\"photoUrls\":[\"string\"],\"tags\":[{\"id\":0,\"name\":\"string\"}],\"status\":\"available\"}";
connection.getIoThread().execute(new Runnable() {
@Override
public void run() {
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/v2/pet");
request.getRequestHeaders().put(Headers.HOST, "localhost");
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
connection.sendRequest(request, client.createClientCallback(reference, latch, post));
}
});
latch.await(10, TimeUnit.SECONDS);
} catch (Exception e) {
logger.error("IOException: ", e);
throw new ClientException(e);
} finally {
IoUtils.safeClose(connection);
}
int statusCode = reference.get().getResponseCode();
String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
Assert.assertEquals(200, statusCode);
if (statusCode == 200) {
Assert.assertNotNull(body);
Assert.assertEquals("addPet", body);
}
}
use of io.undertow.client.ClientConnection in project light-4j by networknt.
the class ConsulClientImpl method unregisterService.
@Override
public void unregisterService(String serviceId, String token) {
String path = "/v1/agent/service/deregister/" + serviceId;
ClientConnection connection = null;
try {
connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
} catch (Exception e) {
logger.error("Exeption:", e);
}
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
try {
ClientRequest request = new ClientRequest().setMethod(Methods.PUT).setPath(path);
request.getRequestHeaders().put(Headers.HOST, "localhost");
if (token != null)
request.getRequestHeaders().put(Constants.CONSUL_TOKEN, token);
connection.sendRequest(request, client.createClientCallback(reference, latch));
latch.await();
int statusCode = reference.get().getResponseCode();
if (statusCode >= 300) {
System.out.println("body = " + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
throw new Exception("Failed to unregister on Consul: " + statusCode);
}
} catch (Exception e) {
logger.error("Exception:", e);
} finally {
IoUtils.safeClose(connection);
}
}
use of io.undertow.client.ClientConnection in project light-4j by networknt.
the class ConsulClientImpl method checkPass.
@Override
public void checkPass(String serviceId, String token) {
if (logger.isDebugEnabled())
logger.debug("checkPass serviceId = " + serviceId);
String path = "/v1/agent/check/pass/" + "service:" + serviceId;
ClientConnection connection = null;
try {
connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
} catch (Exception e) {
logger.error("Exeption:", e);
}
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
try {
ClientRequest request = new ClientRequest().setMethod(Methods.PUT).setPath(path);
request.getRequestHeaders().put(Headers.HOST, "localhost");
if (token != null)
request.getRequestHeaders().put(Constants.CONSUL_TOKEN, token);
connection.sendRequest(request, client.createClientCallback(reference, latch));
latch.await();
int statusCode = reference.get().getResponseCode();
if (statusCode >= 300) {
logger.error("Failed to checkPass on Consul: " + statusCode + ":" + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
throw new Exception("Failed to checkPass on Consul: " + statusCode + ":" + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
}
} catch (Exception e) {
logger.error("CheckPass request exception", e);
} finally {
IoUtils.safeClose(connection);
}
}
use of io.undertow.client.ClientConnection in project undertow by undertow-io.
the class Http2EndExchangeTestCase method testHttp2EndExchangeWithBrokenConnection.
@Test
public void testHttp2EndExchangeWithBrokenConnection() throws Exception {
int port = DefaultServer.getHostPort("default");
final CountDownLatch requestStartedLatch = new CountDownLatch(1);
final CompletableFuture<String> testResult = new CompletableFuture<>();
Undertow server = Undertow.builder().addHttpsListener(port + 1, DefaultServer.getHostAddress("default"), DefaultServer.getServerSslContext()).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setSocketOption(Options.REUSE_ADDRESSES, true).setHandler(new BlockingHandler(new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (!exchange.getProtocol().equals(Protocols.HTTP_2_0)) {
testResult.completeExceptionally(new RuntimeException("Not HTTP/2 request"));
return;
}
requestStartedLatch.countDown();
log.debug("Received Request");
// do some pretend work
Thread.sleep(2000);
if (exchange.isComplete()) {
testResult.complete("FAILED, exchange ended in the background");
return;
}
try {
exchange.getOutputStream().write("Bogus Data".getBytes(StandardCharsets.UTF_8));
exchange.getOutputStream().flush();
testResult.complete("FAILED, should not have completed successfully");
return;
} catch (IOException expected) {
}
if (!exchange.isComplete()) {
testResult.complete("Failed, should have completed the exchange");
} else {
testResult.complete("PASSED");
}
}
})).build();
server.start();
try {
ADDRESS = new URI("https://" + DefaultServer.getHostAddress() + ":" + (port + 1));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
// Create xnio worker
final Xnio xnio = Xnio.getInstance();
final XnioWorker xnioWorker = xnio.createWorker(null, DEFAULT_OPTIONS);
try {
final UndertowClient client = createClient();
final ClientConnection connection = client.connect(ADDRESS, xnioWorker, new UndertowXnioSsl(xnioWorker.getXnio(), OptionMap.EMPTY, DefaultServer.getClientSSLContext()), DefaultServer.getBufferPool(), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
try {
connection.getIoThread().execute(new Runnable() {
@Override
public void run() {
final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
connection.sendRequest(request, new ClientCallback<ClientExchange>() {
@Override
public void completed(ClientExchange result) {
try {
log.debug("Callback invoked");
new Thread(new Runnable() {
@Override
public void run() {
try {
requestStartedLatch.await(10, TimeUnit.SECONDS);
result.getRequestChannel().getIoThread().execute(new Runnable() {
@Override
public void run() {
IoUtils.safeClose(result.getConnection());
log.debug("Closed Connection");
}
});
} catch (Exception e) {
testResult.completeExceptionally(e);
}
}
}).start();
} catch (Exception e) {
testResult.completeExceptionally(e);
}
}
@Override
public void failed(IOException e) {
testResult.completeExceptionally(e);
}
});
}
});
Assert.assertEquals("PASSED", testResult.get(10, TimeUnit.SECONDS));
} finally {
IoUtils.safeClose(connection);
}
} finally {
stopWorker(xnioWorker);
server.stop();
// sleep 1 s to prevent BindException (Address already in use) when running the CI
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
}
}
Aggregations