Merge branch 'master' into BAEL-1267-programmatic-tomcat
This commit is contained in:
@@ -0,0 +1,209 @@
|
||||
package com.baeldung.asynchttpclient;
|
||||
|
||||
import io.netty.handler.codec.http.HttpHeaders;
|
||||
import org.asynchttpclient.AsyncCompletionHandler;
|
||||
import org.asynchttpclient.AsyncHandler;
|
||||
import org.asynchttpclient.AsyncHttpClient;
|
||||
import org.asynchttpclient.AsyncHttpClientConfig;
|
||||
import org.asynchttpclient.BoundRequestBuilder;
|
||||
import org.asynchttpclient.Dsl;
|
||||
import org.asynchttpclient.HttpResponseBodyPart;
|
||||
import org.asynchttpclient.HttpResponseStatus;
|
||||
import org.asynchttpclient.ListenableFuture;
|
||||
import org.asynchttpclient.Request;
|
||||
import org.asynchttpclient.Response;
|
||||
import org.asynchttpclient.ws.WebSocket;
|
||||
import org.asynchttpclient.ws.WebSocketListener;
|
||||
import org.asynchttpclient.ws.WebSocketUpgradeHandler;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class AsyncHttpClientTestCase {
|
||||
|
||||
private static AsyncHttpClient HTTP_CLIENT;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
AsyncHttpClientConfig clientConfig = Dsl.config().setConnectTimeout(15000).setRequestTimeout(15000).build();
|
||||
HTTP_CLIENT = Dsl.asyncHttpClient(clientConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeSyncGetRequest() {
|
||||
|
||||
BoundRequestBuilder boundGetRequest = HTTP_CLIENT.prepareGet("http://www.baeldung.com");
|
||||
|
||||
Future<Response> responseFuture = boundGetRequest.execute();
|
||||
try {
|
||||
Response response = responseFuture.get(5000, TimeUnit.MILLISECONDS);
|
||||
assertNotNull(response);
|
||||
assertEquals(200, response.getStatusCode());
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequest() {
|
||||
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
HTTP_CLIENT.executeRequest(unboundGetRequest, new AsyncCompletionHandler<Integer>() {
|
||||
@Override
|
||||
public Integer onCompleted(Response response) {
|
||||
|
||||
int resposeStatusCode = response.getStatusCode();
|
||||
assertEquals(200, resposeStatusCode);
|
||||
return resposeStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
// execute a bound GET request
|
||||
BoundRequestBuilder boundGetRequest = HTTP_CLIENT.prepareGet("http://www.baeldung.com");
|
||||
|
||||
boundGetRequest.execute(new AsyncCompletionHandler<Integer>() {
|
||||
@Override
|
||||
public Integer onCompleted(Response response) {
|
||||
int resposeStatusCode = response.getStatusCode();
|
||||
assertEquals(200, resposeStatusCode);
|
||||
return resposeStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequestWithAsyncHandler() {
|
||||
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
HTTP_CLIENT.executeRequest(unboundGetRequest, new AsyncHandler<Integer>() {
|
||||
|
||||
int responseStatusCode = -1;
|
||||
|
||||
@Override
|
||||
public State onStatusReceived(HttpResponseStatus responseStatus) {
|
||||
responseStatusCode = responseStatus.getStatusCode();
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onHeadersReceived(HttpHeaders headers) {
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) {
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onThrowable(Throwable t) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer onCompleted() {
|
||||
assertEquals(200, responseStatusCode);
|
||||
return responseStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequestWithListanableFuture() {
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
ListenableFuture<Response> listenableFuture = HTTP_CLIENT.executeRequest(unboundGetRequest);
|
||||
listenableFuture.addListener(() -> {
|
||||
Response response;
|
||||
try {
|
||||
response = listenableFuture.get(5000, TimeUnit.MILLISECONDS);
|
||||
assertEquals(200, response.getStatusCode());
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}, Executors.newCachedThreadPool());
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWebSocketClient_tryToConnect() {
|
||||
|
||||
WebSocketUpgradeHandler.Builder upgradeHandlerBuilder = new WebSocketUpgradeHandler.Builder();
|
||||
WebSocketUpgradeHandler wsHandler = upgradeHandlerBuilder.addWebSocketListener(new WebSocketListener() {
|
||||
@Override
|
||||
public void onOpen(WebSocket websocket) {
|
||||
// WebSocket connection opened
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(WebSocket websocket, int code, String reason) {
|
||||
// WebSocket connection closed
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable t) {
|
||||
// WebSocket connection error
|
||||
assertTrue(t.getMessage().contains("Request timeout"));
|
||||
}
|
||||
}).build();
|
||||
|
||||
WebSocket WEBSOCKET_CLIENT = null;
|
||||
try {
|
||||
WEBSOCKET_CLIENT = Dsl.asyncHttpClient()
|
||||
.prepareGet("ws://localhost:5590/websocket")
|
||||
.addHeader("header_name", "header_value")
|
||||
.addQueryParam("key", "value")
|
||||
.setRequestTimeout(5000)
|
||||
.execute(wsHandler).get();
|
||||
|
||||
if (WEBSOCKET_CLIENT.isOpen()) {
|
||||
WEBSOCKET_CLIENT.sendPingFrame();
|
||||
WEBSOCKET_CLIENT.sendTextFrame("test message");
|
||||
WEBSOCKET_CLIENT.sendBinaryFrame(new byte[]{'t', 'e', 's', 't'});
|
||||
}
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (WEBSOCKET_CLIENT != null && WEBSOCKET_CLIENT.isOpen()) {
|
||||
WEBSOCKET_CLIENT.sendCloseFrame(200, "OK");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Test for {@link JettyServerFactory}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class JettyServerFactoryUnitTest {
|
||||
|
||||
/**
|
||||
* Tests that when a base server is provided a request returns a status 404.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void givenBaseServer_whenHttpRequest_thenStatus404() throws Exception {
|
||||
Server server = JettyServerFactory.createBaseServer();
|
||||
server.start();
|
||||
|
||||
int statusCode = sendGetRequest();
|
||||
|
||||
Assert.assertEquals(404, statusCode);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that when a web app server is provided a request returns a status
|
||||
* 200.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void givenWebAppServer_whenHttpRequest_thenStatus200() throws Exception {
|
||||
Server server = JettyServerFactory.createWebAppServer();
|
||||
server.start();
|
||||
|
||||
int statusCode = sendGetRequest();
|
||||
|
||||
Assert.assertEquals(200, statusCode);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that when a multi handler server is provided a request returns a
|
||||
* status 200.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void givenMultiHandlerServerServer_whenHttpRequest_thenStatus200() throws Exception {
|
||||
Server server = JettyServerFactory.createMultiHandlerServer();
|
||||
server.start();
|
||||
|
||||
int statusCode = sendGetRequest();
|
||||
|
||||
Assert.assertEquals(200, statusCode);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a default HTTP GET request to the server and returns the response
|
||||
* status code.
|
||||
*
|
||||
* @return the status code of the response
|
||||
* @throws Exception
|
||||
*/
|
||||
private int sendGetRequest() throws Exception {
|
||||
HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT);
|
||||
HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH);
|
||||
HttpClient client = HttpClientBuilder.create().build();
|
||||
HttpResponse response = client.execute(target, request);
|
||||
return response.getStatusLine().getStatusCode();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -32,9 +32,9 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
headers.put("Content-Type", "application/json");
|
||||
|
||||
return builder
|
||||
.given("test GET ")
|
||||
.given("test GET")
|
||||
.uponReceiving("GET REQUEST")
|
||||
.path("/")
|
||||
.path("/pact")
|
||||
.method("GET")
|
||||
.willRespondWith()
|
||||
.status(200)
|
||||
@@ -45,11 +45,9 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
.method("POST")
|
||||
.headers(headers)
|
||||
.body("{\"name\": \"Michael\"}")
|
||||
.path("/create")
|
||||
.path("/pact")
|
||||
.willRespondWith()
|
||||
.status(201)
|
||||
.headers(headers)
|
||||
.body("")
|
||||
.toPact();
|
||||
}
|
||||
|
||||
@@ -59,7 +57,7 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
|
||||
//when
|
||||
ResponseEntity<String> response
|
||||
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
|
||||
= new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class);
|
||||
|
||||
//then
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(200);
|
||||
@@ -73,7 +71,7 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
|
||||
//when
|
||||
ResponseEntity<String> postResponse = new RestTemplate().exchange(
|
||||
mockProvider.getUrl() + "/create",
|
||||
mockProvider.getUrl() + "/pact",
|
||||
HttpMethod.POST,
|
||||
new HttpEntity<>(jsonBody, httpHeaders),
|
||||
String.class
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.smooks.converter;
|
||||
|
||||
import com.baeldung.smooks.model.Item;
|
||||
import com.baeldung.smooks.model.Order;
|
||||
import com.baeldung.smooks.model.Status;
|
||||
import com.baeldung.smooks.model.Supplier;
|
||||
import org.junit.Test;
|
||||
import org.milyn.validation.ValidationResult;
|
||||
import java.text.SimpleDateFormat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class SmooksIntegrationTest {
|
||||
|
||||
private static final String EDIFACT_MESSAGE =
|
||||
"UNA:+.? '\r\n" +
|
||||
"UNH+771+IN_PROGRESS+2018-01-14'\r\n" +
|
||||
"CTA+CompanyX+1234567'\r\n" +
|
||||
"LIN+1+PX1234+9.99'\r\n" +
|
||||
"LIN+2+RX990+120.32'\r\n";
|
||||
private static final String EMAIL_MESSAGE =
|
||||
"Hi,\r\n" +
|
||||
"Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status.\r\n" +
|
||||
"Consider contact supplier \"CompanyX\" with phone number: \"1234567\".\r\n" +
|
||||
"Order items:\r\n" +
|
||||
"1 X PX1234 (total price 9.99)\r\n" +
|
||||
"2 X RX990 (total price 240.64)\r\n";
|
||||
|
||||
@Test
|
||||
public void givenOrderXML_whenConvert_thenPOJOsConstructedCorrectly() throws Exception {
|
||||
|
||||
OrderConverter xmlToJavaOrderConverter = new OrderConverter();
|
||||
Order order = xmlToJavaOrderConverter.convertOrderXMLToOrderObject("/smooks/order.xml");
|
||||
|
||||
assertThat(order.getNumber(),is(771L));
|
||||
assertThat(order.getStatus(),is(Status.IN_PROGRESS));
|
||||
assertThat(order.getCreationDate(),is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14")));
|
||||
assertThat(order.getSupplier(),is(new Supplier("CompanyX","1234567")));
|
||||
assertThat(order.getItems(),containsInAnyOrder(
|
||||
new Item("PX1234",9.99,1),
|
||||
new Item("RX990",120.32,2))
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIncorrectOrderXML_whenValidate_thenExpectValidationErrors() throws Exception {
|
||||
OrderValidator orderValidator = new OrderValidator();
|
||||
ValidationResult validationResult = orderValidator.validate("/smooks/order.xml");
|
||||
|
||||
assertThat(validationResult.getErrors(), hasSize(1));
|
||||
// 1234567 didn't match ^[0-9\\-\\+]{9,15}$
|
||||
assertThat(validationResult.getErrors().get(0).getFailRuleResult().getRuleName(),is("supplierPhone"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOrderXML_whenApplyEDITemplate_thenConvertedToEDIFACT() throws Exception {
|
||||
OrderConverter orderConverter = new OrderConverter();
|
||||
String edifact = orderConverter.convertOrderXMLtoEDIFACT("/smooks/order.xml");
|
||||
assertThat(edifact,is(EDIFACT_MESSAGE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOrderXML_whenApplyEmailTemplate_thenConvertedToEmailMessage() throws Exception {
|
||||
OrderConverter orderConverter = new OrderConverter();
|
||||
String emailMessage = orderConverter.convertOrderXMLtoEmailMessage("/smooks/order.xml");
|
||||
assertThat(emailMessage,is(EMAIL_MESSAGE));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user