Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -0,0 +1,56 @@
package com.baeldung.jetty;
import org.apache.commons.io.IOUtils;
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.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class JettyIntegrationTest {
private static JettyServer jettyServer;
@BeforeClass
public static void setup() throws Exception {
jettyServer = new JettyServer();
jettyServer.start();
}
@AfterClass
public static void cleanup() throws Exception {
jettyServer.stop();
}
@Test
public void givenServer_whenSendRequestToBlockingServlet_thenReturnStatusOK() throws Exception {
// given
String url = "http://localhost:8090/status";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
// then
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
}
@Test
public void givenServer_whenSendRequestToNonBlockingServlet_thenReturnStatusOK() throws Exception {
// when
String url = "http://localhost:8090/heavy/async";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
// then
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
String responseContent = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
assertThat(responseContent).isEqualTo("This is some heavy resource that will be served in an async way");
}
}
@@ -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();
}
}
@@ -0,0 +1,109 @@
package com.baeldung.mqtt;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EngineTemperatureSensorLiveTest {
private static Logger log = LoggerFactory.getLogger(EngineTemperatureSensorLiveTest.class);
@Test
public void whenSendSingleMessage_thenSuccess() throws Exception {
String publisherId = UUID.randomUUID().toString();
MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId);
String subscriberId = UUID.randomUUID().toString();
MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId);
MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(true);
options.setCleanSession(true);
options.setConnectionTimeout(10);
subscriber.connect(options);
publisher.connect(options);
CountDownLatch receivedSignal = new CountDownLatch(1);
subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> {
byte[] payload = msg.getPayload();
log.info("[I46] Message received: topic={}, payload={}", topic, new String(payload));
receivedSignal.countDown();
});
Callable<Void> target = new EngineTemperatureSensor(publisher);
target.call();
receivedSignal.await(1, TimeUnit.MINUTES);
log.info("[I56] Success !");
}
@Test
public void whenSendMultipleMessages_thenSuccess() throws Exception {
String publisherId = UUID.randomUUID().toString();
MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId);
String subscriberId = UUID.randomUUID().toString();
MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId);
MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(true);
options.setCleanSession(true);
options.setConnectionTimeout(10);
publisher.connect(options);
subscriber.connect(options);
CountDownLatch receivedSignal = new CountDownLatch(10);
subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> {
byte[] payload = msg.getPayload();
log.info("[I82] Message received: topic={}, payload={}", topic, new String(payload));
receivedSignal.countDown();
});
Callable<Void> target = new EngineTemperatureSensor(publisher);
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
try {
target.call();
}
catch(Exception ex) {
throw new RuntimeException(ex);
}
}, 1, 1, TimeUnit.SECONDS);
receivedSignal.await(1, TimeUnit.MINUTES);
executor.shutdown();
assertTrue(receivedSignal.getCount() == 0 , "Countdown should be zero");
log.info("[I105] Success !");
}
}
@@ -0,0 +1,37 @@
package com.baeldung.nanohttpd;
import org.apache.commons.io.IOUtils;
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.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class ApplicationControllerUnitTest {
private static final String BASE_URL = "http://localhost:8072/";
private static final HttpClient CLIENT = HttpClientBuilder.create().build();
@BeforeClass
public static void setUp() throws IOException {
new ApplicationController();
}
@Test
public void givenServer_whenRootRouteRequested_thenHelloWorldReturned() throws IOException {
HttpResponse response = CLIENT.execute(new HttpGet(BASE_URL));
assertTrue(IOUtils.toString(response.getEntity().getContent()).contains("Hello world!"));
assertEquals(200, response.getStatusLine().getStatusCode());
}
@Test
public void givenServer_whenUsersRequested_thenThenAllUsersReturned() throws IOException {
HttpResponse response = CLIENT.execute(new HttpGet(BASE_URL + "users"));
assertEquals("UserA, UserB, UserC", IOUtils.toString(response.getEntity().getContent()));
}
}
@@ -0,0 +1,37 @@
package com.baeldung.nanohttpd;
import static org.junit.Assert.*;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
public class ItemGetControllerUnitTest {
private static final String URL = "http://localhost:8071";
private static final HttpClient CLIENT = HttpClientBuilder.create().build();
@BeforeClass
public static void setUp() throws IOException {
new ItemGetController();
}
@Test
public void givenServer_whenDoingGet_thenParamIsReadCorrectly() throws IOException {
HttpResponse response = CLIENT.execute(new HttpGet(URL + "?itemId=1234"));
assertEquals("Requested itemId = 1234", IOUtils.toString(response.getEntity().getContent()));
}
@Test
public void givenServer_whenDoingPost_then404IsReturned() throws IOException {
HttpResponse response = CLIENT.execute(new HttpPost(URL));
assertEquals(404, response.getStatusLine().getStatusCode());
}
}
@@ -0,0 +1,89 @@
package com.baeldung.netty;
import java.nio.charset.Charset;
import static org.assertj.core.api.Assertions.*;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
public class EmbeddedChannelUnitTest {
@Test
public void givenTwoChannelHandlers_testPipeline() {
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"/calculate?a=10&b=5");
httpRequest.headers().add("Operator", "Add");
EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());
channel.pipeline().addFirst(new HttpMessageHandler()).addLast(new CalculatorOperationHandler());
// send HTTP request to server and check that the message is on the inbound pipeline
assertThat(channel.writeInbound(httpRequest)).isTrue();
long inboundChannelResponse = channel.readInbound();
assertThat(inboundChannelResponse).isEqualTo(15);
// we should have an outbound message in the form of a HTTP response
assertThat(channel.outboundMessages().size()).isEqualTo(1);
// Object response = channel.readOutbound();
FullHttpResponse httpResponse = channel.readOutbound();
String httpResponseContent = httpResponse.content().toString(Charset.defaultCharset());
assertThat(httpResponseContent).isEqualTo("15");
}
@Test
public void givenTwoChannelHandlers_testExceptionHandlingInHttpMessageHandler() {
EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());
final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
"/calculate?a=10&b=5");
wrongHttpRequest.headers().add("Operator", "Add");
assertThatThrownBy(() -> {
// send invalid HTTP request to server and expect and error
channel.pipeline().fireChannelRead(wrongHttpRequest);
channel.checkException();
}).isInstanceOf(UnsupportedOperationException.class)
.hasMessage("HTTP method not supported");
FullHttpResponse errorHttpResponse = channel.readOutbound();
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
assertThat(errorHttpResponseContent).isEqualToIgnoringCase("Operation not defined");
assertThat(errorHttpResponse.status()).isEqualTo(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
@Test
public void givenTwoChannelHandlers_testExceptionHandlingInCalculatorOperationHandler() {
EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());
final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"/calculate?a=10&b=5");
wrongHttpRequest.headers().add("Operator", "Invalid_operation");
// the HttpMessageHandler does not handle the exception and throws it down the pipeline
assertThatThrownBy(() -> {
channel.writeInbound(wrongHttpRequest);
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Operation not defined");
// the outbound message is a HTTP response with the status code 500
FullHttpResponse errorHttpResponse = channel.readOutbound();
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
assertThat(errorHttpResponseContent).isEqualToIgnoringCase("Operation not defined");
assertThat(errorHttpResponse.status()).isEqualTo(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
@@ -0,0 +1,85 @@
package com.baeldung.smack;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.filter.StanzaTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.jxmpp.stringprep.XmppStringprepException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class SmackIntegrationTest {
private static AbstractXMPPConnection connection;
private Logger logger = LoggerFactory.getLogger(SmackIntegrationTest.class);
@BeforeClass
public static void setup() throws IOException, InterruptedException, XMPPException, SmackException {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("baeldung","baeldung")
.setXmppDomain("jabb3r.org")
.setHost("jabb3r.org")
.build();
XMPPTCPConnectionConfiguration config2 = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("baeldung2","baeldung2")
.setXmppDomain("jabb3r.org")
.setHost("jabb3r.org")
.build();
connection = new XMPPTCPConnection(config);
connection.connect();
connection.login();
}
@Test
public void whenSendMessageWithChat_thenReceiveMessage() throws XmppStringprepException, InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
ChatManager chatManager = ChatManager.getInstanceFor(connection);
final String[] expected = {null};
new StanzaThread().run();
chatManager.addIncomingListener((entityBareJid, message, chat) -> {
logger.info("Message arrived: " + message.getBody());
expected[0] = message.getBody();
latch.countDown();
});
latch.await();
Assert.assertEquals("Hello!", expected[0]);
}
@Test
public void whenSendMessage_thenReceiveMessageWithFilter() throws XmppStringprepException, InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
final String[] expected = {null};
new StanzaThread().run();
connection.addAsyncStanzaListener(stanza -> {
if (stanza instanceof Message) {
Message message = (Message) stanza;
expected[0] = message.getBody();
latch.countDown();
}
}, StanzaTypeFilter.MESSAGE);
latch.await();
Assert.assertEquals("Hello!", expected[0]);
}
}
@@ -0,0 +1,55 @@
package com.baeldung.tomcat;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Created by adi on 1/14/18.
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class ProgrammaticTomcatIntegrationTest {
private ProgrammaticTomcat tomcat = new ProgrammaticTomcat();
@Before
public void setUp() throws Exception {
tomcat.startTomcat();
}
@After
public void tearDown() throws Exception {
tomcat.stopTomcat();
}
@Test
public void givenTomcatStarted_whenAccessServlet_responseIsTestAndResponseHeaderIsSet() throws Exception {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet getServlet = new HttpGet("http://localhost:8080/my-servlet");
HttpResponse response = httpClient.execute(getServlet);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
String myHeaderValue = response.getFirstHeader("myHeader").getValue();
assertEquals("myHeaderValue", myHeaderValue);
HttpEntity responseEntity = response.getEntity();
assertNotNull(responseEntity);
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
assertEquals("test", responseString);
}
}