Merge pull request #2 from eugenp/master

merge from eugenp
This commit is contained in:
xamcross 2018-09-12 00:03:21 +03:00 committed by GitHub
commit 26c597a4d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 956 additions and 45 deletions

View File

@ -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 <K, V> Stream<K> keys(Map<K, V> map, V value) {
return map.entrySet()
.stream()
.filter(entry -> value.equals(entry.getValue()))
.map(Map.Entry::getKey);
}
public static <K, V> Set<K> getKeys(Map<K, V> map, V value) {
Set<K> keys = new HashSet<>();
for (Entry<K, V> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
keys.add(entry.getKey());
}
}
return keys;
}
public static <K, V> K getKey(Map<K, V> map, V value) {
for (Entry<K, V> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.collection;
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<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
collection.clear();
assertTrue(collection.isEmpty());
}
@Test
void givenTwoArrayListsWithCommonElements_whenRemoveAll_thenFirstListMissElementsFromSecondList() {
Collection<Integer> firstCollection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collection<Integer> 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);
}
}

View File

@ -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<String, String> 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<String, String> 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<String>(Arrays.asList(
new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),
MapUtil.getKeys(capitalCountryMap, "South Africa"));
}
@Test
public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() {
Map<String, String> 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<String, String> 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<String>(Arrays.asList(
new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),
MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet()));
}
@Test
public void whenUsingBidiMap_shouldReturnKey() {
BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
assertEquals("Berlin", capitalCountryMap.getKey("Germany"));
}
@Test
public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() {
BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>();
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<String, String> 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<String, String> capitalCountryMap = HashBiMap.create();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
assertEquals("Berlin", capitalCountryMap.inverse().get("Germany"));
}
}

View File

@ -55,6 +55,12 @@
<artifactId>fuel-coroutines</artifactId>
<version>${fuel.version}</version>
</dependency>
<dependency>
<groupId>nl.komponents.kovenant</groupId>
<artifactId>kovenant</artifactId>
<version>3.3.0</version>
<type>pom</type>
</dependency>
</dependencies>
<properties>

View File

@ -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<Long, Exception>()
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<Long, Exception>()
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<Long, Exception>()
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)
}
}

View File

@ -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 <T> timedTask(millis: Long, body: () -> T) : Promise<T?, List<Exception>> {
val timeoutTask = task {
Thread.sleep(millis)
null
}
val activeTask = task(body = body)
return any(activeTask, timeoutTask)
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<Employee> employeeList = session.createQuery("from Employee")
.setCacheMode(CacheMode.IGNORE).getResultList();
assertEquals(employeeList.size(), 5);
transaction.commit();
}
}

View File

@ -15,7 +15,7 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class BenchmarkUnitTest
public class BenchmarkManualTest
{
public void

View File

@ -84,6 +84,13 @@
<artifactId>spectator-api</artifactId>
<version>${spectator-api.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>

View File

@ -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

View File

@ -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";

View File

@ -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<String, Number> metricMap = timer
.getMonitors()
@ -235,4 +234,4 @@ public class MetricTypeManualTest {
assertEquals("information collected", informational.getValue());
}
}
}

View File

@ -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);
}
}

View File

@ -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<String> whitelist = new HashSet<String>();
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<GrantedAuthority> authorities =new ArrayList<GrantedAuthority>();
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);
}
}

View File

@ -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
}
}

View File

@ -0,0 +1,9 @@
package org.baeldung.ip.config;
//@Configuration
//@EnableWebSecurity
//@ImportResource({ "classpath:spring-security-ip.xml" })
public class SecurityXmlConfig {
}

View File

@ -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");
}
}

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="john" password="{noop}123" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
<security:http>
<security:form-login/>
<security:intercept-url pattern="/login" access="permitAll()" />
<security:intercept-url pattern="/foos/**" access="hasIpAddress('11.11.11.11')" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
</beans>

View File

@ -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"));
}
}

View File

@ -7,13 +7,13 @@
<artifactId>gatling</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>io.gatling.highcharts</groupId>
@ -76,21 +76,24 @@
<id>simulation</id>
<build>
<plugins>
<plugin>
<groupId>io.gatling</groupId>
<artifactId>gatling-maven-plugin</artifactId>
<version>${gatling-maven-plugin.version}</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>execute</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<plugin>
<groupId>io.gatling</groupId>
<artifactId>gatling-maven-plugin</artifactId>
<version>${gatling-maven-plugin.version}</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<disableCompiler>true</disableCompiler>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
@ -123,10 +126,10 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<encoding>UTF-8</encoding>
<scala.version>2.11.12</scala.version> <!--2.11.12 --> <!--2.12.6 -->
<gatling.version>2.2.5</gatling.version> <!--2.2.5 --> <!--2.3.1 -->
<scala.version>2.12.6</scala.version> <!--2.11.12 --> <!--2.12.6 -->
<gatling.version>2.3.1</gatling.version> <!--2.2.5 --> <!--2.3.1 -->
<scala-maven-plugin.version>3.2.2</scala-maven-plugin.version> <!--3.2.2 --> <!--3.3.2 -->
<gatling-maven-plugin.version>2.2.1</gatling-maven-plugin.version> <!--2.2.1 --> <!--2.2.4 -->
<gatling-maven-plugin.version>2.2.4</gatling-maven-plugin.version> <!--2.2.1 --> <!--2.2.4 -->
</properties>
</project>