From 1bf70b8f088ca90d644ca5d9e900648185718cf9 Mon Sep 17 00:00:00 2001 From: dhruba619 Date: Sun, 5 Feb 2017 00:46:21 +0530 Subject: [PATCH 01/33] BAEL-183 JUnit vs TestNG --- .../test/comparison/DependentTests.java | 46 ++++++++ .../comparison/MyParameterisedUnitTest.java | 50 +++++++++ .../comparison/MyParameterisedUnitTestNg.java | 80 ++++++++++++++ .../com/baeldung/test/comparison/MyTest1.java | 12 +++ .../com/baeldung/test/comparison/MyTest2.java | 10 ++ .../com/baeldung/test/comparison/MyTest5.java | 13 +++ .../test/comparison/RegistrationTest.java | 11 ++ .../baeldung/test/comparison/SignInTest.java | 12 +++ .../test/comparison/SummationServiceTest.java | 60 +++++++++++ .../SummationServiceTestTestNg.java | 101 ++++++++++++++++++ .../baeldung/test/comparison/TimeOutTest.java | 10 ++ .../src/test/resources/parameterised_test.xml | 10 ++ core-java/src/test/resources/test_group.xml | 13 +++ core-java/src/test/resources/test_suite.xml | 9 ++ 14 files changed, 437 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/MyTest1.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/MyTest2.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/MyTest5.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/RegistrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/SignInTest.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTest.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java create mode 100644 core-java/src/test/resources/parameterised_test.xml create mode 100644 core-java/src/test/resources/test_group.xml create mode 100644 core-java/src/test/resources/test_suite.xml diff --git a/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java b/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java new file mode 100644 index 0000000000..6b0394a368 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java @@ -0,0 +1,46 @@ +package com.baeldung.test.comparison; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class DependentTests { + + private EmailValidator emailValidator; + private LoginValidator loginValidator; + private String validEmail = "abc@qwe.com"; + + @BeforeClass + public void setup(){ + emailValidator = new EmailValidator(); + loginValidator = new LoginValidator(); + } + + @Test + public void validEmailTest() { + boolean valid = emailValidator.validate(validEmail); + Assert.assertEquals(valid, true); + } + + @Test(dependsOnMethods={"validEmailTest"}) + public void validateLogin() { + boolean valid = loginValidator.validate(); + Assert.assertEquals(valid, true); + } +} + +class EmailValidator{ + + public boolean validate(String validEmail) { + return true; + } + +} + +class LoginValidator{ + + public boolean validate() { + return true; + } + +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java new file mode 100644 index 0000000000..9e63956556 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.test.comparison; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(value = Parameterized.class) +public class MyParameterisedUnitTest { + + private String name; + private NameCheck nameCheck; + + @Before + public void initialSetup() { + nameCheck = new NameCheck(); + } + + public MyParameterisedUnitTest(String myName) { + this.name = myName; + } + + @Parameters + public static Collection data() { + Object[][] data + = new Object[][] { { "Peter" }, { "Sam" }, { "Tim" }, { "Lucy" } }; + return Arrays.asList(data); + } + + @Test + public void pushNameTest() { + boolean valid = nameCheck.nameCheck(name); + Assert.assertEquals(valid, true); + } +} + +class NameCheck{ + + public boolean nameCheck(String name) { + if(name.length()>0) + return true; + return false; + } + +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java new file mode 100644 index 0000000000..d5e4465b3d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java @@ -0,0 +1,80 @@ +package com.baeldung.test.comparison; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +public class MyParameterisedUnitTestNg { + + private PrimeNumberCheck primeNumberChecker; + + @BeforeClass + public void intialSetup(){ + primeNumberChecker = new PrimeNumberCheck(); + } + + @Test(enabled=false) + @Parameters({"num","expectedResult"}) + public void parameterCheckTest(int number,boolean expectedResult) { + Assert.assertEquals(expectedResult, + primeNumberChecker.validate(number)); + } + + @DataProvider(name = "test1") + public static Object[][] primeNumbers() { + return new Object[][] { + {2, true}, {6, false}, {19, true}, {22, false}, {23, true}}; + } + + @Test(dataProvider = "test1") + public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) { + Assert.assertEquals(expectedResult, + primeNumberChecker.validate(inputNumber)); + } + + @Test(dataProvider = "myDataProvider") + public void parameterCheckTest(User user) { + Assert.assertEquals("sam",user.getName()); + Assert.assertEquals(12,user.getAge()); + } + + @DataProvider(name = "myDataProvider") + public Object[][] parameterProvider() { + User usr = new User(); + usr.setName("sam"); + usr.setAge(12); + return new Object[][]{{usr}}; + } + +} + +class PrimeNumberCheck{ + + public Object validate(int number) { + for(int i=2;i numbers; + + @BeforeClass + public static void initialize() { + numbers = new ArrayList<>(); + } + + @AfterClass + public static void tearDown() { + numbers = null; + } + + @Before + public void runBeforeEachTest() { + numbers.add(1); + numbers.add(2); + numbers.add(3); + } + + @After + public void runAfterEachTest() { + numbers.clear(); + } + + @Test + public void givenNumbers_sumEquals_thenCorrect() { + int sum = 0; + for (int num : numbers) + sum += num; + Assert.assertEquals(6, sum); + } + + @Ignore + @Test + public void givenEmptyList_sumEqualsZero_thenCorrect(){ + int sum = 0; + for (int num : numbers) + sum += num; + Assert.assertEquals(6, sum); + } + + @Test(expected = ArithmeticException.class) + public void calculateWithException() { + int i = 1/0; + } +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java b/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java new file mode 100644 index 0000000000..aecc790374 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java @@ -0,0 +1,101 @@ +package com.baeldung.test.comparison; + +import java.util.ArrayList; +import java.util.List; + +import org.testng.Assert; +import org.testng.TestNG; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class SummationServiceTestTestNg extends TestNG{ + + private List numbers; + + private int testCount=0; + + @BeforeClass + public void initialize() { + numbers = new ArrayList<>(); + } + + @AfterClass + public void tearDown() { + numbers = null; + } + + @BeforeMethod + public void runBeforeEachTest() { + testCount++; + } + + @AfterMethod + public void runAfterEachTest() { + + } + + @BeforeGroups("negative_tests") + public void runBeforeEachNegativeGroup() { + numbers.clear(); + } + + @BeforeGroups("regression") + public void runBeforeEachRegressionGroup() { + numbers.add(-11); + numbers.add(2); + } + + @BeforeGroups("positive_tests") + public void runBeforeEachPositiveGroup() { + numbers.add(1); + numbers.add(2); + numbers.add(3); + } + + @AfterGroups("positive_tests,regression,negative_tests") + public void runAfterEachGroup() { + numbers.clear(); + } + + @Test(groups="positive_tests",enabled=false) + public void givenNumbers_sumEquals_thenCorrect() { + int sum = 0; + for (int num : numbers) + sum += num; + Assert.assertEquals(sum, 6); + } + + @Test(groups="negative_tests") + public void givenEmptyList_sumEqualsZero_thenCorrect(){ + int sum = 0; + for (int num : numbers) + sum += num; + Assert.assertEquals(0, sum); + } + + @Test(groups = "regression") + public void givenNegativeNumber_sumLessthanZero_thenCorrect() { + int sum = 0; + for (int num : numbers) + sum += num; + System.out.println(sum); + Assert.assertTrue(sum<0);; + } + + @Test(groups="sanity") + public void givenNumbers_doSum(){ + + } + + @Test(expectedExceptions = ArithmeticException.class) + public void calculateWithException() { + int i = 1/0; + } + + +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java b/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java new file mode 100644 index 0000000000..baf2db9521 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java @@ -0,0 +1,10 @@ +package com.baeldung.test.comparison; + +import org.testng.annotations.Test; + +public class TimeOutTest { + @Test(timeOut = 1000,enabled=false) + public void testInfinity() { + while (true); + } +} diff --git a/core-java/src/test/resources/parameterised_test.xml b/core-java/src/test/resources/parameterised_test.xml new file mode 100644 index 0000000000..69a2c60460 --- /dev/null +++ b/core-java/src/test/resources/parameterised_test.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/core-java/src/test/resources/test_group.xml b/core-java/src/test/resources/test_group.xml new file mode 100644 index 0000000000..0c9a6c73df --- /dev/null +++ b/core-java/src/test/resources/test_group.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java/src/test/resources/test_suite.xml b/core-java/src/test/resources/test_suite.xml new file mode 100644 index 0000000000..36305aa5fc --- /dev/null +++ b/core-java/src/test/resources/test_suite.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file From 70cc228f1e5761c724bbc86dc6665a99a312320b Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 11 Feb 2017 16:53:26 +0100 Subject: [PATCH 02/33] BAEL-12 advanced http client --- httpclient/pom.xml | 13 +- .../HttpClientAdvancedConfiguration.java | 137 ++++++++++++++++++ 2 files changed, 148 insertions(+), 2 deletions(-) create mode 100644 httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java diff --git a/httpclient/pom.xml b/httpclient/pom.xml index be0daae995..eec705b224 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung httpclient @@ -113,6 +114,13 @@ ${mockito.version} test + + com.github.tomakehurst + wiremock + ${wiremock.version} + test + + @@ -145,7 +153,7 @@ **/*LiveTest.java - + @@ -202,6 +210,7 @@ 1.3 4.12 1.10.19 + 2.5.1 4.4.5 4.5.2 diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java new file mode 100644 index 0000000000..5bb86de2ac --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java @@ -0,0 +1,137 @@ +package org.baeldung.httpclient.advancedconfig; + + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.DefaultProxyRoutePlanner; +import org.junit.Rule; +import org.junit.Test; + +import java.io.IOException; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.junit.Assert.assertEquals; + +public class HttpClientAdvancedConfiguration { + + @Rule + public WireMockRule serviceMock = new WireMockRule(8089); + + @Rule + public WireMockRule proxyMock = new WireMockRule(8090); + + @Test + public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException { + //given + serviceMock.stubFor(get(urlEqualTo("/detail")) + .withHeader("User-Agent", equalTo("BaeldungAgent/1.0")) + .willReturn(aResponse() + .withStatus(200))); + + String userAgent = "BaeldungAgent/1.0"; + HttpClient httpClient = HttpClients.createDefault(); + final HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); + httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent); + + //when + HttpResponse response = httpClient.execute(httpGet); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + } + + @Test + public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException { + //given + serviceMock.stubFor(post(urlEqualTo("/person")) + .withHeader("Content-Type", equalTo("application/xml")) + .withRequestBody(equalTo("1")) + .willReturn(aResponse() + .withStatus(200))); + + HttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost("http://localhost:8089/person"); + httpPost.setHeader("Content-Type", "application/xml"); + StringEntity xmlEntity = new StringEntity("1"); + httpPost.setEntity(xmlEntity); + + //when + HttpResponse response = httpClient.execute(httpPost); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + + } + + @Test + public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { + //given + proxyMock.stubFor(get(urlMatching(".*")) + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + + serviceMock.stubFor(get(urlEqualTo("/private")) + .willReturn(aResponse().withStatus(200))); + + + HttpHost proxy = new HttpHost("localhost", 8090); + DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + HttpClient httpclient = HttpClients.custom() + .setRoutePlanner(routePlanner) + .build(); + + //when + final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); + HttpResponse response = httpclient.execute(httpGet); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + proxyMock.verify(getRequestedFor(urlEqualTo("/private"))); + serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); + } + + @Test + public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { + //given + proxyMock.stubFor(get(urlMatching(".*")) + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + + serviceMock.stubFor(get(urlEqualTo("/private/username_admin/secret_password")) + .willReturn(aResponse().withStatus(200))); + + + HttpHost proxy = new HttpHost("localhost", 8090); + DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(new AuthScope(proxy), + new UsernamePasswordCredentials("username_admin", "secret_password")); + + HttpClient httpclient = HttpClients.custom() + .setRoutePlanner(routePlanner) + .setDefaultCredentialsProvider(credentialsProvider) + .build(); + + + //when + final HttpGet httpGet = new HttpGet("http://localhost:8089/private/username_admin/secret_password"); + HttpResponse response = httpclient.execute(httpGet); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + proxyMock.verify(getRequestedFor(urlEqualTo("/private/username_admin/secret_password"))); + serviceMock.verify(getRequestedFor(urlEqualTo("/private/username_admin/secret_password"))); + } + + +} From 34bfeed011ad8429d8a72071733a1040e9cc1eac Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 11 Feb 2017 17:15:08 +0100 Subject: [PATCH 03/33] BAEL-12 end-to-end test case for auth proxy --- .../HttpClientAdvancedConfiguration.java | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java index 5bb86de2ac..1bb176876c 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java @@ -7,11 +7,15 @@ import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.AuthCache; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.entity.StringEntity; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; @@ -103,20 +107,32 @@ public class HttpClientAdvancedConfiguration { @Test public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { //given - proxyMock.stubFor(get(urlMatching(".*")) + proxyMock.stubFor(get(urlMatching("/private")) .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); - - serviceMock.stubFor(get(urlEqualTo("/private/username_admin/secret_password")) + serviceMock.stubFor(get(urlEqualTo("/private")) .willReturn(aResponse().withStatus(200))); HttpHost proxy = new HttpHost("localhost", 8090); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + // Client credentials CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("username_admin", "secret_password")); + + // Create AuthCache instance + AuthCache authCache = new BasicAuthCache(); + + // Generate BASIC scheme object and add it to the local auth cache + BasicScheme basicAuth = new BasicScheme(); + authCache.put(proxy, basicAuth); + HttpClientContext context = HttpClientContext.create(); + context.setCredentialsProvider(credentialsProvider); + context.setAuthCache(authCache); + + HttpClient httpclient = HttpClients.custom() .setRoutePlanner(routePlanner) .setDefaultCredentialsProvider(credentialsProvider) @@ -124,13 +140,13 @@ public class HttpClientAdvancedConfiguration { //when - final HttpGet httpGet = new HttpGet("http://localhost:8089/private/username_admin/secret_password"); - HttpResponse response = httpclient.execute(httpGet); + final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); + HttpResponse response = httpclient.execute(httpGet, context); //then assertEquals(response.getStatusLine().getStatusCode(), 200); - proxyMock.verify(getRequestedFor(urlEqualTo("/private/username_admin/secret_password"))); - serviceMock.verify(getRequestedFor(urlEqualTo("/private/username_admin/secret_password"))); + proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic"))); + serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); } From 23696a24bd69f0febb433d3ef9e0224ec6e26ebb Mon Sep 17 00:00:00 2001 From: dhruba619 Date: Sat, 11 Feb 2017 23:57:50 +0530 Subject: [PATCH 04/33] BAEL-183 Updated after review --- .../test/comparison/DependentTests.java | 62 +++---- .../test/comparison/DivisibilityTest.java | 21 +++ .../comparison/MyParameterisedUnitTest.java | 29 ++-- .../comparison/MyParameterisedUnitTestNg.java | 129 +++++++-------- .../com/baeldung/test/comparison/MyTest1.java | 12 -- .../com/baeldung/test/comparison/MyTest2.java | 10 -- .../test/comparison/RegistrationTest.java | 8 +- .../baeldung/test/comparison/SignInTest.java | 10 +- .../test/comparison/StringCaseTest.java | 22 +++ .../{MyTest5.java => SuiteTest.java} | 7 +- .../test/comparison/SummationServiceTest.java | 39 +++-- .../SummationServiceTestTestNg.java | 151 +++++++++--------- .../baeldung/test/comparison/TimeOutTest.java | 9 +- .../test/java/temp/SummationServiceTest.java | 49 ++++++ 14 files changed, 309 insertions(+), 249 deletions(-) create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java delete mode 100644 core-java/src/test/java/com/baeldung/test/comparison/MyTest1.java delete mode 100644 core-java/src/test/java/com/baeldung/test/comparison/MyTest2.java create mode 100644 core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java rename core-java/src/test/java/com/baeldung/test/comparison/{MyTest5.java => SuiteTest.java} (57%) create mode 100644 core-java/src/test/java/temp/SummationServiceTest.java diff --git a/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java b/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java index 6b0394a368..3ef4949067 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java +++ b/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java @@ -5,42 +5,42 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class DependentTests { - - private EmailValidator emailValidator; - private LoginValidator loginValidator; - private String validEmail = "abc@qwe.com"; - - @BeforeClass - public void setup(){ - emailValidator = new EmailValidator(); - loginValidator = new LoginValidator(); - } - - @Test - public void validEmailTest() { - boolean valid = emailValidator.validate(validEmail); - Assert.assertEquals(valid, true); - } - @Test(dependsOnMethods={"validEmailTest"}) - public void validateLogin() { - boolean valid = loginValidator.validate(); - Assert.assertEquals(valid, true); - } + private EmailValidator emailValidator; + private LoginValidator loginValidator; + private String validEmail = "abc@qwe.com"; + + @BeforeClass + public void setup() { + emailValidator = new EmailValidator(); + loginValidator = new LoginValidator(); + } + + @Test + public void givenEmail_ifValid_thenTrue() { + boolean valid = emailValidator.validate(validEmail); + Assert.assertEquals(valid, true); + } + + @Test(dependsOnMethods = { "givenEmail_ifValid_thenTrue" }) + public void givenValidEmail_whenLoggedin_thenTrue() { + boolean valid = loginValidator.validate(); + Assert.assertEquals(valid, true); + } } -class EmailValidator{ +class EmailValidator { + + public boolean validate(String validEmail) { + return true; + } - public boolean validate(String validEmail) { - return true; - } - } -class LoginValidator{ +class LoginValidator { + + public boolean validate() { + return true; + } - public boolean validate() { - return true; - } - } diff --git a/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java b/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java new file mode 100644 index 0000000000..9ae13f5934 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java @@ -0,0 +1,21 @@ +package com.baeldung.test.comparison; + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class DivisibilityTest { + + private static int number; + + @BeforeClass + public static void setup() { + number = 40; + } + + @Test + public void givenNumber_whenDivisiblebyTwo_thenCorrect() { + assertEquals(number % 2, 0); + } +} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java index 9e63956556..3372bbb577 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java +++ b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java @@ -12,39 +12,38 @@ import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class MyParameterisedUnitTest { - + private String name; private NameCheck nameCheck; - + @Before public void initialSetup() { nameCheck = new NameCheck(); } - + public MyParameterisedUnitTest(String myName) { this.name = myName; } - + @Parameters public static Collection data() { - Object[][] data - = new Object[][] { { "Peter" }, { "Sam" }, { "Tim" }, { "Lucy" } }; + Object[][] data = new Object[][] { { "Peter" }, { "Sam" }, { "Tim" }, { "Lucy" } }; return Arrays.asList(data); } - + @Test - public void pushNameTest() { + public void givenName_whenValidLength_thenTrue() { boolean valid = nameCheck.nameCheck(name); Assert.assertEquals(valid, true); } } -class NameCheck{ +class NameCheck { + + public boolean nameCheck(String name) { + if (name.length() > 0) + return true; + return false; + } - public boolean nameCheck(String name) { - if(name.length()>0) - return true; - return false; - } - } diff --git a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java index d5e4465b3d..4096c3fb6f 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java +++ b/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java @@ -7,74 +7,75 @@ import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class MyParameterisedUnitTestNg { - - private PrimeNumberCheck primeNumberChecker; - - @BeforeClass - public void intialSetup(){ - primeNumberChecker = new PrimeNumberCheck(); - } - - @Test(enabled=false) - @Parameters({"num","expectedResult"}) - public void parameterCheckTest(int number,boolean expectedResult) { - Assert.assertEquals(expectedResult, - primeNumberChecker.validate(number)); - } - - @DataProvider(name = "test1") - public static Object[][] primeNumbers() { - return new Object[][] { - {2, true}, {6, false}, {19, true}, {22, false}, {23, true}}; - } - - @Test(dataProvider = "test1") - public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) { - Assert.assertEquals(expectedResult, - primeNumberChecker.validate(inputNumber)); - } - - @Test(dataProvider = "myDataProvider") - public void parameterCheckTest(User user) { - Assert.assertEquals("sam",user.getName()); - Assert.assertEquals(12,user.getAge()); - } - - @DataProvider(name = "myDataProvider") - public Object[][] parameterProvider() { - User usr = new User(); - usr.setName("sam"); - usr.setAge(12); - return new Object[][]{{usr}}; - } + + private PrimeNumberCheck primeNumberChecker; + + @BeforeClass + public void intialSetup() { + primeNumberChecker = new PrimeNumberCheck(); + } + + @Test(enabled = false) + @Parameters({ "num", "expectedResult" }) + public void givenNumber_ifPrime_thenCorrect(int number, boolean expectedResult) { + Assert.assertEquals(expectedResult, primeNumberChecker.validate(number)); + } + + @DataProvider(name = "test1") + public static Object[][] primeNumbers() { + return new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false }, { 23, true } }; + } + + @Test(dataProvider = "test1") + public void givenNumber_whenPrime_thenCorrect(Integer inputNumber, Boolean expectedResult) { + Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); + } + + @Test(dataProvider = "myDataProvider") + public void parameterCheckTest(User user) { + Assert.assertEquals("sam", user.getName()); + Assert.assertEquals(12, user.getAge()); + } + + @DataProvider(name = "myDataProvider") + public Object[][] parameterProvider() { + User usr = new User(); + usr.setName("sam"); + usr.setAge(12); + return new Object[][] { { usr } }; + } } -class PrimeNumberCheck{ +class PrimeNumberCheck { + + public Object validate(int number) { + for (int i = 2; i < number; i++) { + if (number % i == 0) + return false; + } + return true; + } - public Object validate(int number) { - for(int i=2;i numbers; - + private static List numbers; + @BeforeClass public static void initialize() { numbers = new ArrayList<>(); } - + @AfterClass public static void tearDown() { numbers = null; } - + @Before public void runBeforeEachTest() { numbers.add(1); numbers.add(2); numbers.add(3); } - + @After public void runAfterEachTest() { numbers.clear(); } - + @Test public void givenNumbers_sumEquals_thenCorrect() { - int sum = 0; - for (int num : numbers) - sum += num; + int sum = numbers.stream() + .reduce(0, Integer::sum); Assert.assertEquals(6, sum); } - + @Ignore @Test - public void givenEmptyList_sumEqualsZero_thenCorrect(){ - int sum = 0; - for (int num : numbers) - sum += num; - Assert.assertEquals(6, sum); - } - - @Test(expected = ArithmeticException.class) - public void calculateWithException() { - int i = 1/0; + public void givenEmptyList_sumEqualsZero_thenCorrect() { + int sum = numbers.stream() + .reduce(0, Integer::sum); + Assert.assertEquals(6, sum); + } + + @Test(expected = ArithmeticException.class) + public void givenNumber_whenThrowsException_thenCorrect() { + int i = 1 / 0; } } diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java b/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java index aecc790374..fb02f28d06 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java +++ b/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java @@ -13,89 +13,82 @@ import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -public class SummationServiceTestTestNg extends TestNG{ - - private List numbers; - - private int testCount=0; - - @BeforeClass - public void initialize() { - numbers = new ArrayList<>(); - } +public class SummationServiceTestTestNg extends TestNG { - @AfterClass - public void tearDown() { - numbers = null; - } + private List numbers; - @BeforeMethod - public void runBeforeEachTest() { - testCount++; - } + private int testCount = 0; - @AfterMethod - public void runAfterEachTest() { - - } - - @BeforeGroups("negative_tests") - public void runBeforeEachNegativeGroup() { - numbers.clear(); - } - - @BeforeGroups("regression") - public void runBeforeEachRegressionGroup() { - numbers.add(-11); - numbers.add(2); - } - - @BeforeGroups("positive_tests") - public void runBeforeEachPositiveGroup() { - numbers.add(1); - numbers.add(2); - numbers.add(3); - } - - @AfterGroups("positive_tests,regression,negative_tests") - public void runAfterEachGroup() { - numbers.clear(); - } - - @Test(groups="positive_tests",enabled=false) + @BeforeClass + public void initialize() { + numbers = new ArrayList<>(); + } + + @AfterClass + public void tearDown() { + numbers = null; + } + + @BeforeMethod + public void runBeforeEachTest() { + testCount++; + } + + @AfterMethod + public void runAfterEachTest() { + + } + + @BeforeGroups("negative_tests") + public void runBeforeEachNegativeGroup() { + numbers.clear(); + } + + @BeforeGroups("regression") + public void runBeforeEachRegressionGroup() { + numbers.add(-11); + numbers.add(2); + } + + @BeforeGroups("positive_tests") + public void runBeforeEachPositiveGroup() { + numbers.add(1); + numbers.add(2); + numbers.add(3); + } + + @AfterGroups("positive_tests,regression,negative_tests") + public void runAfterEachGroup() { + numbers.clear(); + } + + @Test(groups = "positive_tests", enabled = false) public void givenNumbers_sumEquals_thenCorrect() { - int sum = 0; - for (int num : numbers) - sum += num; + int sum = numbers.stream().reduce(0, Integer::sum); Assert.assertEquals(sum, 6); } - - @Test(groups="negative_tests") - public void givenEmptyList_sumEqualsZero_thenCorrect(){ - int sum = 0; - for (int num : numbers) - sum += num; - Assert.assertEquals(0, sum); - } - - @Test(groups = "regression") - public void givenNegativeNumber_sumLessthanZero_thenCorrect() { - int sum = 0; - for (int num : numbers) - sum += num; - System.out.println(sum); - Assert.assertTrue(sum<0);; - } - - @Test(groups="sanity") - public void givenNumbers_doSum(){ - - } - - @Test(expectedExceptions = ArithmeticException.class) - public void calculateWithException() { - int i = 1/0; - } - - + + @Test(groups = "negative_tests") + public void givenEmptyList_sumEqualsZero_thenCorrect() { + int sum = numbers.stream().reduce(0, Integer::sum); + Assert.assertEquals(0, sum); + } + + @Test(groups = "regression") + public void givenNegativeNumber_sumLessthanZero_thenCorrect() { + int sum = numbers.stream().reduce(0, Integer::sum); + Assert.assertTrue(sum < 0); + ; + } + + @Test(groups = "sanity") + public void givenNumbers_doSum() { + + } + + @Test(expectedExceptions = ArithmeticException.class) + public void givenNumber_whenThrowsException_thenCorrect() { + int i = 1 / 0; + } + } diff --git a/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java b/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java index baf2db9521..6e06132009 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java +++ b/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java @@ -3,8 +3,9 @@ package com.baeldung.test.comparison; import org.testng.annotations.Test; public class TimeOutTest { - @Test(timeOut = 1000,enabled=false) - public void testInfinity() { - while (true); - } + @Test(timeOut = 1000, enabled = false) + public void givenExecution_takeMoreTime_thenFail() { + while (true) + ; + } } diff --git a/core-java/src/test/java/temp/SummationServiceTest.java b/core-java/src/test/java/temp/SummationServiceTest.java new file mode 100644 index 0000000000..3c2d39f5dd --- /dev/null +++ b/core-java/src/test/java/temp/SummationServiceTest.java @@ -0,0 +1,49 @@ +package temp; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import junit.framework.Assert; + +public class SummationServiceTest { + + private static List numbers; + + @BeforeClass + public static void initialize() { + numbers = new ArrayList<>(); + } + + @AfterClass + public static void tearDown() { + numbers = null; + } + + @Before + public void runBeforeEachTest() { + numbers.add(1); + numbers.add(2); + numbers.add(3); + } + + @After + public void runAfterEachTest() { + numbers.clear(); + } + + @Test + public void givenNumbers_sumEquals_thenCorrect() { + int sum = 0; + for (int num : numbers) + sum += num; + assertEquals(6, sum); + } +} \ No newline at end of file From 4b728ec65b1314e54ae6668557bcbb425fb72cbc Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sun, 12 Feb 2017 13:40:00 +0530 Subject: [PATCH 05/33] Delete JoinerSplitterTest.java (#1160) --- .../baeldung/stream/JoinerSplitterTest.java | 65 ------------------- 1 file changed, 65 deletions(-) delete mode 100644 core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java diff --git a/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java b/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java deleted file mode 100644 index b995976b2c..0000000000 --- a/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.stream; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.baeldung.streamApi.JoinerSplitter; - -public class JoinerSplitterTest { - - @Test - public void provided_array_convert_to_stream_and_convert_to_string() { - - String[] programming_languages = {"java", "python", "nodejs", "ruby"}; - - String expectation = "java,python,nodejs,ruby"; - - String result = JoinerSplitter.join(programming_languages); - assertEquals(result, expectation); - } - - @Test - public void provided_array_convert_to_stream_and_convert_to_prefixPostfixString() { - String[] programming_languages = {"java", "python", - "nodejs", "ruby"}; - String expectation = "[java,python,nodejs,ruby]"; - - String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages); - assertEquals(result, expectation); - } - - @Test - public void provided_string_convert_to_stream_and_convert_to_listOfString() { - String programming_languages = "java,python,nodejs,ruby"; - - List expectation = new ArrayList(); - expectation.add("java"); - expectation.add("python"); - expectation.add("nodejs"); - expectation.add("ruby"); - - List result = JoinerSplitter.split(programming_languages); - - assertEquals(result, expectation); - } - - @Test - public void provided_string_convert_to_stream_and_convert_to_listOfChar() { - String programming_languages = "java,python,nodejs,ruby"; - - List expectation = new ArrayList(); - char[] charArray = programming_languages.toCharArray(); - for (char c : charArray) { - expectation.add(c); - } - - List result = JoinerSplitter.splitToListOfChar(programming_languages); - assertEquals(result, expectation); - - } - -} From 25dc6bc81c8dbc8e6d808d62025dc8bf77304d31 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sun, 12 Feb 2017 13:41:25 +0530 Subject: [PATCH 06/33] Delete JoinerSplitter.java (#1161) --- .../baeldung/streamApi/JoinerSplitter.java | 40 ------------------- 1 file changed, 40 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java diff --git a/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java b/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java deleted file mode 100644 index 52ffc61799..0000000000 --- a/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.streamApi; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class JoinerSplitter { - - public static String join(String[] arrayOfString) { - return Arrays - .asList(arrayOfString) - .stream() - .map(x -> x) - .collect(Collectors.joining(",")); - } - - public static String joinWithPrefixPostFix(String[] arrayOfString) { - return Arrays - .asList(arrayOfString) - .stream() - .map(x -> x) - .collect(Collectors.joining(",", "[", "]")); - } - - public static List split(String str) { - return Stream - .of(str.split(",")) - .map(elem -> new String(elem)) - .collect(Collectors.toList()); - } - - public static List splitToListOfChar(String str) { - return str - .chars() - .mapToObj(item -> (char) item) - .collect(Collectors.toList()); - } - -} From 4aaefd39df187bd67191c62ac2d7bd0ecc0b83ee Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sun, 12 Feb 2017 14:20:49 +0530 Subject: [PATCH 07/33] changing package structure (#1157) * rest with spark java * 4 * Update Application.java * indentation changes * spring @requestmapping shortcuts * removing spring requestmapping and pushing spring-mvc-java * Joining/Splitting Strings with Java and Stream API * adding more join/split functionality * changing package name * testcase change --- core-java/0.5967303215007616 | 0 core-java/0.9252611327674576 | 0 .../com/baeldung/string/JoinerSplitter.java | 36 ++++++++++ .../baeldung/string/JoinerSplitterTest.java | 65 +++++++++++++++++++ 4 files changed, 101 insertions(+) create mode 100644 core-java/0.5967303215007616 create mode 100644 core-java/0.9252611327674576 create mode 100644 core-java/src/main/java/com/baeldung/string/JoinerSplitter.java create mode 100644 core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java diff --git a/core-java/0.5967303215007616 b/core-java/0.5967303215007616 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/0.9252611327674576 b/core-java/0.9252611327674576 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/src/main/java/com/baeldung/string/JoinerSplitter.java b/core-java/src/main/java/com/baeldung/string/JoinerSplitter.java new file mode 100644 index 0000000000..085be66801 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/string/JoinerSplitter.java @@ -0,0 +1,36 @@ +package com.baeldung.string; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class JoinerSplitter { + + public static String join ( String[] arrayOfString ) { + return Arrays.asList(arrayOfString) + .stream() + .map(x -> x) + .collect(Collectors.joining(",")); + } + + public static String joinWithPrefixPostFix ( String[] arrayOfString ) { + return Arrays.asList(arrayOfString) + .stream() + .map(x -> x) + .collect(Collectors.joining(",","[","]")); + } + + public static List split ( String str ) { + return Stream.of(str.split(",")) + .map (elem -> new String(elem)) + .collect(Collectors.toList()); + } + + public static List splitToListOfChar ( String str ) { + return str.chars() + .mapToObj(item -> (char) item) + .collect(Collectors.toList()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java b/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java new file mode 100644 index 0000000000..303296cbc6 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java @@ -0,0 +1,65 @@ +package com.baeldung.string; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.baeldung.string.JoinerSplitter; + +public class JoinerSplitterTest { + + @Test + public void provided_array_convert_to_stream_and_convert_to_string() { + + String[] programming_languages = {"java", "python", "nodejs", "ruby"}; + + String expectation = "java,python,nodejs,ruby"; + + String result = JoinerSplitter.join(programming_languages); + assertEquals(result, expectation); + } + + @Test + public void provided_array_convert_to_stream_and_convert_to_prefixPostfix() { + String[] programming_languages = {"java", "python", + "nodejs", "ruby"}; + String expectation = "[java,python,nodejs,ruby]"; + + String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages); + assertEquals(result, expectation); + } + + @Test + public void provided_string_convert_to_stream_and_convert_to_listOfString() { + String programming_languages = "java,python,nodejs,ruby"; + + List expectation = new ArrayList(); + expectation.add("java"); + expectation.add("python"); + expectation.add("nodejs"); + expectation.add("ruby"); + + List result = JoinerSplitter.split(programming_languages); + + assertEquals(result, expectation); + } + + @Test + public void provided_string_convert_to_stream_and_convert_to_listOfChar() { + String programming_languages = "java,python,nodejs,ruby"; + + List expectation = new ArrayList(); + char[] charArray = programming_languages.toCharArray(); + for (char c : charArray) { + expectation.add(c); + } + + List result = JoinerSplitter.splitToListOfChar(programming_languages); + assertEquals(result, expectation); + + } + +} From f772286896a1082fc662e91659a4f335c1b6101c Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sun, 12 Feb 2017 10:22:25 +0100 Subject: [PATCH 08/33] BAEL-669 test of an infinite stream (#1126) * BAEL-669 test of an infinite stream * BAEL-699 example of custom type infinite stream * BAEL-699 do..while stream way * BAEL-669 generate stream of random uuids --- .../com/baeldung/stream/InfiniteStreams.java | 27 +++++++++++ .../baeldung/stream/InfiniteStreamTest.java | 48 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java create mode 100644 core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java diff --git a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java new file mode 100644 index 0000000000..097b516f8c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java @@ -0,0 +1,27 @@ +package com.baeldung.stream; + + +import java.util.stream.Stream; + +public class InfiniteStreams { + public static void main(String[] args) { + doWhileOldWay(); + + doWhileStreamWay(); + + } + + private static void doWhileOldWay() { + + int i = 0; + while (i < 10) { + System.out.println(i); + i++; + } + } + + private static void doWhileStreamWay() { + Stream integers = Stream.iterate(0, i -> i + 1); + integers.limit(10).forEach(System.out::println); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java b/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java new file mode 100644 index 0000000000..a1537a1735 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java @@ -0,0 +1,48 @@ +package com.baeldung.stream; + + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class InfiniteStreamTest { + + @Test + public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() { + //given + Stream infiniteStream = Stream.iterate(0, i -> i + 2); + + //when + List collect = infiniteStream + .limit(10) + .collect(Collectors.toList()); + + //then + assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)); + } + + @Test + public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() { + //given + Supplier randomUUIDSupplier = UUID::randomUUID; + Stream infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier); + + //when + List randomInts = infiniteStreamOfRandomUUID + .skip(10) + .limit(10) + .collect(Collectors.toList()); + + //then + assertEquals(randomInts.size(), 10); + } + +} From 7a895108f087e25bdf514a5fb23c1505761742bc Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 12 Feb 2017 07:30:32 -0600 Subject: [PATCH 09/33] Update README.MD --- spring-security-mvc-boot/README.MD | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index d59aea97b4..3e789dedad 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -5,3 +5,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [A Custom Security Expression with Spring Security](http://www.baeldung.com/spring-security-create-new-custom-security-expression) - [Custom AccessDecisionVoters in Spring Security](http://www.baeldung.com/spring-security-custom-voter) - [Spring Security: Authentication with a Database-backed UserDetailsService](http://www.baeldung.com/spring-security-authentication-with-a-database) +- [Two Login Pages with Spring Security](http://www.baeldung.com/spring-security-two-login-pages) From c6c3b71ba1fae47d7c76a66e4fc30708a072121d Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 12 Feb 2017 07:32:40 -0600 Subject: [PATCH 10/33] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index cd16935864..341dbdf910 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -57,3 +57,4 @@ - [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) - [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) - [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) +- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm) From 424f55ac484eb2dd662dda7491170eceaad1fb2d Mon Sep 17 00:00:00 2001 From: lor6 Date: Sun, 12 Feb 2017 16:11:55 +0200 Subject: [PATCH 11/33] custom access denied page (#1133) * custom access denied page * fix formatting, remove imports --- .../security/CustomAccessDeniedHandler.java | 30 +++++++++++++++++++ .../java/org/baeldung/spring/MvcConfig.java | 1 + .../baeldung/spring/SecSecurityConfig.java | 10 +++++++ .../src/main/resources/webSecurityConfig.xml | 6 ++++ .../main/webapp/WEB-INF/view/accessDenied.jsp | 15 ++++++++++ .../src/main/webapp/WEB-INF/view/homepage.jsp | 24 ++++++++------- .../src/main/webapp/WEB-INF/web.xml | 7 +++++ 7 files changed, 82 insertions(+), 11 deletions(-) create mode 100644 spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java create mode 100644 spring-security-mvc-login/src/main/webapp/WEB-INF/view/accessDenied.jsp diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java new file mode 100644 index 0000000000..ea4407c5c4 --- /dev/null +++ b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java @@ -0,0 +1,30 @@ +package org.baeldung.security; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.access.AccessDeniedHandler; + +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + public static final Logger LOG = Logger.getLogger(CustomAccessDeniedHandler.class); + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exc) throws IOException, ServletException { + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + if (auth != null) { + LOG.warn("User: " + auth.getName() + " attempted to access the protected URL: " + request.getRequestURI()); + } + + response.sendRedirect(request.getContextPath() + "/accessDenied"); + } + +} diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/MvcConfig.java index 02392df736..b59dbee0cf 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/MvcConfig.java @@ -28,6 +28,7 @@ public class MvcConfig extends WebMvcConfigurerAdapter { registry.addViewController("/login.html"); registry.addViewController("/homepage.html"); registry.addViewController("/admin/adminpage.html"); + registry.addViewController("/accessDenied"); } @Bean diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index ae41a037cd..7331d7bb18 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,5 +1,6 @@ package org.baeldung.spring; +import org.baeldung.security.CustomAccessDeniedHandler; import org.baeldung.security.CustomLogoutSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -8,6 +9,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; @Configuration @@ -53,6 +55,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .logoutUrl("/perform_logout") .deleteCookies("JSESSIONID") .logoutSuccessHandler(logoutSuccessHandler()); + //.and() + //.exceptionHandling().accessDeniedPage("/accessDenied"); + //.exceptionHandling().accessDeniedHandler(accessDeniedHandler()); // @formatter:on } @@ -60,5 +65,10 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public LogoutSuccessHandler logoutSuccessHandler() { return new CustomLogoutSuccessHandler(); } + + @Bean + public AccessDeniedHandler accessDeniedHandler(){ + return new CustomAccessDeniedHandler(); + } } diff --git a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index 9c8fdea9ee..f0fa956934 100644 --- a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -19,10 +19,16 @@ always-use-default-target="true"/> + + + + + + diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/accessDenied.jsp b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/accessDenied.jsp new file mode 100644 index 0000000000..45820cf43d --- /dev/null +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/accessDenied.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + + +Access Denied + + +

Sorry, you do not have permission to view this page.

+ +Click ">here to go back to the Homepage. + + \ No newline at end of file diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/homepage.jsp index 80f27f5466..c9d88cbc9b 100644 --- a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/homepage.jsp @@ -4,21 +4,23 @@ -

This is the body of the sample view

+

This is the body of the sample view

- - This text is only visible to a user -
-
+ + This text is only visible to a user +

+ ">Restricted Admin Page +

+
- - This text is only visible to an admin -
+ + This text is only visible to an admin +
">Admin Page
-
+
+ + ">Logout - ">Logout - \ No newline at end of file diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml index 0a0a340995..eef48ec9b3 100644 --- a/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml @@ -43,8 +43,15 @@ /* + + 403 + /accessDenied + + + + \ No newline at end of file From b279e709893dd4f4928445b1178c18217ddfdbee Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Sun, 12 Feb 2017 18:38:17 +0000 Subject: [PATCH 12/33] CacheLoader tests --- .../baeldung/guava/GuavaCacheLoaderTest.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java new file mode 100644 index 0000000000..2aa2e6140b --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java @@ -0,0 +1,71 @@ +package org.baeldung.guava; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import java.util.Map; +import java.util.concurrent.ExecutionException; + +import static com.google.common.collect.Iterables.cycle; +import static com.google.common.collect.Maps.newHashMap; +import static org.assertj.core.api.Assertions.assertThat; + +public class GuavaCacheLoaderTest { + int callCount = 0; + + @Test + public void givenAMap_whenAddingValues_thenCanTreatThemAsCache() { + Map cache = newHashMap(); + cache.put("foo", "cachedValueForFoo"); + cache.put("bar", "cachedValueForBar"); + + assertThat(cache.get("foo")).isEqualTo("cachedValueForFoo"); + assertThat(cache.get("bar")).isEqualTo("cachedValueForBar"); + } + + @Test + public void givenCacheLoader_whenGettingItemTwice_shouldOnlyCallOnce() throws ExecutionException { + + final LoadingCache loadingCache = CacheBuilder.newBuilder() + .build(new CacheLoader() { + @Override + public String load(final String s) throws Exception { + return slowMethod(s); + } + }); + + String value = loadingCache.get("key"); + value = loadingCache.get("key"); + + assertThat(callCount).isEqualTo(1); + assertThat(value).isEqualTo("key"); + } + + @Test + public void givenCacheLoader_whenRefreshingItem_shouldCallAgain() throws ExecutionException { + + final LoadingCache loadingCache = CacheBuilder.newBuilder() + .build(new CacheLoader() { + @Override + public String load(final String s) throws Exception { + return slowMethod(s); + } + }); + + String value = loadingCache.get("key"); + loadingCache.refresh("key"); + + assertThat(callCount).isEqualTo(2); + assertThat(value).isEqualTo("key"); + } + + private String slowMethod(final String s) { + callCount++; + return s; + } +} From e5597d87cedfe801fbc2a42ca296c4305dd36cbd Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Mon, 13 Feb 2017 01:33:02 +0100 Subject: [PATCH 13/33] BAEL-183 - removing obsolete class --- .../test/java/temp/SummationServiceTest.java | 49 ------------------- 1 file changed, 49 deletions(-) delete mode 100644 core-java/src/test/java/temp/SummationServiceTest.java diff --git a/core-java/src/test/java/temp/SummationServiceTest.java b/core-java/src/test/java/temp/SummationServiceTest.java deleted file mode 100644 index 3c2d39f5dd..0000000000 --- a/core-java/src/test/java/temp/SummationServiceTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package temp; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import junit.framework.Assert; - -public class SummationServiceTest { - - private static List numbers; - - @BeforeClass - public static void initialize() { - numbers = new ArrayList<>(); - } - - @AfterClass - public static void tearDown() { - numbers = null; - } - - @Before - public void runBeforeEachTest() { - numbers.add(1); - numbers.add(2); - numbers.add(3); - } - - @After - public void runAfterEachTest() { - numbers.clear(); - } - - @Test - public void givenNumbers_sumEquals_thenCorrect() { - int sum = 0; - for (int num : numbers) - sum += num; - assertEquals(6, sum); - } -} \ No newline at end of file From 506ac8301b2342c3adc2a7896516eb651f4d8449 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 13 Feb 2017 17:31:28 +0100 Subject: [PATCH 14/33] Refactor Spring Data examples --- .../baeldung/config/ValidatorEventRegister.java | 10 ++++++++-- .../RestResponseEntityExceptionHandler.java | 14 ++++++++++---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java index 89ab848e81..8f14d6c1c6 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java @@ -22,9 +22,15 @@ public class ValidatorEventRegister implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { List events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete"); - + for (Map.Entry entry : validators.entrySet()) { - events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue())); + events + .stream() + .filter(p -> entry + .getKey() + .startsWith(p)) + .findFirst() + .ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue())); } } } diff --git a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java index ee84738e7a..aa24fccac7 100644 --- a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java @@ -1,16 +1,17 @@ package com.baeldung.exception.handlers; -import java.util.stream.Collectors; - import org.springframework.data.rest.core.RepositoryConstraintViolationException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import java.util.stream.Collectors; + @ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @@ -18,8 +19,13 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH public ResponseEntity handleAccessDeniedException(Exception ex, WebRequest request) { RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex; - String errors = nevEx.getErrors().getAllErrors().stream().map(p -> p.toString()).collect(Collectors.joining("\n")); - return new ResponseEntity(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE); + String errors = nevEx + .getErrors() + .getAllErrors() + .stream() + .map(ObjectError::toString) + .collect(Collectors.joining("\n")); + return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE); } } \ No newline at end of file From 5ef3b149f1e44e2a49914f8b3429674b007774b9 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Mon, 13 Feb 2017 23:49:58 +0530 Subject: [PATCH 15/33] Update JoinerSplitterTest.java (#1172) --- .../test/java/com/baeldung/string/JoinerSplitterTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java b/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java index 303296cbc6..9ccff40558 100644 --- a/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java +++ b/core-java/src/test/java/com/baeldung/string/JoinerSplitterTest.java @@ -12,7 +12,7 @@ import com.baeldung.string.JoinerSplitter; public class JoinerSplitterTest { @Test - public void provided_array_convert_to_stream_and_convert_to_string() { + public void givenArray_transformedToStream_convertToString() { String[] programming_languages = {"java", "python", "nodejs", "ruby"}; @@ -23,7 +23,7 @@ public class JoinerSplitterTest { } @Test - public void provided_array_convert_to_stream_and_convert_to_prefixPostfix() { + public void givenArray_transformedToStream_convertToPrefixPostfixString() { String[] programming_languages = {"java", "python", "nodejs", "ruby"}; String expectation = "[java,python,nodejs,ruby]"; @@ -33,7 +33,7 @@ public class JoinerSplitterTest { } @Test - public void provided_string_convert_to_stream_and_convert_to_listOfString() { + public void givenString_transformedToStream_convertToList() { String programming_languages = "java,python,nodejs,ruby"; List expectation = new ArrayList(); @@ -48,7 +48,7 @@ public class JoinerSplitterTest { } @Test - public void provided_string_convert_to_stream_and_convert_to_listOfChar() { + public void givenString_transformedToStream_convertToListOfChar() { String programming_languages = "java,python,nodejs,ruby"; List expectation = new ArrayList(); From 491d36e745932caf297106a973ea5330e6501a60 Mon Sep 17 00:00:00 2001 From: Ravi-ronic Date: Tue, 14 Feb 2017 00:40:28 +0530 Subject: [PATCH 16/33] BAEL-524:after review comments (#1154) * BAEL-524 * BAEL-524 * BAEL-524 * BAEL-524 * BAEL-524 resolving build failure * BAEL-524 do not exclude test class --- struts2/pom.xml | 101 ++++++++++-------- .../src/com/baeldung/struts/CarAction.java | 9 +- .../baeldung/struts/CarMessageService.java | 9 +- .../baeldung/struts/test/TestCarAction.java | 32 ++++++ struts2/src/struts.xml | 12 --- 5 files changed, 102 insertions(+), 61 deletions(-) create mode 100644 struts2/src/com/baeldung/struts/test/TestCarAction.java delete mode 100644 struts2/src/struts.xml diff --git a/struts2/pom.xml b/struts2/pom.xml index 9b9adeaf46..0ae054ef38 100644 --- a/struts2/pom.xml +++ b/struts2/pom.xml @@ -1,48 +1,59 @@ - 4.0.0 - com.baeldung - struts2 - 0.0.1-SNAPSHOT - war - struts2 - - - src - - - src - - **/*.java - - - - - - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-war-plugin - 3.0.0 - - WebContent - - - - - - - - - org.apache.struts - struts2-core - 2.5.5 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + MyStrutsApp + 0.0.1-SNAPSHOT + war + MyStrutsApp + + src + + + src + + + + + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-war-plugin + 3.0.0 + + WebContent + + + + + + + + org.apache.struts + struts2-core + 2.5.5 + + + + org.apache.struts + struts2-junit-plugin + 2.5.5 + + + + org.apache.struts + struts2-convention-plugin + 2.5.8 + + + javax.servlet + javax.servlet-api + 3.0.1 - - + \ No newline at end of file diff --git a/struts2/src/com/baeldung/struts/CarAction.java b/struts2/src/com/baeldung/struts/CarAction.java index a96aa440b6..0b9266339c 100644 --- a/struts2/src/com/baeldung/struts/CarAction.java +++ b/struts2/src/com/baeldung/struts/CarAction.java @@ -1,7 +1,14 @@ package com.baeldung.struts; -public class CarAction { +import org.apache.struts2.convention.annotation.Action; +import org.apache.struts2.convention.annotation.Namespace; +import org.apache.struts2.convention.annotation.Result; +import org.apache.struts2.convention.annotation.ResultPath; +@Namespace("/tutorial") +@Action("/car") +@Result(name = "success", location = "/result.jsp") +public class CarAction { private String carName; private String carMessage; private CarMessageService carMessageService = new CarMessageService(); diff --git a/struts2/src/com/baeldung/struts/CarMessageService.java b/struts2/src/com/baeldung/struts/CarMessageService.java index fef9c1719d..34d3ca3d76 100644 --- a/struts2/src/com/baeldung/struts/CarMessageService.java +++ b/struts2/src/com/baeldung/struts/CarMessageService.java @@ -4,12 +4,15 @@ public class CarMessageService { public String getMessage(String carName) { System.out.println("inside getMessage()" + carName); - if (carName.equalsIgnoreCase("ferrari")) + if (carName.equalsIgnoreCase("ferrari")){ return "Ferrari Fan!"; - else if (carName.equalsIgnoreCase("bmw")) + } + else if (carName.equalsIgnoreCase("bmw")){ return "BMW Fan!"; - else + } + else{ return "please choose ferrari Or bmw"; + } } } diff --git a/struts2/src/com/baeldung/struts/test/TestCarAction.java b/struts2/src/com/baeldung/struts/test/TestCarAction.java new file mode 100644 index 0000000000..ec21bd689a --- /dev/null +++ b/struts2/src/com/baeldung/struts/test/TestCarAction.java @@ -0,0 +1,32 @@ +package com.baeldung.struts.test; +import org.apache.struts2.StrutsTestCase; +import org.junit.Test; + + +import com.baeldung.struts.CarAction; +import com.opensymphony.xwork2.ActionProxy; + +public class TestCarAction extends StrutsTestCase { + + @Test + public void test_givenCarOptions_WhenferrariSelected_ThenShowMessage() throws Exception { + request.setParameter("carName", "ferrari"); + ActionProxy proxy = getActionProxy("/tutorial/car.action"); + CarAction carAction = (CarAction) proxy.getAction(); + String result = proxy.execute(); + assertEquals(result,"success"); + assertEquals(carAction.getCarMessage(), "Ferrari Fan!"); + } + + + public void test_givenCarOptions_WhenbmwSelected_ThenShowMessage() throws Exception { + request.setParameter("carName", "bmw"); + ActionProxy proxy = getActionProxy("/tutorial/car.action"); + CarAction carAction = (CarAction) proxy.getAction(); + String result = proxy.execute(); + assertEquals(result,"success"); + assertEquals(carAction.getCarMessage(), "BMW Fan!"); + } + + +} diff --git a/struts2/src/struts.xml b/struts2/src/struts.xml deleted file mode 100644 index 1c117ac900..0000000000 --- a/struts2/src/struts.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - /result.jsp - - - \ No newline at end of file From 3eb0575708eb3e907a0738c2beee09315791fa57 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Tue, 14 Feb 2017 09:59:12 +0100 Subject: [PATCH 17/33] BAEL-12 userAgent header value in one place --- .../advancedconfig/HttpClientAdvancedConfiguration.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java index 1bb176876c..ac51f75b11 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java @@ -38,12 +38,12 @@ public class HttpClientAdvancedConfiguration { @Test public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException { //given + String userAgent = "BaeldungAgent/1.0"; serviceMock.stubFor(get(urlEqualTo("/detail")) - .withHeader("User-Agent", equalTo("BaeldungAgent/1.0")) + .withHeader("User-Agent", equalTo(userAgent)) .willReturn(aResponse() .withStatus(200))); - String userAgent = "BaeldungAgent/1.0"; HttpClient httpClient = HttpClients.createDefault(); final HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent); From a985a9fb5a6ce3bfe4a9a213a89dccd138df5f59 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Tue, 14 Feb 2017 10:01:09 +0100 Subject: [PATCH 18/33] BAEL-12 remove final --- .../advancedconfig/HttpClientAdvancedConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java index ac51f75b11..99389a001a 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java @@ -45,7 +45,7 @@ public class HttpClientAdvancedConfiguration { .withStatus(200))); HttpClient httpClient = HttpClients.createDefault(); - final HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); + HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent); //when From 24d0acbbd6abc58293ed4b48045adf54f1109cab Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Tue, 14 Feb 2017 10:05:16 +0100 Subject: [PATCH 19/33] BAEL-12 xmlBody into a variable --- .../advancedconfig/HttpClientAdvancedConfiguration.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java index 99389a001a..9b5cb3f293 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfiguration.java @@ -58,16 +58,17 @@ public class HttpClientAdvancedConfiguration { @Test public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException { //given + String xmlBody = "1"; serviceMock.stubFor(post(urlEqualTo("/person")) .withHeader("Content-Type", equalTo("application/xml")) - .withRequestBody(equalTo("1")) + .withRequestBody(equalTo(xmlBody)) .willReturn(aResponse() .withStatus(200))); HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8089/person"); httpPost.setHeader("Content-Type", "application/xml"); - StringEntity xmlEntity = new StringEntity("1"); + StringEntity xmlEntity = new StringEntity(xmlBody); httpPost.setEntity(xmlEntity); //when From cf87412c429c0ebb1bb162fb029908f5d42c3fef Mon Sep 17 00:00:00 2001 From: Tian Baoqiang Date: Wed, 15 Feb 2017 00:34:44 +0800 Subject: [PATCH 20/33] refined #BAEL-100 and remove Java EE app for simplicity (#1168) --- spring-boot/pom.xml | 37 ++------ .../servletcomponentscan/JavaEEApp.java | 28 ------ .../SpringBootAnnotatedApp.java | 4 +- .../SpringBootPlainApp.java | 2 +- .../{javaee => components}/AttrListener.java | 2 +- .../{javaee => components}/EchoServlet.java | 3 +- .../{javaee => components}/HelloFilter.java | 2 +- .../{javaee => components}/HelloServlet.java | 3 +- .../JavaEEAppIntegrationTest.java | 85 ------------------- ...otWithServletComponentIntegrationTest.java | 2 +- ...ithoutServletComponentIntegrationTest.java | 2 +- 11 files changed, 14 insertions(+), 156 deletions(-) delete mode 100644 spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java rename spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/{javaee => components}/AttrListener.java (90%) rename spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/{javaee => components}/EchoServlet.java (90%) rename spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/{javaee => components}/HelloFilter.java (94%) rename spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/{javaee => components}/HelloServlet.java (90%) delete mode 100644 spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppIntegrationTest.java diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index b6a24b6cb7..e77ab10aff 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -24,26 +24,6 @@ org.springframework.boot spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.apache.geronimo.specs - geronimo-osgi-locator - 1.1 - test - - - - org.apache.geronimo.components - geronimo-jaspi - 2.0.0 - test @@ -109,18 +89,12 @@ - org.apache.tomee - arquillian-tomee-embedded - ${arquillian-tomee-embedded.version} - test - - - - org.apache.tomee - javaee-api - ${tomee-javaee-api.version} + org.apache.tomcat + tomcat-servlet-api + ${tomee-servlet-api.version} provided + @@ -220,8 +194,7 @@ 3.1.1 3.3.7-1 3.1.7 - 7.0.2 - 7.0-1 + 8.5.11 diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java deleted file mode 100644 index 773503c5af..0000000000 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.context.Initialized; -import javax.enterprise.event.Observes; -import javax.servlet.ServletContext; - -@ApplicationScoped -public class JavaEEApp { - - private ServletContext context; - - /** - * act as a servletContext provider - */ - private void setContext(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) { - if (this.context != null) { - throw new IllegalStateException("app context started twice"); - } - - this.context = context; - } - - public ServletContext getContext() { - return context; - } - -} diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java index 9fd66ee12a..b4d416dd96 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java @@ -9,13 +9,13 @@ import org.springframework.boot.web.servlet.ServletComponentScan; *
  • * @ServletComponentScan *
  • - * @ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee") + * @ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") *
  • * @ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class}) *
*/ @SpringBootApplication -@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.javaee") +@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components") public class SpringBootAnnotatedApp { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java index 9ce1c296e6..8a39078aac 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java @@ -4,7 +4,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee") +@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") public class SpringBootPlainApp { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java similarity index 90% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java rename to spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java index 321ddd59d1..bad39c52c4 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java @@ -1,4 +1,4 @@ -package com.baeldung.annotation.servletcomponentscan.javaee; +package com.baeldung.annotation.servletcomponentscan.components; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java similarity index 90% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java rename to spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java index b9fed314c7..3419cd0eaf 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java @@ -1,4 +1,4 @@ -package com.baeldung.annotation.servletcomponentscan.javaee; +package com.baeldung.annotation.servletcomponentscan.components; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -6,7 +6,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; -import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java similarity index 94% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java rename to spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java index 81e90d69ad..dc2368c5b2 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.annotation.servletcomponentscan.javaee; +package com.baeldung.annotation.servletcomponentscan.components; import javax.servlet.*; import javax.servlet.annotation.WebFilter; diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java similarity index 90% rename from spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java rename to spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java index 4a46a56107..aeae7aecc9 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java @@ -1,7 +1,6 @@ -package com.baeldung.annotation.servletcomponentscan.javaee; +package com.baeldung.annotation.servletcomponentscan.components; import javax.servlet.ServletConfig; -import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppIntegrationTest.java deleted file mode 100644 index 95106d2dc8..0000000000 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppIntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; - -import javax.inject.Inject; -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.RunAsClient; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.arquillian.test.api.ArquillianResource; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.baeldung.annotation.servletcomponentscan.javaee.AttrListener; -import com.baeldung.annotation.servletcomponentscan.javaee.EchoServlet; -import com.baeldung.annotation.servletcomponentscan.javaee.HelloFilter; -import com.baeldung.annotation.servletcomponentscan.javaee.HelloServlet; - -@RunWith(Arquillian.class) -public class JavaEEAppIntegrationTest { - - @Deployment - public static WebArchive createDeployment() { - return ShrinkWrap.create(WebArchive.class).addClass(JavaEEApp.class).addClasses(AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class); - } - - @Inject - private ServletContext servletContext; - - @Test - public void givenServletContextListener_whenAccessSpecialAttrs_thenFound() throws MalformedURLException { - assertNotNull(servletContext); - assertNotNull(servletContext.getAttribute("servlet-context-attr")); - assertEquals("test", servletContext.getAttribute("servlet-context-attr")); - } - - @Test - public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() throws MalformedURLException { - assertNotNull(servletContext); - FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); - - assertNotNull(filterRegistration); - assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet")); - } - - @ArquillianResource - private URL base; - - @Test - @RunAsClient - public void givenFilterAndServlet_whenGetHello_thenRespondFilteringHello() throws MalformedURLException { - Client client = ClientBuilder.newClient(); - WebTarget target = client.target(URI.create(new URL(base, "hello").toExternalForm())); - Response response = target.request().get(); - - assertEquals("filtering hello", response.readEntity(String.class)); - } - - @Test - @RunAsClient - public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() throws MalformedURLException { - Client client = ClientBuilder.newClient(); - WebTarget target = client.target(URI.create(new URL(base, "echo").toExternalForm())); - Response response = target.request().post(Entity.entity("echo", MediaType.TEXT_PLAIN_TYPE)); - - assertEquals("filtering echo", response.readEntity(String.class)); - } - -} diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 81ac3c9841..8d5eb56bf4 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -19,7 +19,7 @@ import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false", "server.tomcat.additional-tld-skip-patterns=tomee-*.jar,tomcat-*.jar,openejb-*.jar,cxf-*.jar,activemq-*.jar" }) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithServletComponentIntegrationTest { @Autowired private ServletContext servletContext; diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index b2dea25864..64507ad02c 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -19,7 +19,7 @@ import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false", "server.tomcat.additional-tld-skip-patterns=tomee-*.jar,tomcat-*.jar,openejb-*.jar,cxf-*.jar,activemq-*.jar" }) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithoutServletComponentIntegrationTest { @Autowired private ServletContext servletContext; From 7f4c7157eb9dc040e737eff02fc923c02c0f1179 Mon Sep 17 00:00:00 2001 From: maibin Date: Tue, 14 Feb 2017 17:49:10 +0100 Subject: [PATCH 21/33] Struts2 refactoring (#1176) * Modifications to model on Hibernate One to manyTutorial * Modifications to model on Hibernate One to manyTutorial * Modifications to model on Hibernate One to manyTutorial * Simple Genetic Algorithm improvements * Struts2 refactoring --- core-java/0.004102810554955205 | 0 core-java/0.04832801936270381 | 0 core-java/0.5633433244738808 | 0 core-java/0.6256429734439612 | 0 core-java/0.9799201796740292 | 0 struts2/WebContent/WEB-INF/web.xml | 26 +++++++-------- struts2/pom.xml | 27 ++++++++++------ .../baeldung/struts/test/TestCarAction.java | 32 ------------------- .../java}/com/baeldung/struts/CarAction.java | 1 - .../baeldung/struts/CarMessageService.java | 0 .../baeldung/struts/test/CarActionTest.java | 29 +++++++++++++++++ 11 files changed, 57 insertions(+), 58 deletions(-) delete mode 100644 core-java/0.004102810554955205 delete mode 100644 core-java/0.04832801936270381 delete mode 100644 core-java/0.5633433244738808 delete mode 100644 core-java/0.6256429734439612 delete mode 100644 core-java/0.9799201796740292 delete mode 100644 struts2/src/com/baeldung/struts/test/TestCarAction.java rename struts2/src/{ => main/java}/com/baeldung/struts/CarAction.java (90%) rename struts2/src/{ => main/java}/com/baeldung/struts/CarMessageService.java (100%) create mode 100644 struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java diff --git a/core-java/0.004102810554955205 b/core-java/0.004102810554955205 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/0.04832801936270381 b/core-java/0.04832801936270381 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/0.5633433244738808 b/core-java/0.5633433244738808 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/0.6256429734439612 b/core-java/0.6256429734439612 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/0.9799201796740292 b/core-java/0.9799201796740292 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/struts2/WebContent/WEB-INF/web.xml b/struts2/WebContent/WEB-INF/web.xml index 3aa1d1d173..8f1b55943c 100644 --- a/struts2/WebContent/WEB-INF/web.xml +++ b/struts2/WebContent/WEB-INF/web.xml @@ -1,16 +1,12 @@ - - - MyStrutsApp - - struts2 - org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter - - - - struts2 - /* - + + + struts + + struts2 + org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter + + + struts2 + /* + \ No newline at end of file diff --git a/struts2/pom.xml b/struts2/pom.xml index 0ae054ef38..983f18903b 100644 --- a/struts2/pom.xml +++ b/struts2/pom.xml @@ -5,12 +5,12 @@ MyStrutsApp 0.0.1-SNAPSHOT war - MyStrutsApp + struts - src + src/main/java - src + src/main/resources @@ -32,28 +32,35 @@ - + + junit + junit + 4.12 + org.apache.struts struts2-core 2.5.5 - org.apache.struts struts2-junit-plugin 2.5.5 - org.apache.struts struts2-convention-plugin 2.5.8 - javax.servlet - javax.servlet-api - 3.0.1 - + javax.servlet + javax.servlet-api + 3.0.1 + + + org.springframework + spring-core + 4.3.6.RELEASE + \ No newline at end of file diff --git a/struts2/src/com/baeldung/struts/test/TestCarAction.java b/struts2/src/com/baeldung/struts/test/TestCarAction.java deleted file mode 100644 index ec21bd689a..0000000000 --- a/struts2/src/com/baeldung/struts/test/TestCarAction.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.struts.test; -import org.apache.struts2.StrutsTestCase; -import org.junit.Test; - - -import com.baeldung.struts.CarAction; -import com.opensymphony.xwork2.ActionProxy; - -public class TestCarAction extends StrutsTestCase { - - @Test - public void test_givenCarOptions_WhenferrariSelected_ThenShowMessage() throws Exception { - request.setParameter("carName", "ferrari"); - ActionProxy proxy = getActionProxy("/tutorial/car.action"); - CarAction carAction = (CarAction) proxy.getAction(); - String result = proxy.execute(); - assertEquals(result,"success"); - assertEquals(carAction.getCarMessage(), "Ferrari Fan!"); - } - - - public void test_givenCarOptions_WhenbmwSelected_ThenShowMessage() throws Exception { - request.setParameter("carName", "bmw"); - ActionProxy proxy = getActionProxy("/tutorial/car.action"); - CarAction carAction = (CarAction) proxy.getAction(); - String result = proxy.execute(); - assertEquals(result,"success"); - assertEquals(carAction.getCarMessage(), "BMW Fan!"); - } - - -} diff --git a/struts2/src/com/baeldung/struts/CarAction.java b/struts2/src/main/java/com/baeldung/struts/CarAction.java similarity index 90% rename from struts2/src/com/baeldung/struts/CarAction.java rename to struts2/src/main/java/com/baeldung/struts/CarAction.java index 0b9266339c..478f3b4cc2 100644 --- a/struts2/src/com/baeldung/struts/CarAction.java +++ b/struts2/src/main/java/com/baeldung/struts/CarAction.java @@ -3,7 +3,6 @@ package com.baeldung.struts; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; -import org.apache.struts2.convention.annotation.ResultPath; @Namespace("/tutorial") @Action("/car") diff --git a/struts2/src/com/baeldung/struts/CarMessageService.java b/struts2/src/main/java/com/baeldung/struts/CarMessageService.java similarity index 100% rename from struts2/src/com/baeldung/struts/CarMessageService.java rename to struts2/src/main/java/com/baeldung/struts/CarMessageService.java diff --git a/struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java b/struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java new file mode 100644 index 0000000000..64b640edfb --- /dev/null +++ b/struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java @@ -0,0 +1,29 @@ +//package com.baeldung.struts.test; +// +//import org.apache.struts2.StrutsTestCase; +//import org.junit.Test; +// +//import com.baeldung.struts.CarAction; +//import com.opensymphony.xwork2.ActionProxy; +// +//public class CarActionTest extends StrutsTestCase { +// +// public void testgivenCarOptions_WhenferrariSelected_ThenShowMessage() throws Exception { +// request.setParameter("carName", "ferrari"); +// ActionProxy proxy = getActionProxy("/tutorial/car.action"); +// CarAction carAction = (CarAction) proxy.getAction(); +// String result = proxy.execute(); +// assertEquals(result, "success"); +// assertEquals(carAction.getCarMessage(), "Ferrari Fan!"); +// } +// +// public void testgivenCarOptions_WhenbmwSelected_ThenShowMessage() throws Exception { +// request.setParameter("carName", "bmw"); +// ActionProxy proxy = getActionProxy("/tutorial/car.action"); +// CarAction carAction = (CarAction) proxy.getAction(); +// String result = proxy.execute(); +// assertEquals(result, "success"); +// assertEquals(carAction.getCarMessage(), "BMW Fan!"); +// } +// +//} From dd40ed702560dfd9a947462445bb2b4bdea4d12b Mon Sep 17 00:00:00 2001 From: Danil Kornishev Date: Tue, 14 Feb 2017 15:44:45 -0500 Subject: [PATCH 22/33] Neo4j moved (#1152) * Neo4j cleanup * Neo4j cleanup * Neo4j cleanup x2 --- core-java/pom.xml | 40 +-------------- spring-data-neo4j/pom.xml | 51 +++++++++++++++---- .../MovieDatabaseNeo4jConfiguration.java | 7 +-- .../MovieDatabaseNeo4jTestConfiguration.java | 6 +-- .../spring/data/neo4j/domain}/Car.java | 5 +- .../spring/data/neo4j/domain}/Company.java | 5 +- .../com/baeldung/neo4j}/Neo4JServerTest.java | 4 +- .../com/baeldung/neo4j}/Neo4jOgmTest.java | 19 ++++--- .../java/com/baeldung/neo4j}/Neo4jTest.java | 4 +- .../src/test/resources/logback.xml | 16 ++++++ 10 files changed, 79 insertions(+), 78 deletions(-) rename {core-java/src/main/java/com/baeldung/graph => spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain}/Car.java (89%) rename {core-java/src/main/java/com/baeldung/graph => spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain}/Company.java (87%) rename {core-java/src/test/java/com/baeldung/graph => spring-data-neo4j/src/test/java/com/baeldung/neo4j}/Neo4JServerTest.java (97%) rename {core-java/src/test/java/com/baeldung/graph => spring-data-neo4j/src/test/java/com/baeldung/neo4j}/Neo4jOgmTest.java (80%) rename {core-java/src/test/java/com/baeldung/graph => spring-data-neo4j/src/test/java/com/baeldung/neo4j}/Neo4jTest.java (99%) create mode 100644 spring-data-neo4j/src/test/resources/logback.xml diff --git a/core-java/pom.xml b/core-java/pom.xml index 2b6f065c85..b2c59989f1 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -9,45 +9,7 @@ core-java - - - org.neo4j - neo4j - 3.1.0 - - - - org.neo4j.driver - neo4j-java-driver - 1.1.1 - - - - org.neo4j - neo4j-jdbc-driver - 3.0.1 - - - - org.neo4j - neo4j-ogm-core - 2.1.1 - - - - org.neo4j - neo4j-ogm-embedded-driver - 2.1.1 - - - - com.google.inject - guice - 4.1.0 - no_aop - test - - + net.sourceforge.collections diff --git a/spring-data-neo4j/pom.xml b/spring-data-neo4j/pom.xml index ce10313b2e..7e7f02e9a9 100644 --- a/spring-data-neo4j/pom.xml +++ b/spring-data-neo4j/pom.xml @@ -7,10 +7,41 @@ 1.0 + + org.neo4j + neo4j + 3.1.0 + + + + org.neo4j + neo4j-ogm-core + 2.1.1 + + + + org.neo4j + neo4j-ogm-embedded-driver + 2.1.1 + + + + org.neo4j.driver + neo4j-java-driver + 1.1.1 + + + + org.springframework.data + spring-data-neo4j + 4.2.0.RELEASE + + org.springframework.data spring-data-neo4j ${spring-data-neo4j.version} + test-jar @@ -27,13 +58,6 @@ test - - org.springframework.data - spring-data-neo4j - ${spring-data-neo4j.version} - test-jar - - org.neo4j neo4j-kernel @@ -72,9 +96,14 @@ spring-test ${spring-test.version} - + + junit + junit + 4.12 + + @@ -130,16 +159,18 @@ + 1.8 + 1.8 1.8 UTF-8 UTF-8 - 3.0.7 + 3.1.0 4.1.6.RELEASE 1.1 1.4.3.RELEASE 4.3.5.RELEASE - 2.0.6 + 2.1.1 4.12 diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index fb4fda1497..344282d665 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -4,15 +4,12 @@ import org.neo4j.ogm.session.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.data.neo4j.config.Neo4jConfiguration; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.transaction.annotation.EnableTransactionManagement; @ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") -public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { +public class MovieDatabaseNeo4jConfiguration { public static final String URL = System.getenv("NEO4J_URL") != null ? System.getenv("NEO4J_URL") : "http://neo4j:movies@localhost:7474"; @@ -23,7 +20,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { return config; } - @Override + @Bean public SessionFactory getSessionFactory() { return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain"); } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java index 81935b2293..7bb1b78a09 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java @@ -5,9 +5,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; -import org.springframework.data.neo4j.config.Neo4jConfiguration; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; -import org.springframework.data.neo4j.server.Neo4jServer; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @@ -15,7 +13,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") @Profile({ "embedded", "test" }) -public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { +public class MovieDatabaseNeo4jTestConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { @@ -24,7 +22,7 @@ public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { return config; } - @Override + @Bean public SessionFactory getSessionFactory() { return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain"); } diff --git a/core-java/src/main/java/com/baeldung/graph/Car.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java similarity index 89% rename from core-java/src/main/java/com/baeldung/graph/Car.java rename to spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java index 1dc65a0d4b..f2325a334f 100644 --- a/core-java/src/main/java/com/baeldung/graph/Car.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java @@ -1,12 +1,9 @@ -package com.baeldung.graph; +package com.baeldung.spring.data.neo4j.domain; import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; -/** - * @author Danil Kornishev (danil.kornishev@mastercard.com) - */ @NodeEntity public class Car { @GraphId diff --git a/core-java/src/main/java/com/baeldung/graph/Company.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java similarity index 87% rename from core-java/src/main/java/com/baeldung/graph/Company.java rename to spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java index 1fe892b331..4422ade44f 100644 --- a/core-java/src/main/java/com/baeldung/graph/Company.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java @@ -1,11 +1,8 @@ -package com.baeldung.graph; +package com.baeldung.spring.data.neo4j.domain; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; -/** - * @author Danil Kornishev (danil.kornishev@mastercard.com) - */ @NodeEntity public class Company { private Long id; diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerTest.java index b41588b71e..e959e0237d 100644 --- a/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerTest.java @@ -1,10 +1,11 @@ -package com.baeldung.graph; +package com.baeldung.neo4j; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; +import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.neo4j.driver.v1.AuthTokens; @@ -12,7 +13,6 @@ import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.StatementResult; -import org.testng.Assert; @Ignore public class Neo4JServerTest { diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmTest.java similarity index 80% rename from core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmTest.java index 00bd47d029..3e218f39d7 100644 --- a/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmTest.java @@ -1,18 +1,19 @@ -package com.baeldung.graph; +package com.baeldung.neo4j; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; import org.junit.Test; import org.neo4j.ogm.config.Configuration; import org.neo4j.ogm.model.Result; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; -import org.testng.Assert; -import java.util.HashMap; -import java.util.Map; +import com.baeldung.spring.data.neo4j.domain.Car; +import com.baeldung.spring.data.neo4j.domain.Company; +import org.neo4j.ogm.transaction.Transaction; -/** - * @author Danil Kornishev (danil.kornishev@mastercard.com) - */ public class Neo4jOgmTest { @Test @@ -20,7 +21,7 @@ public class Neo4jOgmTest { Configuration conf = new Configuration(); conf.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); - SessionFactory factory = new SessionFactory(conf, "com.baeldung.graph"); + SessionFactory factory = new SessionFactory(conf, "com.baeldung.spring.data.neo4j.domain"); Session session = factory.openSession(); Car tesla = new Car("tesla", "modelS"); @@ -30,6 +31,8 @@ public class Neo4jOgmTest { session.save(baeldung); + Assert.assertEquals(1, session.countEntitiesOfType(Company.class)); + Map params = new HashMap<>(); params.put("make", "tesla"); Result result = session.query("MATCH (car:Car) <-[:owns]- (company:Company)" + diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/graph/Neo4jTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jTest.java index 6956c2c39f..c303410e57 100644 --- a/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jTest.java @@ -1,4 +1,4 @@ -package com.baeldung.graph; +package com.baeldung.neo4j; import java.io.File; @@ -7,6 +7,7 @@ import java.util.HashMap; import java.util.Map; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; @@ -16,7 +17,6 @@ import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Result; import org.neo4j.graphdb.factory.GraphDatabaseFactory; -import org.testng.Assert; public class Neo4jTest { diff --git a/spring-data-neo4j/src/test/resources/logback.xml b/spring-data-neo4j/src/test/resources/logback.xml new file mode 100644 index 0000000000..39a6538324 --- /dev/null +++ b/spring-data-neo4j/src/test/resources/logback.xml @@ -0,0 +1,16 @@ + + + + + + %d %5p %40.40c:%4L - %m%n + + + + + + + + + + From f3f021f036197f53a8c6288a4895ed7160ae16a0 Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Wed, 15 Feb 2017 01:20:28 +0000 Subject: [PATCH 23/33] Mesos marathon module (#1107) * mesos marathon demo * Updated DockerFile to point to maven target * Pointed to baeldung docker repository * Added file permissions for Dockerise script --- mesos-marathon/Dockerfile | 4 ++ mesos-marathon/dockerise.sh | 5 ++ mesos-marathon/marathon.json | 14 ++++++ mesos-marathon/pom.xml | 46 +++++++++++++++++++ .../java/com/mogronalol/DemoApplication.java | 14 ++++++ .../java/com/mogronalol/HelloController.java | 17 +++++++ .../src/main/resources/application.properties | 1 + .../com/mogronalol/DemoApplicationTests.java | 34 ++++++++++++++ pom.xml | 1 + 9 files changed, 136 insertions(+) create mode 100644 mesos-marathon/Dockerfile create mode 100755 mesos-marathon/dockerise.sh create mode 100644 mesos-marathon/marathon.json create mode 100644 mesos-marathon/pom.xml create mode 100644 mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java create mode 100644 mesos-marathon/src/main/java/com/mogronalol/HelloController.java create mode 100644 mesos-marathon/src/main/resources/application.properties create mode 100644 mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java diff --git a/mesos-marathon/Dockerfile b/mesos-marathon/Dockerfile new file mode 100644 index 0000000000..ca79f2dc82 --- /dev/null +++ b/mesos-marathon/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:8-jre-alpine +ADD target/mesos-marathon-0.0.1-SNAPSHOT.jar app.jar +EXPOSE 8082 +ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/mesos-marathon/dockerise.sh b/mesos-marathon/dockerise.sh new file mode 100755 index 0000000000..50f5d38306 --- /dev/null +++ b/mesos-marathon/dockerise.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -e +docker login -u mogronalol -p $DOCKER_PASSWORD +docker build -t baeldung/mesos-marathon-demo:$BUILD_NUMBER . +docker push baeldung/mesos-marathon-demo:$BUILD_NUMBER diff --git a/mesos-marathon/marathon.json b/mesos-marathon/marathon.json new file mode 100644 index 0000000000..6471259e92 --- /dev/null +++ b/mesos-marathon/marathon.json @@ -0,0 +1,14 @@ +{ + "id": "mesos-marathon-demo", + "container": { + "type": "DOCKER", + "docker": { + "image": "", + "network": "BRIDGE", + "portMappings": [ + { "containerPort": 8082, "hostPort": 0 } + ] + }, + "volumes": [] + } +} \ No newline at end of file diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml new file mode 100644 index 0000000000..ca17a5c4c4 --- /dev/null +++ b/mesos-marathon/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + com.baeldung + mesos-marathon + 0.0.1-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.5.1.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 1.5.1.RELEASE + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java b/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java new file mode 100644 index 0000000000..f757178026 --- /dev/null +++ b/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java @@ -0,0 +1,14 @@ +package com.mogronalol; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } +} diff --git a/mesos-marathon/src/main/java/com/mogronalol/HelloController.java b/mesos-marathon/src/main/java/com/mogronalol/HelloController.java new file mode 100644 index 0000000000..2059280ba0 --- /dev/null +++ b/mesos-marathon/src/main/java/com/mogronalol/HelloController.java @@ -0,0 +1,17 @@ +package com.mogronalol; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController(value = "/") +public class HelloController { + + @GetMapping + @ResponseBody + public String getMapping() { + return "Hello world"; + } + +} diff --git a/mesos-marathon/src/main/resources/application.properties b/mesos-marathon/src/main/resources/application.properties new file mode 100644 index 0000000000..8d51d0c619 --- /dev/null +++ b/mesos-marathon/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8082 \ No newline at end of file diff --git a/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java b/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java new file mode 100644 index 0000000000..5e88f9a70f --- /dev/null +++ b/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java @@ -0,0 +1,34 @@ +package com.mogronalol; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RestTemplate; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = {DemoApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class DemoApplicationTests { + + private RestTemplate restTemplate; + + @LocalServerPort + private int port; + + @Before + public void setUp() { + restTemplate = new RestTemplate(); + } + + @Test + public void contextLoads() { + final String result = restTemplate.getForObject("http://localhost:" + port + "/", String.class); + assertThat(result).isEqualTo("Hello world"); + } + +} diff --git a/pom.xml b/pom.xml index 2392e2c594..9eb4e78dbf 100644 --- a/pom.xml +++ b/pom.xml @@ -81,6 +81,7 @@ mapstruct metrics + mesos-marathon mockito mocks From 746ed952db17ae4d626bc9398693ab9cf5e3cb49 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Tue, 14 Feb 2017 20:52:25 -0600 Subject: [PATCH 24/33] Update README.md --- spring-security-mvc-login/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-mvc-login/README.md b/spring-security-mvc-login/README.md index d1f6b884b1..35305112b4 100644 --- a/spring-security-mvc-login/README.md +++ b/spring-security-mvc-login/README.md @@ -10,6 +10,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security Logout](http://www.baeldung.com/spring-security-logout) - [Spring Security Expressions – hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) - [Spring HTTP/HTTPS Channel Security](http://www.baeldung.com/spring-channel-security-https) +- [Spring Security - Customize the 403 Forbidden/Access Denied Page](http://www.baeldung.com/spring-security-custom-access-denied-page) ### Build the Project ``` From 9135c6073e9c3ce2906c0a6e9274d26619acd618 Mon Sep 17 00:00:00 2001 From: Stephen Braimah Date: Mon, 13 Feb 2017 21:45:43 +0100 Subject: [PATCH 25/33] BAEL-639: Guide to Guava's EventBus Tests - removed EventWrapper and added DeadEvent Subscriber --- .../org/baeldung/guava/GuavaEventBusTest.java | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java index 1db361d22c..0ff25c6df2 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java @@ -1,5 +1,6 @@ package org.baeldung.guava; +import com.google.common.eventbus.EventBus; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -9,25 +10,27 @@ import static org.junit.Assert.*; public class GuavaEventBusTest { private EventListener listener; + private EventBus eventBus; @Before public void setUp() { + eventBus = new EventBus(); listener = new EventListener(); - EventBusWrapper.register(listener); + + eventBus.register(listener); } @After public void tearDown() { - EventBusWrapper.unregister(listener); + eventBus.unregister(listener); } @Test public void givenStringEvent_whenEventHandled_thenSuccess() { listener.resetEventsHandled(); - EventBusWrapper.post("String Event"); + eventBus.post("String Event"); assertEquals(1, listener.getEventsHandled()); - } @Test @@ -35,8 +38,17 @@ public class GuavaEventBusTest { listener.resetEventsHandled(); CustomEvent customEvent = new CustomEvent("Custom Event"); - EventBusWrapper.post(customEvent); + eventBus.post(customEvent); assertEquals(1, listener.getEventsHandled()); } + + @Test + public void givenUnSubscribedEvent_whenEventHandledByDeadEvent_thenSuccess() { + listener.resetEventsHandled(); + + eventBus.post(12345); + assertEquals(1, listener.getEventsHandled()); + } + } From cc089e52974a80cb539176cc19922092e986c765 Mon Sep 17 00:00:00 2001 From: Mohd Farid Date: Wed, 15 Feb 2017 12:06:04 +0530 Subject: [PATCH 26/33] BAEL-668 find min/max from a list/collection (#1134) * BAEL-668 find min/max from a list/collection * BAEL-668 using mapToInt instead of Compare * BAEL-668 using direct assertion with the method call --- .../com/baeldung/java_8_features/Person.java | 27 ++++++++++++++ .../com/baeldung/java8/Java8MaxMinTest.java | 37 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/java_8_features/Person.java create mode 100644 core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java diff --git a/core-java/src/main/java/com/baeldung/java_8_features/Person.java b/core-java/src/main/java/com/baeldung/java_8_features/Person.java new file mode 100644 index 0000000000..83b5530ee8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/Person.java @@ -0,0 +1,27 @@ +package com.baeldung.java_8_features; + +public class Person { + private String name; + private Integer age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } +} diff --git a/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java b/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java new file mode 100644 index 0000000000..0e361d96e1 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java @@ -0,0 +1,37 @@ +package com.baeldung.java8; + +import com.baeldung.java_8_features.Person; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class Java8MaxMinTest { + + @Test + public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() { + //given + final List listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10); + final Integer expectedResult = 89; + + //then + assertEquals(expectedResult, + (Integer) listOfIntegers.stream().mapToInt(val -> val).max().getAsInt()); + } + + @Test + public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() { + //given + final Person alex = new Person("Alex", 23); + final Person john = new Person("John", 40); + final Person peter = new Person("Peter", 32); + final List people = Arrays.asList(alex, john, peter); + + //then + assertEquals("Alex must be having min age", alex, + people.stream().min((o1, o2) -> o1.getAge().compareTo(o2.getAge())).get()); + } + +} From f7ef3766cbb49b3588e2d3b740d4e0c6ae24e92e Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Wed, 15 Feb 2017 09:58:37 +0100 Subject: [PATCH 27/33] BAEL-639: Guide to Guava's EventBus Tests - adding sleep --- guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java index 0ff25c6df2..b20ea45e41 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java @@ -44,10 +44,12 @@ public class GuavaEventBusTest { } @Test - public void givenUnSubscribedEvent_whenEventHandledByDeadEvent_thenSuccess() { + public void givenUnSubscribedEvent_whenEventHandledByDeadEvent_thenSuccess() throws InterruptedException { listener.resetEventsHandled(); eventBus.post(12345); + Thread.sleep(1000); + assertEquals(1, listener.getEventsHandled()); } From 429c700caff0ac3c59b97255999aca649f28a624 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Wed, 15 Feb 2017 10:04:00 +0100 Subject: [PATCH 28/33] BAEL-639: Fixing failing test --- .../org/baeldung/guava/EventBusWrapper.java | 21 ------------------- .../org/baeldung/guava/EventListener.java | 7 +++++++ .../org/baeldung/guava/GuavaEventBusTest.java | 1 - 3 files changed, 7 insertions(+), 22 deletions(-) delete mode 100644 guava/src/main/java/org/baeldung/guava/EventBusWrapper.java diff --git a/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java b/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java deleted file mode 100644 index 243bc9e6ea..0000000000 --- a/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.guava; - -import com.google.common.eventbus.EventBus; - -class EventBusWrapper { - - private static EventBus eventBus = new EventBus(); - - static void register(Object object) { - eventBus.register(object); - } - - static void unregister(Object object) { - eventBus.unregister(object); - } - - static void post(Object object) { - eventBus.post(object); - } - -} diff --git a/guava/src/main/java/org/baeldung/guava/EventListener.java b/guava/src/main/java/org/baeldung/guava/EventListener.java index 02f22ce6b9..438fcade63 100644 --- a/guava/src/main/java/org/baeldung/guava/EventListener.java +++ b/guava/src/main/java/org/baeldung/guava/EventListener.java @@ -1,5 +1,6 @@ package org.baeldung.guava; +import com.google.common.eventbus.DeadEvent; import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,6 +22,12 @@ public class EventListener { eventsHandled++; } + @Subscribe + public void handleDeadEvent(DeadEvent deadEvent) { + LOG.info("unhandled event [" + deadEvent.getEvent() + "]"); + eventsHandled++; + } + public int getEventsHandled() { return eventsHandled; } diff --git a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java index b20ea45e41..1390eb05aa 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java @@ -48,7 +48,6 @@ public class GuavaEventBusTest { listener.resetEventsHandled(); eventBus.post(12345); - Thread.sleep(1000); assertEquals(1, listener.getEventsHandled()); } From 99963ee271d63ccb35a2f8c161e2d7e520c51aca Mon Sep 17 00:00:00 2001 From: pivovarit Date: Wed, 15 Feb 2017 11:24:25 +0100 Subject: [PATCH 29/33] Refactor spring-data-neo4j --- .../spring/data/neo4j/repostory/MovieRepository.java | 1 + .../spring/data/neo4j/repostory/PersonRepository.java | 1 - .../baeldung/spring/data/neo4j/services/MovieService.java | 8 ++++---- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java index 1bd605a7bc..afb82551e7 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java @@ -12,6 +12,7 @@ import java.util.Map; @Repository public interface MovieRepository extends GraphRepository { + Movie findByTitle(@Param("title") String title); @Query("MATCH (m:Movie) WHERE m.title =~ ('(?i).*'+{title}+'.*') RETURN m") diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java index f7f694c07f..4ac40ef75b 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java @@ -6,5 +6,4 @@ import org.springframework.stereotype.Repository; @Repository public interface PersonRepository extends GraphRepository { - } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java index d760d19066..ae1f6eb8e5 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -12,11 +12,11 @@ import java.util.*; public class MovieService { @Autowired - MovieRepository movieRepository; + private MovieRepository movieRepository; private Map toD3Format(Iterator> result) { - List> nodes = new ArrayList>(); - List> rels = new ArrayList>(); + List> nodes = new ArrayList<>(); + List> rels = new ArrayList<>(); int i = 0; while (result.hasNext()) { Map row = result.next(); @@ -37,7 +37,7 @@ public class MovieService { } private Map map(String key1, Object value1, String key2, Object value2) { - Map result = new HashMap(2); + Map result = new HashMap<>(2); result.put(key1, value1); result.put(key2, value2); return result; From 947fddab543f05bd73396b876d309d9491cd1437 Mon Sep 17 00:00:00 2001 From: baljeet20 Date: Wed, 15 Feb 2017 20:34:39 +0530 Subject: [PATCH 30/33] BAEL-604 Introduction to Apache velocity (#1179) * BAEL-604 Introduction to apache velocity * BAEL-604 Introduction to apache velocity --- apache-velocity/pom.xml | 101 ++++++++++++++++++ .../apache/velocity/model/Product.java | 33 ++++++ .../velocity/service/ProductService.java | 20 ++++ .../velocity/servlet/LayoutServlet.java | 41 +++++++ .../velocity/servlet/ProductServlet.java | 40 +++++++ .../src/main/resources/logback.xml | 23 ++++ .../main/webapp/WEB-INF/velocity.properties | 4 + .../src/main/webapp/WEB-INF/web.xml | 49 +++++++++ .../src/main/webapp/fragments/footer.vm | 4 + .../src/main/webapp/fragments/header.vm | 5 + .../src/main/webapp/layout/Default.vm | 22 ++++ .../src/main/webapp/templates/index.vm | 63 +++++++++++ .../src/main/webapp/templates/layoutdemo.vm | 27 +++++ .../servlet/LayoutServletLiveTest.java | 26 +++++ .../servlet/ProductServletLiveTest.java | 24 +++++ pom.xml | 2 + 16 files changed, 484 insertions(+) create mode 100644 apache-velocity/pom.xml create mode 100644 apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java create mode 100644 apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java create mode 100644 apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java create mode 100644 apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java create mode 100644 apache-velocity/src/main/resources/logback.xml create mode 100644 apache-velocity/src/main/webapp/WEB-INF/velocity.properties create mode 100644 apache-velocity/src/main/webapp/WEB-INF/web.xml create mode 100644 apache-velocity/src/main/webapp/fragments/footer.vm create mode 100644 apache-velocity/src/main/webapp/fragments/header.vm create mode 100644 apache-velocity/src/main/webapp/layout/Default.vm create mode 100644 apache-velocity/src/main/webapp/templates/index.vm create mode 100644 apache-velocity/src/main/webapp/templates/layoutdemo.vm create mode 100644 apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java create mode 100644 apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml new file mode 100644 index 0000000000..08f0e96a58 --- /dev/null +++ b/apache-velocity/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + com.baeldung + 0.1-SNAPSHOT + apache-velocity + + war + apache-velocity + + + 1.8 + 1.2 + 4.11 + 1.0.13 + 1.7.5 + 3.6.0 + 2.6 + 2.19.1 + 4.5.2 + 1.7 + 2.0 + + + + + junit + junit + ${junit.version} + test + + + org.apache.velocity + velocity + ${velocity-version} + + + org.apache.velocity + velocity-tools + ${velocity-tools-version} + + + org.slf4j + jcl-over-slf4j + ${jcl-over-slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.apache.httpcomponents + httpclient + ${org.apache.httpcomponents.version} + test + + + + apache-velocity + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${jdk.version} + ${jdk.version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*LiveTest.java + + + + + + + + diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java new file mode 100644 index 0000000000..c215223181 --- /dev/null +++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java @@ -0,0 +1,33 @@ +package com.baeldung.apache.velocity.model; + +public class Product { + + private String name; + private double price; + + public Product(String name, double price) { + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + @Override + public String toString() { + return "Product{" + "name='" + name + '\'' + ", price=" + price + '}'; + } +} diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java new file mode 100644 index 0000000000..0a623d4d65 --- /dev/null +++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java @@ -0,0 +1,20 @@ +package com.baeldung.apache.velocity.service; + +import com.baeldung.apache.velocity.model.Product; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; + +public class ProductService { + + Logger logger = LoggerFactory.getLogger(ProductService.class); + + public List getProducts() { + logger.debug("Product service returning list of products"); + + return Arrays.asList(new Product("Laptop", 31000.00), new Product("Mobile", 16000.00), + new Product("Tablet", 15000.00), new Product("Camera", 23000.00)); + } +} diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java new file mode 100644 index 0000000000..d4208a3880 --- /dev/null +++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java @@ -0,0 +1,41 @@ +package com.baeldung.apache.velocity.servlet; + +import com.baeldung.apache.velocity.model.Product; +import com.baeldung.apache.velocity.service.ProductService; +import org.apache.velocity.Template; +import org.apache.velocity.context.Context; +import org.apache.velocity.tools.view.VelocityLayoutServlet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +public class LayoutServlet extends VelocityLayoutServlet { + ProductService service = new ProductService(); + + @Override + public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) { + + Logger logger= LoggerFactory.getLogger(LayoutServlet.class); + + List products = service.getProducts(); + + context.put("products", products); + + Template template = null; + + try { + template = getTemplate("templates/layoutdemo.vm"); + + response.setHeader("Template Returned", "Success"); + } catch (Exception e) { + logger.error("Error while reading the template ",e); + } + + return template; + + } + +} diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java new file mode 100644 index 0000000000..60c9169fce --- /dev/null +++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java @@ -0,0 +1,40 @@ +package com.baeldung.apache.velocity.servlet; + +import com.baeldung.apache.velocity.model.Product; +import com.baeldung.apache.velocity.service.ProductService; +import org.apache.velocity.Template; +import org.apache.velocity.context.Context; +import org.apache.velocity.tools.view.VelocityViewServlet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +public class ProductServlet extends VelocityViewServlet { + + ProductService service = new ProductService(); + + @Override + public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) { + + Logger logger= LoggerFactory.getLogger(ProductServlet.class); + + List products = service.getProducts(); + + context.put("products", products); + + Template template = null; + + try { + template = getTemplate("templates/index.vm"); + response.setHeader("Template Returned", "Success"); + } catch (Exception e) { + logger.error("Error while reading the template ", e); + } + + return template; + + } +} diff --git a/apache-velocity/src/main/resources/logback.xml b/apache-velocity/src/main/resources/logback.xml new file mode 100644 index 0000000000..70a420a57a --- /dev/null +++ b/apache-velocity/src/main/resources/logback.xml @@ -0,0 +1,23 @@ + + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties new file mode 100644 index 0000000000..00e0b7e410 --- /dev/null +++ b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties @@ -0,0 +1,4 @@ +resource.loader=webapp +webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader +webapp.resource.loader.path = . +webapp.resource.loader.cache = true \ No newline at end of file diff --git a/apache-velocity/src/main/webapp/WEB-INF/web.xml b/apache-velocity/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..95b41b36dd --- /dev/null +++ b/apache-velocity/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,49 @@ + + + + apache-velocity + + ProductServlet + com.baeldung.apache.velocity.servlet.ProductServlet + + + + LayoutServlet + com.baeldung.apache.velocity.servlet.LayoutServlet + + + velocityLayout + org.apache.velocity.tools.view.VelocityLayoutServlet + + + org.apache.velocity.properties + /WEB-INF/velocity.properties + + + + ProductServlet + / + + + + LayoutServlet + /layout + + + velocityLayout + *.vm + + + + + 30 + + + + + + index.html + + diff --git a/apache-velocity/src/main/webapp/fragments/footer.vm b/apache-velocity/src/main/webapp/fragments/footer.vm new file mode 100644 index 0000000000..41bb36ce5e --- /dev/null +++ b/apache-velocity/src/main/webapp/fragments/footer.vm @@ -0,0 +1,4 @@ +
+ @Copyright baeldung.com +
\ No newline at end of file diff --git a/apache-velocity/src/main/webapp/fragments/header.vm b/apache-velocity/src/main/webapp/fragments/header.vm new file mode 100644 index 0000000000..96700d3baf --- /dev/null +++ b/apache-velocity/src/main/webapp/fragments/header.vm @@ -0,0 +1,5 @@ +
+
+

Layout Demo Page

+
+
\ No newline at end of file diff --git a/apache-velocity/src/main/webapp/layout/Default.vm b/apache-velocity/src/main/webapp/layout/Default.vm new file mode 100644 index 0000000000..39a8b277a5 --- /dev/null +++ b/apache-velocity/src/main/webapp/layout/Default.vm @@ -0,0 +1,22 @@ + + + Velocity + + +
+ #parse("/fragments/header.vm") +
+ + +
+ + + $screen_content + +
+ +
+ #parse("/fragments/footer.vm") +
+ + \ No newline at end of file diff --git a/apache-velocity/src/main/webapp/templates/index.vm b/apache-velocity/src/main/webapp/templates/index.vm new file mode 100644 index 0000000000..0ca07caf42 --- /dev/null +++ b/apache-velocity/src/main/webapp/templates/index.vm @@ -0,0 +1,63 @@ + + + Online Electronic Store + + + + +
+

Today's Offers

+
+
+

$products.size() Products on Sale!

+
+ We are proud to offer these fine products + at these amazing prices. +
+
+ #set( $count = 1 ) + + + + + #foreach( $product in $products ) + + + + + + #set( $count = $count + 1 ) + #end +
Serial #Product NamePrice
$count)$product.getName()$product.getPrice()
+
+
+ + + diff --git a/apache-velocity/src/main/webapp/templates/layoutdemo.vm b/apache-velocity/src/main/webapp/templates/layoutdemo.vm new file mode 100644 index 0000000000..0626b655c9 --- /dev/null +++ b/apache-velocity/src/main/webapp/templates/layoutdemo.vm @@ -0,0 +1,27 @@ +#set( $layout = "layout.vm" ) +
+

Today's Offers

+
+
+

$products.size() Products on Sale!

+
+ We are proud to offer these fine products + at these amazing prices. +
+
+ #set( $count = 1 ) + + + + + #foreach( $product in $products ) + + + + + + #set( $count = $count + 1 ) + #end +
Serial #Product NamePrice
$count)$product.getName()$product.getPrice()
+
+
\ No newline at end of file diff --git a/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java b/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java new file mode 100644 index 0000000000..f1f166b119 --- /dev/null +++ b/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java @@ -0,0 +1,26 @@ +package com.baeldung.apache.velocity.servlet; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class LayoutServletLiveTest { + + @Test + public void whenRequestUsingHttpClient_thenCorrectResponse() throws Exception { + + HttpClient client = new DefaultHttpClient(); + HttpGet method= new HttpGet("http://localhost:8080/layout"); + + HttpResponse httpResponse = client.execute(method); + + assertEquals("Success", httpResponse.getHeaders("Template Returned")[0].getValue()); + + } + +} diff --git a/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java b/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java new file mode 100644 index 0000000000..397e575d4d --- /dev/null +++ b/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java @@ -0,0 +1,24 @@ +package com.baeldung.apache.velocity.servlet; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ProductServletLiveTest { + + @Test + public void whenRequestUsingHttpClient_thenCorrectResponse() throws Exception { + + HttpClient client = new DefaultHttpClient(); + HttpGet method= new HttpGet("http://localhost:8080/"); + + HttpResponse httpResponse = client.execute(method); + + assertEquals("Success", httpResponse.getHeaders("Template Returned")[0].getValue()); + + } +} diff --git a/pom.xml b/pom.xml index 9eb4e78dbf..ecb07e987b 100644 --- a/pom.xml +++ b/pom.xml @@ -192,6 +192,8 @@ xstream struts2 + apache-velocity + From 498230ff89e752ea01a6fd71c081d8ab736fd3c1 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Wed, 15 Feb 2017 20:48:46 +0100 Subject: [PATCH 31/33] Refactor MinMaxTest --- .../com/baeldung/java8/Java8MaxMinTest.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java b/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java index 0e361d96e1..b0e514124d 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8MaxMinTest.java @@ -4,7 +4,9 @@ import com.baeldung.java_8_features.Person; import org.junit.Test; import java.util.Arrays; +import java.util.Comparator; import java.util.List; +import java.util.NoSuchElementException; import static org.junit.Assert.assertEquals; @@ -17,8 +19,12 @@ public class Java8MaxMinTest { final Integer expectedResult = 89; //then - assertEquals(expectedResult, - (Integer) listOfIntegers.stream().mapToInt(val -> val).max().getAsInt()); + final Integer max = listOfIntegers + .stream() + .mapToInt(v -> v) + .max().orElseThrow(NoSuchElementException::new); + + assertEquals("Should be 89", expectedResult, max); } @Test @@ -30,8 +36,12 @@ public class Java8MaxMinTest { final List people = Arrays.asList(alex, john, peter); //then - assertEquals("Alex must be having min age", alex, - people.stream().min((o1, o2) -> o1.getAge().compareTo(o2.getAge())).get()); + final Person minByAge = people + .stream() + .min(Comparator.comparing(Person::getAge)) + .orElseThrow(NoSuchElementException::new); + + assertEquals("Should be Alex", alex, minByAge); } } From 41ea1898ebfabef3dda1715e4559feba70018171 Mon Sep 17 00:00:00 2001 From: Zeger Hendrikse Date: Wed, 15 Feb 2017 23:21:13 +0100 Subject: [PATCH 32/33] Moved tests to live tests --- spring-data-neo4j/pom.xml | 5 ----- .../baeldung/neo4j/{Neo4jTest.java => Neo4jLiveTest.java} | 2 +- .../neo4j/{Neo4jOgmTest.java => Neo4jOgmLiveTest.java} | 2 +- 3 files changed, 2 insertions(+), 7 deletions(-) rename spring-data-neo4j/src/test/java/com/baeldung/neo4j/{Neo4jTest.java => Neo4jLiveTest.java} (99%) rename spring-data-neo4j/src/test/java/com/baeldung/neo4j/{Neo4jOgmTest.java => Neo4jOgmLiveTest.java} (97%) diff --git a/spring-data-neo4j/pom.xml b/spring-data-neo4j/pom.xml index 7e7f02e9a9..96606d597b 100644 --- a/spring-data-neo4j/pom.xml +++ b/spring-data-neo4j/pom.xml @@ -96,11 +96,6 @@ spring-test ${spring-test.version}
- - junit - junit - 4.12 -
diff --git a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jTest.java b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java similarity index 99% rename from spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java index c303410e57..1ff01b93a1 100644 --- a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java @@ -18,7 +18,7 @@ import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Result; import org.neo4j.graphdb.factory.GraphDatabaseFactory; -public class Neo4jTest { +public class Neo4jLiveTest { private static GraphDatabaseService graphDb; diff --git a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmTest.java b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java similarity index 97% rename from spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java index 3e218f39d7..06b31667dd 100644 --- a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java @@ -14,7 +14,7 @@ import com.baeldung.spring.data.neo4j.domain.Car; import com.baeldung.spring.data.neo4j.domain.Company; import org.neo4j.ogm.transaction.Transaction; -public class Neo4jOgmTest { +public class Neo4jOgmLiveTest { @Test public void testOgm() { From a4c5fb1c128570c340f39f859f0dd3575503305f Mon Sep 17 00:00:00 2001 From: Nancy Bosecker Date: Wed, 15 Feb 2017 15:48:53 -0800 Subject: [PATCH 33/33] Solr w Apache SolrJ (#1073) * Solr w Apache SolrJ * Solr w Apache SolrJ --- spring-data-solr/pom.xml | 6 ++ .../solrjava/SolrJavaIntegrationTest.java | 70 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java diff --git a/spring-data-solr/pom.xml b/spring-data-solr/pom.xml index e43b3ff774..2aa9f86a96 100644 --- a/spring-data-solr/pom.xml +++ b/spring-data-solr/pom.xml @@ -51,6 +51,12 @@ ${spring.version} test + diff --git a/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java b/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java new file mode 100644 index 0000000000..1613ba5480 --- /dev/null +++ b/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.solrjava; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.solr.client.solrj.SolrQuery; +import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.apache.solr.client.solrj.impl.XMLResponseParser; +import org.apache.solr.client.solrj.response.QueryResponse; +import org.apache.solr.common.SolrDocument; +import org.apache.solr.common.SolrDocumentList; +import org.apache.solr.common.SolrInputDocument; +import org.junit.Before; +import org.junit.Test; + +public class SolrJavaIntegrationTest { + + private HttpSolrClient solr; + + @Before + public void setUp() throws Exception { + + solr = new HttpSolrClient("http://localhost:8983/solr/bigboxstore"); + solr.setParser(new XMLResponseParser()); + } + + @Test + public void givenAdd_thenVerifyAdded() throws SolrServerException, IOException { + + SolrInputDocument document = new SolrInputDocument(); + document.addField("id", "123456"); + document.addField("name", "Kenmore Dishwasher"); + document.addField("price", "599.99"); + + solr.add(document); + solr.commit(); + + SolrQuery query = new SolrQuery(); + query.set("q", "id:123456"); + QueryResponse response = null; + + response = solr.query(query); + + SolrDocumentList docList = response.getResults(); + assertEquals(docList.getNumFound(), 1); + + for (SolrDocument doc : docList) { + assertEquals((String) doc.getFieldValue("id"), "123456"); + assertEquals((Double) doc.getFieldValue("price"), (Double) 599.99); + } + } + + @Test + public void givenDelete_thenVerifyDeleted() throws SolrServerException, IOException { + + solr.deleteById("123456"); + solr.commit(); + + SolrQuery query = new SolrQuery(); + query.set("q", "id:123456"); + QueryResponse response = null; + + response = solr.query(query); + + SolrDocumentList docList = response.getResults(); + assertEquals(docList.getNumFound(), 0); + } +}