Merge branch 'master' into BAEL-1344

This commit is contained in:
abialas 2017-11-17 23:47:33 +01:00
commit cc74888835
35 changed files with 454 additions and 149 deletions

View File

@ -14,3 +14,4 @@
- [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort)
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)

3
apache-spark/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark)

View File

@ -65,6 +65,24 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
<exclude>**/JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
@ -107,4 +125,5 @@
</pluginRepositories>
</project>

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CasSecuredAppApplicationTests {
public class CasSecuredAppApplicationIntegrationTest {
@Test
public void contextLoads() {

View File

@ -30,3 +30,4 @@
- [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)

View File

@ -0,0 +1,52 @@
package com.baeldung.concurrent.stopping;
import java.util.concurrent.atomic.AtomicBoolean;
public class ControlSubThread implements Runnable {
private Thread worker;
private int interval = 100;
private AtomicBoolean running = new AtomicBoolean(false);
private AtomicBoolean stopped = new AtomicBoolean(true);
public ControlSubThread(int sleepInterval) {
interval = sleepInterval;
}
public void start() {
worker = new Thread(this);
worker.start();
}
public void stop() {
running.set(false);
}
public void interrupt() {
running.set(false);
worker.interrupt();
}
boolean isRunning() {
return running.get();
}
boolean isStopped() {
return stopped.get();
}
public void run() {
running.set(true);
stopped.set(false);
while (running.get()) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// no-op, just loop again
}
// do something
}
stopped.set(true);
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.concurrent.stopping;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StopThreadTest {
@Test
public void whenStoppedThreadIsStopped() throws InterruptedException {
int interval = 100;
ControlSubThread controlSubThread = new ControlSubThread(interval);
controlSubThread.start();
// Give things a chance to get set up
Thread.sleep(interval);
assertTrue(controlSubThread.isRunning());
assertFalse(controlSubThread.isStopped());
// Stop it and make sure the flags have been reversed
controlSubThread.stop();
Thread.sleep(interval);
assertTrue(controlSubThread.isStopped());
}
@Test
public void whenInterruptedThreadIsStopped() throws InterruptedException {
int interval = 5000;
ControlSubThread controlSubThread = new ControlSubThread(interval);
controlSubThread.start();
// Give things a chance to get set up
Thread.sleep(100);
assertTrue(controlSubThread.isRunning());
assertFalse(controlSubThread.isStopped());
// Stop it and make sure the flags have been reversed
controlSubThread.interrupt();
// Wait less than the time we would normally sleep, and make sure we exited.
Thread.sleep(interval/10);
assertTrue(controlSubThread.isStopped());
}
}

View File

@ -115,4 +115,5 @@
- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)

View File

@ -2,4 +2,4 @@
This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library.
### Relevant Articles:
- [A Guide to deeplearning4j](http://www.baeldung.com/a-guide-to-deeplearning4j/)
- [A Guide to deeplearning4j](http://www.baeldung.com/deeplearning4j)

View File

@ -26,16 +26,13 @@ public class TestEJBServlet extends HttpServlet {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Users</title></head>");
out.println("<body>");
out.println("<center><h1>List of users:</h1>");
out.println("<table border=\"1\" align=\"center\" style=\"width:50%\">");
for (User user : users) {
out.println("<tr>");
out.print("<td>" + user.getUsername() + "</td>");
out.print("<td>" + user.getEmail() + "</td>");
out.println("</tr>");
out.print(user.getUsername());
out.print(" " + user.getEmail() + " <br>");
}
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

View File

@ -39,7 +39,6 @@
- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv)
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
- [Introduction to NoException](http://www.baeldung.com/no-exception)
- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java)
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
- [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types)
- [Introduction to javax.measure](http://www.baeldung.com/javax-measure)
@ -53,7 +52,11 @@
- [Using Pairs in Java](http://www.baeldung.com/java-pairs)
- [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag)
- [Introduction to Caffeine](http://www.baeldung.com/java-caching-caffeine)
+-[Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [Introduction To Docx4J](http://www.baeldung.com/docx4j)
- [Introduction to StreamEx](http://www.baeldung.com/streamex)
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -2,3 +2,4 @@
- [Intro to Dropwizard Metrics](http://www.baeldung.com/dropwizard-metrics)
- [Introduction to Netflix Servo](http://www.baeldung.com/netflix-servo)
- [Quick Guide to Micrometer](http://www.baeldung.com/micrometer)

View File

@ -8,3 +8,4 @@
- [Observable Utility Operators in RxJava](http://www.baeldung.com/rxjava-observable-operators)
- [Introduction to rxjava-jdbc](http://www.baeldung.com/rxjava-jdbc)
- [Schedulers in RxJava](http://www.baeldung.com/rxjava-schedulers)
- [Mathematical and Aggregate Operators in RxJava](http://www.baeldung.com/rxjava-math)

View File

@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M3</version>
<version>2.0.0.M6</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
@ -99,6 +99,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
@ -189,7 +194,7 @@
<junit.platform.version>1.0.0</junit.platform.version>
<junit.jupiter.version>5.0.0</junit.jupiter.version>
<maven-surefire-plugin.version>2.20</maven-surefire-plugin.version>
<spring.version>5.0.0.RELEASE</spring.version>
<spring.version>5.0.1.RELEASE</spring.version>
<reactor-spring.version>1.0.1.RELEASE</reactor-spring.version>
<johnzon.version>1.1.3</johnzon.version>
<jsonb-api.version>1.0</jsonb-api.version>

View File

@ -0,0 +1,34 @@
package com.baeldung;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import reactor.ipc.netty.NettyContext;
import reactor.ipc.netty.http.server.HttpServer;
@ComponentScan(basePackages = {"com.baeldung.security"})
@EnableWebFlux
public class SpringSecurity5Application {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(SpringSecurity5Application.class)) {
context.getBean(NettyContext.class).onClose().block();
}
}
@Bean
public NettyContext nettyContext(ApplicationContext context) {
HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context)
.build();
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
HttpServer httpServer = HttpServer.create("localhost", 8080);
return httpServer.newHandler(adapter).block();
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.security;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.security.Principal;
@RestController
public class GreetController {
private GreetService greetService;
public GreetController(GreetService greetService) {
this.greetService = greetService;
}
@GetMapping("/")
public Mono<String> greet(Mono<Principal> principal) {
return principal
.map(Principal::getName)
.map(name -> String.format("Hello, %s", name));
}
@GetMapping("/admin")
public Mono<String> greetAdmin(Mono<Principal> principal) {
return principal
.map(Principal::getName)
.map(name -> String.format("Admin access: %s", name));
}
@GetMapping("/greetService")
public Mono<String> greetService() {
return greetService.greet();
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.security;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class GreetService {
@PreAuthorize("hasRole('ADMIN')")
public Mono<String> greet() {
return Mono.just("Hello from service!");
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.security;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain;
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange()
.pathMatchers("/admin").hasAuthority("ROLE_ADMIN")
.anyExchange().authenticated()
.and().formLogin()
.and().build();
}
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
UserDetails admin = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build();
return new MapReactiveUserDetailsService(user, admin);
}
}

View File

@ -1,6 +1,3 @@
server.port=8081
security.user.name=user
security.user.password=pass
logging.level.root=INFO

View File

@ -0,0 +1,48 @@
package com.baeldung.security;
import com.baeldung.SpringSecurity5Application;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringSecurity5Application.class)
public class SecurityTest {
@Autowired
ApplicationContext context;
private WebTestClient rest;
@Before
public void setup() {
this.rest = WebTestClient
.bindToApplicationContext(this.context)
.configureClient()
.build();
}
@Test
public void whenNoCredentials_thenRedirectToLogin() {
this.rest.get()
.uri("/")
.exchange()
.expectStatus().is3xxRedirection();
}
@Test
@WithMockUser
public void whenHasCredentials_thenSeesGreeting() {
this.rest.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello, user");
}
}

View File

@ -53,7 +53,7 @@ public class WebTestClientTest {
.uri("/resource")
.exchange()
.expectStatus()
.is4xxClientError()
.is3xxRedirection()
.expectBody();
}

View File

@ -3,3 +3,4 @@
- [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti)
- [Introduction to Activiti with Spring](http://www.baeldung.com/spring-activiti)
- [Activiti with Spring Security](http://www.baeldung.com/activiti-spring-security)
- [ProcessEngine Configuration in Activiti](http://www.baeldung.com/activiti-process-engine)

View File

@ -23,3 +23,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent)
- [A CLI with Spring Shell](http://www.baeldung.com/spring-shell-cli)
- [JasperReports with Spring](http://www.baeldung.com/spring-jasper)
- [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view)

View File

@ -19,7 +19,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class SpringBootAdminClientApplicationTests {
public class SpringBootAdminClientApplicationIntegrationTest {
@Autowired Environment environment;

View File

@ -13,7 +13,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { HazelcastConfig.class }, webEnvironment = NONE)
public class HazelcastConfigTest {
public class HazelcastConfigIntegrationTest {
@Autowired private ApplicationContext applicationContext;

View File

@ -16,7 +16,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { NotifierConfiguration.class }, webEnvironment = NONE)
public class NotifierConfigurationTest {
public class NotifierConfigurationIntegrationTest {
@Autowired private ApplicationContext applicationContext;

View File

@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebSecurityConfigTest {
public class WebSecurityConfigIntegrationTest {
@Autowired WebApplicationContext wac;

View File

@ -20,7 +20,7 @@ import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBoot.class)
public class KeycloakConfigurationTest {
public class KeycloakConfigurationIntegrationTest {
@Spy
private KeycloakSecurityContextClientRequestInterceptor factory;

View File

@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class)
public class DataSourceRoutingTests {
public class DataSourceRoutingIntegrationTest {
@Autowired
DataSource routingDatasource;

View File

@ -35,19 +35,17 @@ public class DataSourceRoutingTestConfiguration {
private DataSource clientADatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2)
return dbBuilder.setType(EmbeddedDatabaseType.H2)
.setName("CLIENT_A")
.addScript("classpath:dsrouting-db.sql")
.build();
return embeddedDb;
}
private DataSource clientBDatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2)
return dbBuilder.setType(EmbeddedDatabaseType.H2)
.setName("CLIENT_B")
.addScript("classpath:dsrouting-db.sql")
.build();
return embeddedDb;
}
}

View File

@ -1,7 +1,5 @@
package org.baeldung.properties;
import org.baeldung.properties.ConfigProperties;
import org.baeldung.properties.ConfigPropertiesDemoApplication;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringJMeterJenkinsApplicationTests {
public class SpringJMeterJenkinsApplicationIntegrationTest {
@Test
public void contextLoads() {

View File

@ -1,119 +1,119 @@
package org.baeldung.acl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.baeldung.acl.persistence.dao.NoticeMessageRepository;
import org.baeldung.acl.persistence.entity.NoticeMessage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.test.context.web.ServletTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners(listeners={ServletTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
WithSecurityContextTestExecutionListener.class})
public class SpringAclTest extends AbstractJUnit4SpringContextTests{
private static Integer FIRST_MESSAGE_ID = 1;
private static Integer SECOND_MESSAGE_ID = 2;
private static Integer THIRD_MESSAGE_ID = 3;
private static String EDITTED_CONTENT = "EDITED";
@Configuration
@ComponentScan("org.baeldung.acl.*")
public static class SpringConfig {
}
@Autowired
NoticeMessageRepository repo;
@Test
@WithMockUser(username="manager")
public void givenUsernameManager_whenFindAllMessage_thenReturnFirstMessage(){
List<NoticeMessage> details = repo.findAll();
assertNotNull(details);
assertEquals(1,details.size());
assertEquals(FIRST_MESSAGE_ID,details.get(0).getId());
}
@Test
@WithMockUser(username="manager")
public void givenUsernameManager_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenOK(){
NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(firstMessage);
assertEquals(FIRST_MESSAGE_ID,firstMessage.getId());
firstMessage.setContent(EDITTED_CONTENT);
repo.save(firstMessage);
NoticeMessage editedFirstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(editedFirstMessage);
assertEquals(FIRST_MESSAGE_ID,editedFirstMessage.getId());
assertEquals(EDITTED_CONTENT,editedFirstMessage.getContent());
}
@Test
@WithMockUser(username="hr")
public void givenUsernameHr_whenFindMessageById2_thenOK(){
NoticeMessage secondMessage = repo.findById(SECOND_MESSAGE_ID);
assertNotNull(secondMessage);
assertEquals(SECOND_MESSAGE_ID,secondMessage.getId());
}
@Test(expected=AccessDeniedException.class)
@WithMockUser(username="hr")
public void givenUsernameHr_whenUpdateMessageWithId2_thenFail(){
NoticeMessage secondMessage = new NoticeMessage();
secondMessage.setId(SECOND_MESSAGE_ID);
secondMessage.setContent(EDITTED_CONTENT);
repo.save(secondMessage);
}
@Test
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenFindAllMessage_thenReturnThreeMessage(){
List<NoticeMessage> details = repo.findAll();
assertNotNull(details);
assertEquals(3,details.size());
}
@Test
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenUpdateThirdMessage_thenOK(){
NoticeMessage thirdMessage = new NoticeMessage();
thirdMessage.setId(THIRD_MESSAGE_ID);
thirdMessage.setContent(EDITTED_CONTENT);
repo.save(thirdMessage);
}
@Test(expected=AccessDeniedException.class)
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenFail(){
NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(firstMessage);
assertEquals(FIRST_MESSAGE_ID,firstMessage.getId());
firstMessage.setContent(EDITTED_CONTENT);
repo.save(firstMessage);
}
}
package org.baeldung.acl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.baeldung.acl.persistence.dao.NoticeMessageRepository;
import org.baeldung.acl.persistence.entity.NoticeMessage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.test.context.web.ServletTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners(listeners={ServletTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
WithSecurityContextTestExecutionListener.class})
public class SpringAclIntegrationTest extends AbstractJUnit4SpringContextTests{
private static Integer FIRST_MESSAGE_ID = 1;
private static Integer SECOND_MESSAGE_ID = 2;
private static Integer THIRD_MESSAGE_ID = 3;
private static String EDITTED_CONTENT = "EDITED";
@Configuration
@ComponentScan("org.baeldung.acl.*")
public static class SpringConfig {
}
@Autowired
NoticeMessageRepository repo;
@Test
@WithMockUser(username="manager")
public void givenUsernameManager_whenFindAllMessage_thenReturnFirstMessage(){
List<NoticeMessage> details = repo.findAll();
assertNotNull(details);
assertEquals(1,details.size());
assertEquals(FIRST_MESSAGE_ID,details.get(0).getId());
}
@Test
@WithMockUser(username="manager")
public void givenUsernameManager_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenOK(){
NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(firstMessage);
assertEquals(FIRST_MESSAGE_ID,firstMessage.getId());
firstMessage.setContent(EDITTED_CONTENT);
repo.save(firstMessage);
NoticeMessage editedFirstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(editedFirstMessage);
assertEquals(FIRST_MESSAGE_ID,editedFirstMessage.getId());
assertEquals(EDITTED_CONTENT,editedFirstMessage.getContent());
}
@Test
@WithMockUser(username="hr")
public void givenUsernameHr_whenFindMessageById2_thenOK(){
NoticeMessage secondMessage = repo.findById(SECOND_MESSAGE_ID);
assertNotNull(secondMessage);
assertEquals(SECOND_MESSAGE_ID,secondMessage.getId());
}
@Test(expected=AccessDeniedException.class)
@WithMockUser(username="hr")
public void givenUsernameHr_whenUpdateMessageWithId2_thenFail(){
NoticeMessage secondMessage = new NoticeMessage();
secondMessage.setId(SECOND_MESSAGE_ID);
secondMessage.setContent(EDITTED_CONTENT);
repo.save(secondMessage);
}
@Test
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenFindAllMessage_thenReturnThreeMessage(){
List<NoticeMessage> details = repo.findAll();
assertNotNull(details);
assertEquals(3,details.size());
}
@Test
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenUpdateThirdMessage_thenOK(){
NoticeMessage thirdMessage = new NoticeMessage();
thirdMessage.setId(THIRD_MESSAGE_ID);
thirdMessage.setContent(EDITTED_CONTENT);
repo.save(thirdMessage);
}
@Test(expected=AccessDeniedException.class)
@WithMockUser(roles={"EDITOR"})
public void givenRoleEditor_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenFail(){
NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID);
assertNotNull(firstMessage);
assertEquals(FIRST_MESSAGE_ID,firstMessage.getId());
firstMessage.setContent(EDITTED_CONTENT);
repo.save(firstMessage);
}
}