group and cleanup (#3027)

* move security content from spring-security-rest-full

* swagger update

* move query language to new module

* rename spring-security-rest-full to spring-rest-full

* group persistence modules

* group testing modules

* try fix conflict

* cleanup

* group and cleanup
This commit is contained in:
Doha2012
2017-11-13 17:45:26 +02:00
committed by Grzegorz Piwowarek
parent 2a85b9c96e
commit 2e5531edd0
198 changed files with 20 additions and 15 deletions
@@ -0,0 +1,135 @@
package com.baeldug.json;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.json.Person;
import com.baeldung.json.PersonBuilder;
import com.baeldung.json.PersonWriter;
public class JsonUnitTest {
private Person person;
private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
private String personJson;
private String petshopJson;
@Test
public void whenPersonIsConvertedToString_thenAValidJsonStringIsReturned() throws IOException {
String generatedJsonString = new PersonWriter(person).write();
assertEquals(
"Generated String has the expected format and content",
personJson,
generatedJsonString);
}
@Test
public void whenJsonStringIsConvertedToPerson_thenAValidObjectIsReturned(
) throws IOException, ParseException {
Person person = new PersonBuilder(personJson).build();
assertEquals("First name has expected value", "Michael", person.getFirstName());
assertEquals("Last name has expected value", "Scott", person.getLastName());
assertEquals(
"Birthdate has expected value",
dateFormat.parse("06/15/1978"),
person.getBirthdate());
assertThat(
"Email list has two items",
person.getEmails(),
hasItems("michael.scott@dd.com", "michael.scarn@gmail.com"));
}
@Test
public void whenUsingObjectModelToQueryForSpecificProperty_thenExpectedValueIsReturned(
) throws IOException, ParseException {
JsonReader reader = Json.createReader(new StringReader(petshopJson));
JsonObject jsonObject = reader.readObject();
assertEquals(
"The query should return the 'name' property of the third pet from the list",
"Jake",
jsonObject.getJsonArray("pets").getJsonObject(2).getString("name"));
}
@Test
public void whenUsingStreamingApiToQueryForSpecificProperty_thenExpectedValueIsReturned(
) throws IOException, ParseException {
JsonParser jsonParser = Json.createParser(new StringReader(petshopJson));
int count = 0;
String result = null;
while(jsonParser.hasNext()) {
Event e = jsonParser.next();
if (e == Event.KEY_NAME) {
if(jsonParser.getString().equals("name")) {
jsonParser.next();
if(++count == 3) {
result = jsonParser.getString();
break;
}
}
}
}
assertEquals(
"The query should return the 'name' property of the third pet from the list",
"Jake",
result);
}
@Before
public void init() throws ParseException {
// Creates a Person object
person = new Person();
person.setFirstName("Michael");
person.setLastName("Scott");
person.setBirthdate(dateFormat.parse("06/15/1978"));
person.setEmails(Arrays.asList("michael.scott@dd.com", "michael.scarn@gmail.com"));
// Initializes the Person Json
personJson = "\n" +
"{\n" +
" \"firstName\":\"Michael\",\n" +
" \"lastName\":\"Scott\",\n" +
" \"birthdate\":\"06/15/1978\",\n" +
" \"emails\":[\n" +
" \"michael.scott@dd.com\",\n" +
" \"michael.scarn@gmail.com\"\n" +
" ]\n" +
"}";
// Initializes the Pet Shop Json
petshopJson = "\n" +
"{\n" +
" \"ownerId\":\"1\", \n" +
" \"pets\":[ \n" +
" {\"name\": \"Kitty\", \"type\": \"cat\"}, \n" +
" {\"name\": \"Rex\", \"type\": \"dog\"}, \n" +
" {\"name\": \"Jake\", \"type\": \"dog\"} \n" +
" ]\n" +
"}";
}
}
@@ -0,0 +1,73 @@
package com.baeldung.arquillan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.baeldung.arquillian.CapsConvertor;
import com.baeldung.arquillian.CapsService;
import com.baeldung.arquillian.Car;
import com.baeldung.arquillian.CarEJB;
import com.baeldung.arquillian.Component;
import com.baeldung.arquillian.ConvertToLowerCase;
@RunWith(Arquillian.class)
public class ArquillianLiveTest {
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class).addClasses(Component.class, CapsService.class, CapsConvertor.class, ConvertToLowerCase.class, Car.class, CarEJB.class).addAsResource("META-INF/persistence.xml").addAsManifestResource(EmptyAsset.INSTANCE,
"beans.xml");
}
@Inject
Component component;
@Test
public void givenMessage_WhenComponentSendMessage_ThenMessageReceived() {
Assert.assertEquals("Message, MESSAGE", component.message(("MESSAGE")));
component.sendMessage(System.out, "MESSAGE");
}
@Inject
private CapsService capsService;
@Test
public void givenWord_WhenUppercase_ThenLowercase() {
assertTrue("capitalize".equals(capsService.getConvertedCaps("CAPITALIZE")));
assertEquals("capitalize", capsService.getConvertedCaps("CAPITALIZE"));
}
@Inject
private CarEJB carEJB;
@Test
public void testCars() {
assertTrue(carEJB.findAllCars().isEmpty());
Car c1 = new Car();
c1.setName("Impala");
Car c2 = new Car();
c2.setName("Maverick");
Car c3 = new Car();
c3.setName("Aspen");
Car c4 = new Car();
c4.setName("Lincoln");
carEJB.saveCar(c1);
carEJB.saveCar(c2);
carEJB.saveCar(c3);
carEJB.saveCar(c4);
assertEquals(4, carEJB.findAllCars().size());
carEJB.deleteCar(c4);
assertEquals(3, carEJB.findAllCars().size());
}
}
@@ -0,0 +1,101 @@
package com.baeldung.convListVal;
import static org.jboss.arquillian.graphene.Graphene.guardHttp;
import java.io.File;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
@RunWith(Arquillian.class)
public class ConvListValIntegrationTest {
@ArquillianResource
private URL deploymentUrl;
private static final String WEBAPP_SRC = "src/main/webapp";
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ( ShrinkWrap.create(
WebArchive.class, "jee7.war").
addClasses(ConvListVal.class, MyListener.class)).
addAsWebResource(new File(WEBAPP_SRC, "ConvListVal.xhtml")).
addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Drone
WebDriver browser;
@ArquillianResource
URL contextPath;
@FindBy(id="myForm:age")
private WebElement ageInput;
@FindBy(id="myForm:average")
private WebElement averageInput;
@FindBy(id="myForm:send")
private WebElement sendButton;
@Test
@RunAsClient
public void givenAge_whenAgeInvalid_thenErrorMessage() throws Exception {
browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf");
ageInput.sendKeys("stringage");
guardHttp(sendButton).click();
Assert.assertTrue("Show Age error message", browser.findElements(By.id("myForm:ageError")).size() > 0);
}
@Test
@RunAsClient
public void givenAverage_whenAverageInvalid_thenErrorMessage() throws Exception {
browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf");
averageInput.sendKeys("stringaverage");
guardHttp(sendButton).click();
Assert.assertTrue("Show Average error message", browser.findElements(By.id("myForm:averageError")).size() > 0);
}
@Test
@RunAsClient
public void givenDate_whenDateInvalid_thenErrorMessage() throws Exception {
browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf");
averageInput.sendKeys("123");
guardHttp(sendButton).click();
Assert.assertTrue("Show Date error message", browser.findElements(By.id("myForm:myDateError")).size() > 0);
}
@Test
@RunAsClient
public void givenSurname_whenSurnameMinLenghtInvalid_thenErrorMessage() throws Exception {
browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf");
averageInput.sendKeys("aaa");
guardHttp(sendButton).click();
Assert.assertTrue("Show Surname error message", browser.findElements(By.id("myForm:surnameError")).size() > 0);
}
@Test
@RunAsClient
public void givenSurname_whenSurnameMaxLenghtInvalid_thenErrorMessage() throws Exception {
browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf");
averageInput.sendKeys("aaaaabbbbbc");
guardHttp(sendButton).click();
Assert.assertTrue("Show Surname error message", browser.findElements(By.id("myForm:surnameError")).size() > 0);
}
}
@@ -0,0 +1,114 @@
package com.baeldung.jaxws;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.namespace.QName;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.baeldung.jaxws.client.Employee;
import com.baeldung.jaxws.client.EmployeeAlreadyExists_Exception;
import com.baeldung.jaxws.client.EmployeeNotFound_Exception;
import com.baeldung.jaxws.client.EmployeeService;
import com.baeldung.jaxws.client.EmployeeService_Service;
@RunWith(Arquillian.class)
public class EmployeeServiceLiveTest {
private static final String APP_NAME = "jee7";
private static final String WSDL_PATH = "EmployeeService?wsdl";
private static QName SERVICE_NAME = new QName("http://bottomup.server.jaxws.baeldung.com/", "EmployeeService");
private static URL wsdlUrl;
@ArquillianResource
private URL deploymentUrl;
private EmployeeService employeeServiceProxy;
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, APP_NAME + ".war")
.addPackage(com.baeldung.jaxws.server.bottomup.EmployeeService.class.getPackage())
.addPackage(com.baeldung.jaxws.server.bottomup.model.Employee.class.getPackage())
.addPackage(com.baeldung.jaxws.server.bottomup.exception.EmployeeNotFound.class.getPackage())
.addPackage(com.baeldung.jaxws.server.repository.EmployeeRepository.class.getPackage())
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Before
public void setUp() {
try {
wsdlUrl = new URL(deploymentUrl, WSDL_PATH);
} catch (MalformedURLException e) {
e.printStackTrace();
}
EmployeeService_Service employeeService_Service = new EmployeeService_Service(wsdlUrl);
employeeServiceProxy = employeeService_Service.getEmployeeServiceImplPort();
}
@Test
public void givenEmployees_whenGetCount_thenCorrectNumberOfEmployeesReturned() {
int employeeCount = employeeServiceProxy.countEmployees();
List<Employee> employeeList = employeeServiceProxy.getAllEmployees();
assertEquals(employeeList.size(), employeeCount);
}
@Test
public void givenEmployees_whenGetAvailableEmployee_thenCorrectEmployeeReturned() throws EmployeeNotFound_Exception {
Employee employee = employeeServiceProxy.getEmployee(2);
assertEquals(employee.getFirstName(), "Jack");
}
@Test(expected = EmployeeNotFound_Exception.class)
public void givenEmployees_whenGetNonAvailableEmployee_thenEmployeeNotFoundException() throws EmployeeNotFound_Exception {
employeeServiceProxy.getEmployee(20);
}
@Test
public void givenEmployees_whenAddNewEmployee_thenEmployeeCountIncreased() throws EmployeeAlreadyExists_Exception {
int employeeCount = employeeServiceProxy.countEmployees();
employeeServiceProxy.addEmployee(4, "Anna");
assertEquals(employeeServiceProxy.countEmployees(), employeeCount + 1);
}
@Test(expected = EmployeeAlreadyExists_Exception.class)
public void givenEmployees_whenAddAlreadyExistingEmployee_thenEmployeeAlreadyExistsException() throws EmployeeAlreadyExists_Exception {
employeeServiceProxy.addEmployee(1, "Anna");
}
@Test
public void givenEmployees_whenUpdateExistingEmployee_thenUpdatedEmployeeReturned() throws EmployeeNotFound_Exception {
Employee updated = employeeServiceProxy.updateEmployee(1, "Joan");
assertEquals(updated.getFirstName(), "Joan");
}
@Test(expected = EmployeeNotFound_Exception.class)
public void givenEmployees_whenUpdateNonExistingEmployee_thenEmployeeNotFoundException() throws EmployeeNotFound_Exception {
employeeServiceProxy.updateEmployee(20, "Joan");
}
@Test
public void givenEmployees_whenDeleteExistingEmployee_thenSuccessReturned() throws EmployeeNotFound_Exception {
boolean deleteEmployee = employeeServiceProxy.deleteEmployee(3);
assertEquals(deleteEmployee, true);
}
@Test(expected = EmployeeNotFound_Exception.class)
public void givenEmployee_whenDeleteNonExistingEmployee_thenEmployeeNotFoundException() throws EmployeeNotFound_Exception {
employeeServiceProxy.deleteEmployee(20);
}
}
@@ -0,0 +1,66 @@
package com.baeldung.timer;
import com.jayway.awaitility.Awaitility;
import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
public class AutomaticTimerBeanIntegrationTest {
//the @AutomaticTimerBean has a method called every 10 seconds
//testing the difference ==> 100000
final static long TIMEOUT = 10000l;
//the tolerance accepted , so if between two consecutive calls there has to be at least 9 or max 11 seconds.
//because the timer service is not intended for real-time applications so it will not be exactly 10 seconds
final static long TOLERANCE = 1000l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
//only @AutomaticTimerBean is deployed not the other timers
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, AutomaticTimerBean.class);
}
@Test
public void should_receive_two_pings() {
Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
//the test will wait here until two events are triggered
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
long delay = secondEvent.getTime() - firstEvent.getTime();
System.out.println("Actual timeout = " + delay);
//ensure that the delay between the events is more or less 10 seconds (no real time precision)
assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}
@@ -0,0 +1,56 @@
package com.baeldung.timer;
import com.jayway.awaitility.Awaitility;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
public class ProgrammaticAtFixedRateTimerBeanIntegrationTest {
final static long TIMEOUT = 1000;
final static long TOLERANCE = 500l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticAtFixedRateTimerBean.class);
}
@Test
public void should_receive_ten_pings() {
Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(10));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
long delay = secondEvent.getTime() - firstEvent.getTime();
System.out.println("Actual timeout = " + delay);
assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}
@@ -0,0 +1,53 @@
package com.baeldung.timer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
public class ProgrammaticTimerBeanIntegrationTest {
final static long TIMEOUT = 5000l;
final static long TOLERANCE = 1000l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticTimerBean.class);
}
@Test
public void should_receive_two_pings() {
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
long delay = secondEvent.getTime() - firstEvent.getTime();
System.out.println("Actual timeout = " + delay);
assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}
@@ -0,0 +1,61 @@
package com.baeldung.timer;
import com.jayway.awaitility.Awaitility;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
public class ProgrammaticWithFixedDelayTimerBeanIntegrationTest {
final static long TIMEOUT = 15000l;
final static long TOLERANCE = 1000l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticWithInitialFixedDelayTimerBean.class);
}
@Test
public void should_receive_two_pings() {
Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
// 10 seconds pause so we get the startTime and it will trigger first event
long startTime = System.currentTimeMillis();
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
long delay = secondEvent.getTime() - startTime;
System.out.println("Actual timeout = " + delay);
//apx 15 seconds = 10 delay + 2 timers (first after a pause of 10 seconds and the next others every 5 seconds)
assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}
@@ -0,0 +1,67 @@
package com.baeldung.timer;
import com.jayway.awaitility.Awaitility;
import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
public class ScheduleTimerBeanIntegrationTest {
private final static long TIMEOUT = 5000l;
private final static long TOLERANCE = 1000l;
@Inject TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven
.resolver()
.loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity()
.asFile();
return ShrinkWrap
.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ScheduleTimerBean.class);
}
@Test
public void should_receive_three_pings() {
Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(3));
TimerEvent firstEvent = timerEventListener
.getEvents()
.get(0);
TimerEvent secondEvent = timerEventListener
.getEvents()
.get(1);
TimerEvent thirdEvent = timerEventListener
.getEvents()
.get(2);
long delay = secondEvent.getTime() - firstEvent.getTime();
assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
delay = thirdEvent.getTime() - secondEvent.getTime();
assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}
@@ -0,0 +1,30 @@
package com.baeldung.timer;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
class WithinWindowMatcher extends BaseMatcher<Long> {
private final long timeout;
private final long tolerance;
public WithinWindowMatcher(long timeout, long tolerance) {
this.timeout = timeout;
this.tolerance = tolerance;
}
@Override
public boolean matches(Object item) {
final Long actual = (Long) item;
return Math.abs(actual - timeout) < tolerance;
}
@Override
public void describeTo(Description description) {
//To change body of implemented methods use File | Settings | File Templates.
}
public static Matcher<Long> withinWindow(final long timeout, final long tolerance) {
return new WithinWindowMatcher(timeout, tolerance);
}
}