From cc0749ce8a21ab16f0bb8111ee59188e30ffb051 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Thu, 6 Sep 2018 20:15:23 +0200 Subject: [PATCH 01/13] [BAEL-2170] Differences between ArrayList clear and removeAll --- .../list/arraylist/ClearVsRemoveAllTest.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllTest.java b/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllTest.java new file mode 100644 index 0000000000..5b9fbc3415 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllTest.java @@ -0,0 +1,38 @@ +package com.baeldung.list.arraylist; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests demonstrating differences between ArrayList#clear() and ArrayList#removeAll() + */ +class ClearVsRemoveAllTest { + + /* + * Tests + */ + @Test + void givenArrayListWithElements_whenClear_thenListBecomesEmpty() { + ArrayList list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); + + list.clear(); + + assertTrue(list.isEmpty()); + } + + @Test + void givenTwoArrayListsWithCommonElements_whenRemoveAll_thenFirstListMissElementsFromSecondList() { + ArrayList firstList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); + ArrayList secondList = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7)); + + firstList.removeAll(secondList); + + assertEquals(Arrays.asList(1, 2), firstList); + } + +} From 801108b0e1180d2bbd89f2cdeb5028c912aa10c7 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 8 Sep 2018 00:03:05 +0530 Subject: [PATCH 02/13] BAEL-8899 Let's upgrade the Gatling versions -Updated gatling and scala versions to latest --- testing-modules/gatling/pom.xml | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 1afaefd47e..f0906da0bc 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -110,13 +110,10 @@ - 1.8 - 1.8 - UTF-8 - 2.11.12 - 2.2.5 - 3.2.2 - 2.2.1 + 2.13.0-M5 + 2.3.1 + 3.4.2 + 3.0.0-M5 From a0caa18ca2b2a70bd7dbe51159dbf501699c45df Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 8 Sep 2018 00:10:50 +0530 Subject: [PATCH 03/13] Update pom.xml --- testing-modules/gatling/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index f0906da0bc..a78a4e369c 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -112,7 +112,7 @@ 2.13.0-M5 2.3.1 - 3.4.2 + 3.3.1 3.0.0-M5 From 9d70db511801e4366989a6765817d45c0eec5155 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Mon, 10 Sep 2018 22:08:34 +0530 Subject: [PATCH 04/13] BAEL-8899 Let's upgrade the Gatling versions -Fixed dependency versions --- testing-modules/gatling/pom.xml | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index a78a4e369c..08b8545d06 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -7,13 +7,13 @@ gatling 1.0-SNAPSHOT - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + io.gatling.highcharts @@ -78,6 +78,9 @@ execute + + true + @@ -110,10 +113,13 @@ - 2.13.0-M5 - 2.3.1 - 3.3.1 - 3.0.0-M5 + 1.8 + 1.8 + UTF-8 + 2.12.6 + 2.3.1 + 3.2.2 + 2.2.4 From a1194fdfbcda651da3ec8099edd21c6e1f1548eb Mon Sep 17 00:00:00 2001 From: dupirefr Date: Mon, 10 Sep 2018 20:27:21 +0200 Subject: [PATCH 05/13] [BAEL-2170] Renamed test and used Collection instead of ArrayList --- .../list/arraylist/ClearVsRemoveAllTest.java | 38 ------------------ .../arraylist/ClearVsRemoveAllUnitTest.java | 40 +++++++++++++++++++ 2 files changed, 40 insertions(+), 38 deletions(-) delete mode 100644 core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllTest.java create mode 100644 core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllTest.java b/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllTest.java deleted file mode 100644 index 5b9fbc3415..0000000000 --- a/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.list.arraylist; - -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Unit tests demonstrating differences between ArrayList#clear() and ArrayList#removeAll() - */ -class ClearVsRemoveAllTest { - - /* - * Tests - */ - @Test - void givenArrayListWithElements_whenClear_thenListBecomesEmpty() { - ArrayList list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); - - list.clear(); - - assertTrue(list.isEmpty()); - } - - @Test - void givenTwoArrayListsWithCommonElements_whenRemoveAll_thenFirstListMissElementsFromSecondList() { - ArrayList firstList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); - ArrayList secondList = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7)); - - firstList.removeAll(secondList); - - assertEquals(Arrays.asList(1, 2), firstList); - } - -} diff --git a/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllUnitTest.java new file mode 100644 index 0000000000..5e31a326b8 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.list.arraylist; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests demonstrating differences between ArrayList#clear() and ArrayList#removeAll() + */ +class ClearVsRemoveAllUnitTest { + + /* + * Tests + */ + @Test + void givenArrayListWithElements_whenClear_thenListBecomesEmpty() { + Collection collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); + + collection.clear(); + + assertTrue(collection.isEmpty()); + } + + @Test + void givenTwoArrayListsWithCommonElements_whenRemoveAll_thenFirstListMissElementsFromSecondList() { + Collection firstCollection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); + Collection secondCollection = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7)); + + firstCollection.removeAll(secondCollection); + + assertEquals(Arrays.asList(1, 2), firstCollection); + assertEquals(Arrays.asList(3, 4, 5, 6, 7), secondCollection); + } + +} From 69c6c30d8d88da267c6f44ef2207743bcc7a9be4 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Mon, 10 Sep 2018 20:28:27 +0200 Subject: [PATCH 06/13] [BAEL-2170] Moved code to Collection-dedicated package --- .../arraylist => collection}/ClearVsRemoveAllUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-java-collections/src/test/java/com/baeldung/{list/arraylist => collection}/ClearVsRemoveAllUnitTest.java (96%) diff --git a/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllUnitTest.java b/core-java-collections/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java similarity index 96% rename from core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java index 5e31a326b8..8b0a7ef0db 100644 --- a/core-java-collections/src/test/java/com/baeldung/list/arraylist/ClearVsRemoveAllUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.list.arraylist; +package com.baeldung.collection; import org.junit.jupiter.api.Test; From 50f0d571824e9a788b676229e93a4f7d76784aca Mon Sep 17 00:00:00 2001 From: Felipe Santiago Corro Date: Mon, 10 Sep 2018 18:01:47 -0300 Subject: [PATCH 07/13] Proxy in Hibernate load() method (#5222) --- .../hibernate/proxy/BatchEmployee.java | 56 ++++++++++++++ .../com/baeldung/hibernate/proxy/Boss.java | 49 ++++++++++++ .../baeldung/hibernate/proxy/Employee.java | 53 +++++++++++++ .../hibernate/proxy/HibernateUtil.java | 57 ++++++++++++++ .../proxy/HibernateProxyUnitTest.java | 75 +++++++++++++++++++ 5 files changed, 290 insertions(+) create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java create mode 100644 hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java new file mode 100644 index 0000000000..00643ab3dd --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java @@ -0,0 +1,56 @@ +package com.baeldung.hibernate.proxy; + +import org.hibernate.annotations.BatchSize; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@BatchSize(size = 5) +public class BatchEmployee implements Serializable { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + private Boss boss; + + @Column(name = "name") + private String name; + + @Column(name = "surname") + private String surname; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Boss getBoss() { + return boss; + } + + public void setBoss(Boss boss) { + this.boss = boss; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java new file mode 100644 index 0000000000..b6e01814d0 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java @@ -0,0 +1,49 @@ +package com.baeldung.hibernate.proxy; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class Boss implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "surname") + private String surname; + + public Boss() { } + + public Boss(String name, String surname) { + this.name = name; + this.surname = surname; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java new file mode 100644 index 0000000000..6bc64c35ef --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java @@ -0,0 +1,53 @@ +package com.baeldung.hibernate.proxy; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class Employee implements Serializable { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + private Boss boss; + + @Column(name = "name") + private String name; + + @Column(name = "surname") + private String surname; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Boss getBoss() { + return boss; + } + + public void setBoss(Boss boss) { + this.boss = boss; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java new file mode 100644 index 0000000000..e6ad0432bd --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.proxy; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).build(); + } + return sessionFactory; + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addPackage("com.baeldung.hibernate.proxy"); + metadataSources.addAnnotatedClass(Boss.class); + metadataSources.addAnnotatedClass(Employee.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java new file mode 100644 index 0000000000..fa41797dd2 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java @@ -0,0 +1,75 @@ +package com.baeldung.hibernate.proxy; + +import org.hibernate.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.fail; + +public class HibernateProxyUnitTest { + + private Session session; + + @Before + public void init(){ + try { + session = HibernateUtil.getSessionFactory("hibernate.properties") + .openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + + Boss boss = new Boss("Eduard", "Freud"); + session.save(boss); + } + + @After + public void close(){ + if(session != null) { + session.close(); + } + } + + @Test(expected = NullPointerException.class) + public void givenAnInexistentEmployeeId_whenUseGetMethod_thenReturnNull() { + Employee employee = session.get(Employee.class, new Long(14)); + assertNull(employee); + employee.getId(); + } + + @Test + public void givenAnInexistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() { + Employee employee = session.load(Employee.class, new Long(14)); + assertNotNull(employee); + } + + @Test + public void givenABatchEmployeeList_whenSaveOne_thenSaveTheWholeBatch() { + Transaction transaction = session.beginTransaction(); + + for (long i = 1; i <= 5; i++) { + Employee employee = new Employee(); + employee.setName("Employee " + i); + session.save(employee); + } + + //After this line is possible to see all the insertions in the logs + session.flush(); + session.clear(); + transaction.commit(); + + transaction = session.beginTransaction(); + + List employeeList = session.createQuery("from Employee") + .setCacheMode(CacheMode.IGNORE).getResultList(); + + assertEquals(employeeList.size(), 5); + transaction.commit(); + } +} From ba32ee32c6b00773b2122a33c6dfa17350f07c3b Mon Sep 17 00:00:00 2001 From: xamcross Date: Tue, 11 Sep 2018 06:43:06 +0300 Subject: [PATCH 08/13] BAEL-2070 Qualifier used instead of Primary (#5205) * BAEL-2070 Qualifier used instead of Primary to distinguish between different repository beans * BAEL-2095 CrudRepository save() method * (REVERT) BAEL-2095 CrudRepository save() method --- .../baeldung/dependency/exception/app/PurchaseDeptService.java | 3 ++- .../dependency/exception/repository/DressRepository.java | 3 ++- .../dependency/exception/repository/ShoeRepository.java | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java index 1e6fad63aa..e0fe01acdd 100644 --- a/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java @@ -1,13 +1,14 @@ package com.baeldung.dependency.exception.app; import com.baeldung.dependency.exception.repository.InventoryRepository; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service public class PurchaseDeptService { private InventoryRepository repository; - public PurchaseDeptService(InventoryRepository repository) { + public PurchaseDeptService(@Qualifier("dresses") InventoryRepository repository) { this.repository = repository; } } \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java index 4a6c836143..5a1371ce04 100644 --- a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java @@ -1,9 +1,10 @@ package com.baeldung.dependency.exception.repository; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Repository; -@Primary +@Qualifier("dresses") @Repository public class DressRepository implements InventoryRepository { } diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java index 60495914cd..227d8934b6 100644 --- a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java @@ -1,7 +1,9 @@ package com.baeldung.dependency.exception.repository; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; +@Qualifier("shoes") @Repository public class ShoeRepository implements InventoryRepository { } From 57b6480e73e526a6cc2f6095947a2358c9f1ed32 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Mon, 10 Sep 2018 23:43:35 -0400 Subject: [PATCH 09/13] Examples for article on Kovenant (#5011) * Examples of Reflection in Kotlin * Some article updates to make better use of Assert * Replaced printlines with log statements * Added @Ignore to so tests with no assertions * Examples for Kovenant * Fixed an issue where tests fail depending on the order they are run * Test for timeouts on promises --- core-kotlin/pom.xml | 6 + .../com/baeldung/kotlin/KovenantTest.kt | 191 ++++++++++++++++++ .../baeldung/kotlin/KovenantTimeoutTest.kt | 38 ++++ 3 files changed, 235 insertions(+) create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 70cbd67645..0894a57320 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -55,6 +55,12 @@ fuel-coroutines ${fuel.version} + + nl.komponents.kovenant + kovenant + 3.3.0 + pom + diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt new file mode 100644 index 0000000000..469118f0f6 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt @@ -0,0 +1,191 @@ +package com.baeldung.kotlin + +import nl.komponents.kovenant.* +import nl.komponents.kovenant.Kovenant.deferred +import nl.komponents.kovenant.combine.and +import nl.komponents.kovenant.combine.combine +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import java.io.IOException +import java.util.* +import java.util.concurrent.TimeUnit + +class KovenantTest { + @Before + fun setupTestMode() { + Kovenant.testMode { error -> + println("An unexpected error occurred") + Assert.fail(error.message) + } + } + + @Test + fun testSuccessfulDeferred() { + val def = deferred() + Assert.assertFalse(def.promise.isDone()) + + def.resolve(1L) + Assert.assertTrue(def.promise.isDone()) + Assert.assertTrue(def.promise.isSuccess()) + Assert.assertFalse(def.promise.isFailure()) + } + + @Test + fun testFailedDeferred() { + val def = deferred() + Assert.assertFalse(def.promise.isDone()) + + def.reject(RuntimeException()) + Assert.assertTrue(def.promise.isDone()) + Assert.assertFalse(def.promise.isSuccess()) + Assert.assertTrue(def.promise.isFailure()) + } + + @Test + fun testResolveDeferredTwice() { + val def = deferred() + def.resolve(1L) + try { + def.resolve(1L) + } catch (e: AssertionError) { + // Expected. + // This is slightly unusual. The AssertionError comes from Assert.fail() from setupTestMode() + } + } + + @Test + fun testSuccessfulTask() { + val promise = task { 1L } + Assert.assertTrue(promise.isDone()) + Assert.assertTrue(promise.isSuccess()) + Assert.assertFalse(promise.isFailure()) + } + + @Test + fun testFailedTask() { + val promise = task { throw RuntimeException() } + Assert.assertTrue(promise.isDone()) + Assert.assertFalse(promise.isSuccess()) + Assert.assertTrue(promise.isFailure()) + } + + @Test + fun testCallbacks() { + val promise = task { 1L } + + promise.success { + println("This was a success") + Assert.assertEquals(1L, it) + } + + promise.fail { + println(it) + Assert.fail("This shouldn't happen") + } + + promise.always { + println("This always happens") + } + } + + @Test + fun testGetValues() { + val promise = task { 1L } + Assert.assertEquals(1L, promise.get()) + } + + @Test + fun testAllSucceed() { + val numbers = all( + task { 1L }, + task { 2L }, + task { 3L } + ) + + Assert.assertEquals(listOf(1L, 2L, 3L), numbers.get()) + } + + @Test + fun testOneFails() { + val runtimeException = RuntimeException() + + val numbers = all( + task { 1L }, + task { 2L }, + task { throw runtimeException } + ) + + Assert.assertEquals(runtimeException, numbers.getError()) + } + + @Test + fun testAnySucceeds() { + val promise = any( + task { + TimeUnit.SECONDS.sleep(3) + 1L + }, + task { + TimeUnit.SECONDS.sleep(2) + 2L + }, + task { + TimeUnit.SECONDS.sleep(1) + 3L + } + ) + + Assert.assertTrue(promise.isDone()) + Assert.assertTrue(promise.isSuccess()) + Assert.assertFalse(promise.isFailure()) + } + + @Test + fun testAllFails() { + val runtimeException = RuntimeException() + val ioException = IOException() + val illegalStateException = IllegalStateException() + val promise = any( + task { + TimeUnit.SECONDS.sleep(3) + throw runtimeException + }, + task { + TimeUnit.SECONDS.sleep(2) + throw ioException + }, + task { + TimeUnit.SECONDS.sleep(1) + throw illegalStateException + } + ) + + Assert.assertTrue(promise.isDone()) + Assert.assertFalse(promise.isSuccess()) + Assert.assertTrue(promise.isFailure()) + } + + @Test + fun testSimpleCombine() { + val promise = task { 1L } and task { "Hello" } + val result = promise.get() + + Assert.assertEquals(1L, result.first) + Assert.assertEquals("Hello", result.second) + } + + @Test + fun testLongerCombine() { + val promise = combine( + task { 1L }, + task { "Hello" }, + task { Currency.getInstance("USD") } + ) + val result = promise.get() + + Assert.assertEquals(1L, result.first) + Assert.assertEquals("Hello", result.second) + Assert.assertEquals(Currency.getInstance("USD"), result.third) + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt new file mode 100644 index 0000000000..e37d2cc2fa --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt @@ -0,0 +1,38 @@ +package com.baeldung.kotlin + +import nl.komponents.kovenant.Promise +import nl.komponents.kovenant.any +import nl.komponents.kovenant.task +import org.junit.Assert +import org.junit.Ignore +import org.junit.Test + +@Ignore +// Note that this can not run in the same test run if KovenantTest has already been executed +class KovenantTimeoutTest { + @Test + fun testTimeout() { + val promise = timedTask(1000) { "Hello" } + val result = promise.get() + Assert.assertEquals("Hello", result) + } + + @Test + fun testTimeoutExpired() { + val promise = timedTask(1000) { + Thread.sleep(3000) + "Hello" + } + val result = promise.get() + Assert.assertNull(result) + } + + fun timedTask(millis: Long, body: () -> T) : Promise> { + val timeoutTask = task { + Thread.sleep(millis) + null + } + val activeTask = task(body = body) + return any(activeTask, timeoutTask) + } +} From fe96e112a57d74223008b0dc73aff10d64f3056f Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Tue, 11 Sep 2018 09:26:33 +0530 Subject: [PATCH 10/13] BAEL-2178 (#5194) * BAEL-2178 * revert previous commit, adding classes to collections project --- .../java/com/baeldung/java/map/MapUtil.java | 44 ++++++++ .../baeldung/java/map/MapUtilUnitTest.java | 104 ++++++++++++++++++ 2 files changed, 148 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java create mode 100644 core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java diff --git a/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java b/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java new file mode 100644 index 0000000000..688c7592f3 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java @@ -0,0 +1,44 @@ +/** + * + */ +package com.baeldung.java.map; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import java.util.stream.Stream; + +/** + * @author swpraman + * + */ +public class MapUtil { + + public static Stream keys(Map map, V value) { + return map.entrySet() + .stream() + .filter(entry -> value.equals(entry.getValue())) + .map(Map.Entry::getKey); + } + + public static Set getKeys(Map map, V value) { + Set keys = new HashSet<>(); + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) { + keys.add(entry.getKey()); + } + } + return keys; + } + + public static K getKey(Map map, V value) { + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) { + return entry.getKey(); + } + } + return null; + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java new file mode 100644 index 0000000000..e31385e972 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java @@ -0,0 +1,104 @@ +/** + * + */ +package com.baeldung.java.map; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.collections4.BidiMap; +import org.apache.commons.collections4.bidimap.DualHashBidiMap; +import org.junit.Test; + +import com.google.common.collect.HashBiMap; + +/** + * @author swpraman + * + */ +public class MapUtilUnitTest { + + + @Test + public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("New Delhi", "India"); + assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India")); + } + + @Test + public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + capitalCountryMap.put("Bloemfontein", "South Africa"); + + assertEquals(new HashSet(Arrays.asList( + new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), + MapUtil.getKeys(capitalCountryMap, "South Africa")); + } + + @Test + public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get()); + } + + @Test + public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + capitalCountryMap.put("Bloemfontein", "South Africa"); + assertEquals(new HashSet(Arrays.asList( + new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), + MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet())); + } + + @Test + public void whenUsingBidiMap_shouldReturnKey() { + BidiMap capitalCountryMap = new DualHashBidiMap(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + assertEquals("Berlin", capitalCountryMap.getKey("Germany")); + } + + @Test + public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() { + BidiMap capitalCountryMap = new DualHashBidiMap(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + assertEquals("Pretoria", capitalCountryMap.getKey("South Africa")); + } + + @Test + public void whenUsingBiMap_shouldReturnKey() { + HashBiMap capitalCountryMap = HashBiMap.create(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingBiMapAddDuplicateValue_shouldThrowException() { + HashBiMap capitalCountryMap = HashBiMap.create(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); + } + +} From a05fc4f82a925b5d9ae6636e788f071d7b5bdce9 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Tue, 11 Sep 2018 12:48:31 +0530 Subject: [PATCH 11/13] BAEL-8902 Metrics Project Test Fails - Fixed tests --- metrics/pom.xml | 7 ++++ .../MicrometerAtlasIntegrationTest.java | 11 +++++-- .../metrics/servo/AtlasObserverLiveTest.java | 3 ++ .../metrics/servo/MetricTypeManualTest.java | 33 +++++++++---------- 4 files changed, 35 insertions(+), 19 deletions(-) diff --git a/metrics/pom.xml b/metrics/pom.xml index 86f197240b..9cf1ec588f 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -84,6 +84,13 @@ spectator-api ${spectator-api.version} + + + org.assertj + assertj-core + test + + diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java index e7f3d7ec72..689e23ad6d 100644 --- a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java @@ -1,8 +1,12 @@ package com.baeldung.metrics.micrometer; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; +import static org.assertj.core.api.Assertions.withinPercentage; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import io.micrometer.atlas.AtlasMeterRegistry; @@ -31,8 +35,10 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import org.assertj.core.data.Percentage; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import com.netflix.spectator.atlas.AtlasConfig; @@ -156,7 +162,8 @@ public class MicrometerAtlasIntegrationTest { timer.record(30, TimeUnit.MILLISECONDS); assertTrue(2 == timer.count()); - assertTrue(50 > timer.totalTime(TimeUnit.MILLISECONDS) && 45 <= timer.totalTime(TimeUnit.MILLISECONDS)); + + assertThat(timer.totalTime(TimeUnit.MILLISECONDS)).isBetween(40.0, 55.0); } @Test @@ -173,7 +180,7 @@ public class MicrometerAtlasIntegrationTest { } long timeElapsed = longTaskTimer.stop(currentTaskId); - assertTrue(timeElapsed / (int) 1e6 == 2); + assertEquals(2L, timeElapsed/((int) 1e6),1L); } @Test diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java index 134c3c91cf..b8a5b93e49 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java @@ -27,6 +27,9 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; +/** + * Atlas server needs to be up and running for this live test to work. + */ public class AtlasObserverLiveTest { private final String atlasUri = "http://localhost:7101/api/v1"; diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeManualTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeManualTest.java index d810de155a..92bbd615b9 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeManualTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeManualTest.java @@ -109,20 +109,20 @@ public class MetricTypeManualTest { .build(), MILLISECONDS); Stopwatch stopwatch = timer.start(); - MILLISECONDS.sleep(1); - timer.record(2, MILLISECONDS); + SECONDS.sleep(1); + timer.record(2, SECONDS); stopwatch.stop(); - assertEquals("timer should count 1 millisecond", 1, timer + assertEquals("timer should count 1 second", 1000, timer .getValue() - .intValue()); - assertEquals("timer should count 3 millisecond in total", 3, timer.getTotalTime() - .intValue()); + .intValue(),1000); + assertEquals("timer should count 3 second in total", 3000, timer.getTotalTime() + .intValue(),1000); assertEquals("timer should record 2 updates", 2, timer .getCount() .intValue()); - assertEquals("timer should have max 2", 2, timer.getMax(), 0.01); + assertEquals("timer should have max 2", 2000, timer.getMax(), 0.01); } @Test @@ -161,7 +161,6 @@ public class MetricTypeManualTest { } @Test - //== public void givenStatsTimer_whenExecuteTask_thenStatsCalculated() throws Exception { System.setProperty("netflix.servo", "1000"); StatsTimer timer = new StatsTimer(MonitorConfig @@ -178,21 +177,21 @@ public class MetricTypeManualTest { .build(), MILLISECONDS); Stopwatch stopwatch = timer.start(); - MILLISECONDS.sleep(1); - timer.record(3, MILLISECONDS); + SECONDS.sleep(1); + timer.record(3, SECONDS); stopwatch.stop(); stopwatch = timer.start(); - timer.record(6, MILLISECONDS); - MILLISECONDS.sleep(2); + timer.record(6, SECONDS); + SECONDS.sleep(2); stopwatch.stop(); - assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalTime()); - assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalMeasurement()); + assertEquals("timer should count 12 seconds in total", 12000, timer.getTotalTime(),500); + assertEquals("timer should count 12 seconds in total", 12000, timer.getTotalMeasurement(),500); assertEquals("timer should record 4 updates", 4, timer.getCount()); - assertEquals("stats timer value time-cost/update should be 2", 3, timer + assertEquals("stats timer value time-cost/update should be 2", 3000, timer .getValue() - .intValue()); + .intValue(),500); final Map metricMap = timer .getMonitors() @@ -235,4 +234,4 @@ public class MetricTypeManualTest { assertEquals("information collected", informational.getValue()); } -} +} \ No newline at end of file From 0553cb63506fe3b570dfd022df666013b6c9240b Mon Sep 17 00:00:00 2001 From: Sam Millington Date: Tue, 11 Sep 2018 13:24:11 +0100 Subject: [PATCH 12/13] Update and rename BenchmarkUnitTest.java to BenchmarkManualTest.java (#5225) --- .../{BenchmarkUnitTest.java => BenchmarkManualTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename java-streams/src/test/java/com/baeldung/streamordering/{BenchmarkUnitTest.java => BenchmarkManualTest.java} (98%) diff --git a/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java b/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java similarity index 98% rename from java-streams/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java rename to java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java index ba1cb1f726..656a6d95f9 100644 --- a/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java @@ -15,7 +15,7 @@ import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; -public class BenchmarkUnitTest +public class BenchmarkManualTest { public void From 7b256aa060c7fb0be7ecd4458b20793d946316ef Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Tue, 11 Sep 2018 21:41:30 +0200 Subject: [PATCH 13/13] whitelist ip range (#5221) --- .../java/org/baeldung/ip/IpApplication.java | 12 +++++ .../CustomIpAuthenticationProvider.java | 53 +++++++++++++++++++ .../baeldung/ip/config/SecurityConfig.java | 36 +++++++++++++ .../baeldung/ip/config/SecurityXmlConfig.java | 9 ++++ .../org/baeldung/ip/web/MainController.java | 21 ++++++++ .../src/main/resources/spring-security-ip.xml | 21 ++++++++ .../java/org/baeldung/web/IpLiveTest.java | 27 ++++++++++ 7 files changed, 179 insertions(+) create mode 100644 spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java create mode 100644 spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java create mode 100644 spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java create mode 100644 spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java create mode 100644 spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java create mode 100644 spring-security-mvc-boot/src/main/resources/spring-security-ip.xml create mode 100644 spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java new file mode 100644 index 0000000000..fd270686a2 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java @@ -0,0 +1,12 @@ +package org.baeldung.ip; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class IpApplication extends SpringBootServletInitializer { + public static void main(String[] args) { + SpringApplication.run(IpApplication.class, args); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java new file mode 100644 index 0000000000..078dd81259 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java @@ -0,0 +1,53 @@ +package org.baeldung.ip.config; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.web.authentication.WebAuthenticationDetails; +import org.springframework.stereotype.Component; + +@Component +public class CustomIpAuthenticationProvider implements AuthenticationProvider { + + Set whitelist = new HashSet(); + + public CustomIpAuthenticationProvider() { + super(); + whitelist.add("11.11.11.11"); + whitelist.add("127.0.0.1"); + } + + @Override + public Authentication authenticate(Authentication auth) throws AuthenticationException { + WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails(); + String userIp = details.getRemoteAddress(); + if(! whitelist.contains(userIp)){ + throw new BadCredentialsException("Invalid IP Address"); + } + final String name = auth.getName(); + final String password = auth.getCredentials().toString(); + + if (name.equals("john") && password.equals("123")) { + List authorities =new ArrayList(); + authorities.add(new SimpleGrantedAuthority("ROLE_USER")); + return new UsernamePasswordAuthenticationToken(name, password, authorities); + } + else{ + throw new BadCredentialsException("Invalid username or password"); + } + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java new file mode 100644 index 0000000000..b4ed8277d6 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java @@ -0,0 +1,36 @@ +package org.baeldung.ip.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +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; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private CustomIpAuthenticationProvider authenticationProvider; + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("john").password("{noop}123").authorities("ROLE_USER"); + // auth.authenticationProvider(authenticationProvider); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() +// .antMatchers("/foos/**").hasIpAddress("11.11.11.11") + .antMatchers("/foos/**").access("isAuthenticated() and hasIpAddress('11.11.11.11')") + .anyRequest().authenticated() + .and().formLogin().permitAll() + .and().csrf().disable(); + // @formatter:on + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java new file mode 100644 index 0000000000..1d22ca4c67 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java @@ -0,0 +1,9 @@ +package org.baeldung.ip.config; + + +//@Configuration +//@EnableWebSecurity +//@ImportResource({ "classpath:spring-security-ip.xml" }) +public class SecurityXmlConfig { + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java new file mode 100644 index 0000000000..da5db5e825 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java @@ -0,0 +1,21 @@ +package org.baeldung.ip.web; + +import javax.servlet.http.HttpServletRequest; + +import org.baeldung.custom.persistence.model.Foo; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class MainController { + + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id, HttpServletRequest request) { + return new Foo("Sample"); + } + +} diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml b/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml new file mode 100644 index 0000000000..31796ad134 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java new file mode 100644 index 0000000000..e12e2f87b0 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java @@ -0,0 +1,27 @@ +package org.baeldung.web; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import org.junit.Test; + + +public class IpLiveTest { + + @Test + public void givenUser_whenGetHomePage_thenOK() { + final Response response = RestAssured.given().auth().form("john", "123").get("http://localhost:8082/"); + assertEquals(200, response.getStatusCode()); + assertTrue(response.asString().contains("Welcome")); + } + + @Test + public void givenUserWithWrongIP_whenGetFooById_thenForbidden() { + final Response response = RestAssured.given().auth().form("john", "123").get("http://localhost:8082/foos/1"); + assertEquals(403, response.getStatusCode()); + assertTrue(response.asString().contains("Forbidden")); + } + +} \ No newline at end of file