JavaEE workshop #7
Kuba Hejda
(JPA, security, RestTemplate, integration testing)

JPA - Cascade
- One of highly used patterns
- Allows to propagate lifecycle status of the entity down the structure
- PERSIST, MERGE, REMOVE, DETACH, REFRESH, ALL
- comes under behavioral patterns
- chain of receiver objects having the responsibility, depending on run-time conditions, to either handle a request or forward it to the next receiver on the chain
- Real implementation: servlet filters

Filtering the request and response
Spring security
- adds a possibility to secure the application
- allows us to manage users and roles
- many types of authentication - Basic, OAuth, ...
- integrations on other IDM (identity management), Keycloak, Azure, LDAP, AWS Cognito...
- custom authentication filters
- custom security user
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private BasicAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1Pass"))
.roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("adminPass"))
.roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET,"/user/login/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}@Configuration
@RequiredArgsConstructor
public class SecurityConfiguration {
private final SecurityConfigurationProperties securityConfigurationProperties;
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.authorizeHttpRequests((authz) -> authz
.antMatchers(HttpMethod.GET, "/api/v1/products/**", "/api/v1/authors/**", "/api/v1/genres/**", "/api/v1/carts/**")
.permitAll()
.antMatchers(HttpMethod.POST, "/api/v1/orders/**", "/api/v1/carts/**")
.permitAll()
.antMatchers(HttpMethod.PUT, "/api/v1/carts/**")
.permitAll()
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}New Spring security
@Bean
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration()
.setAllowedOriginPatterns(List.of(securityConfigurationProperties.getUrl()));
corsConfiguration.setAllowedMethods(securityConfigurationProperties.getMethods());
corsConfiguration.setAllowedHeaders(List.of("Authorization", "Content-Type"));
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}Global Cors settings
REST - RestTemplate
- Sending REST requests
- tutorial
Integration testing
- Martin Fowler: "ITs determine if independently developed units of software work correctly when they are connected to each other"
- Can be expensive for resources
- Links:
Integration Testing
-
spring-boot-starter-test
- include: assertJ, Mockito, JUnit 5, Hamcrast, ..
- @SpringBootTest
- @TestConfiguration
- @MockBean, @SpyBean
-
Auto configured tests
- Spring MVC tests - @WebMvcTest
- JSON Tests - @JsonTest
- Data JPA Tests - @DataJpaTest
- ...
Java integration tests
-
maven-failsafe-plugin
- designed for running integration tests
- name convention *IT.java, *IT*.java, *ITCase.java
- runs in verify maven phase (not in test phase)
- IT of repository layer
- HyperSQL vs. Derby vs. H2
- Pros: Fast, no external resoruces needed, easy to run in CI
- Cons: Not real production database, SQL syntax can differ, may lead to separate SQL scripts
Java unit tests
-
maven-surefire-plugin
- designed for running unit tests
- name convention *Test.java, *TestCase.java
- runs in test maven phase (not in verify phase)
- Can use Spring context, but not all of it and should not test the integration
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IT</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
<classesDirectory>${project.build.outputDirectory}</classesDirectory>
<includes>
<include>**/*IT</include>
</includes>
</configuration>
</plugin>Q & A
ITA 08 - Workshop 07
By IT-absolvent
ITA 08 - Workshop 07
Workshop #7
- 354