This commit is contained in:
Dhawal Kapil 2022-06-07 21:10:51 +05:30
commit 071a394377
30 changed files with 301 additions and 34 deletions

View File

@ -4,6 +4,4 @@ This module contains articles about Apache CXF
## Relevant Articles:
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)

View File

@ -1,2 +1,2 @@
### Relevant Articles:
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)

View File

@ -0,0 +1,45 @@
package com.baeldung.httpclient.parameters;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class HttpClientParametersLiveTest {
private static HttpClient client;
@BeforeAll
public static void setUp() {
client = HttpClient.newHttpClient();
}
@Test
public void givenQueryParams_whenGetRequest_thenResponseOk() throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_2)
.uri(URI.create("https://postman-echo.com/get?param1=value1&param2=value2"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
}
@Test
public void givenQueryParams_whenGetRequestWithDefaultConfiguration_thenResponseOk() throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://postman-echo.com/get?param1=value1&param2=value2"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
}
}

View File

@ -13,5 +13,4 @@ This module contains articles about the Java List collection
- [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference)
- [List vs. ArrayList in Java](https://www.baeldung.com/java-list-vs-arraylist)
- [How to Store HashMap<String, ArrayList> Inside a List](https://www.baeldung.com/java-hashmap-inside-list)
- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists)
- [[<-- Prev]](/core-java-modules/core-java-collections-list-2)

View File

@ -5,4 +5,5 @@ This module contains articles about the Java List collection
### Relevant Articles:
- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists)
- [Reverse an ArrayList in Java](https://www.baeldung.com/java-reverse-arraylist)
- [Sort a List Alphabetically in Java](https://www.baeldung.com/java-sort-list-alphabetically)
- [[<-- Prev]](/core-java-modules/core-java-collections-list-3)

View File

@ -2,7 +2,6 @@
- [Introduction to Docker Compose](https://www.baeldung.com/ops/docker-compose)
- [Reusing Docker Layers with Spring Boot](https://www.baeldung.com/docker-layers-spring-boot)
- [Running Spring Boot with PostgreSQL in Docker Compose](https://www.baeldung.com/spring-boot-postgresql-docker)
- [How To Configure Java Heap Size Inside a Docker Container](https://www.baeldung.com/ops/docker-jvm-heap-size)
- [Dockerfile Strategies for Git](https://www.baeldung.com/ops/dockerfile-git-strategies)
- [How to Get Docker-Compose to Always Use the Latest Image](https://www.baeldung.com/ops/docker-compose-latest-image)

View File

@ -1,3 +0,0 @@
### Relevant Articles:
- How to Get Docker-Compose to Always Use the Latest Image

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Running Spring Boot with PostgreSQL in Docker Compose](https://www.baeldung.com/spring-boot-postgresql-docker)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [How To Configure Java Heap Size Inside a Docker Container](https://www.baeldung.com/ops/docker-jvm-heap-size)

View File

@ -9,3 +9,4 @@
- [Convert boolean to int in Java](https://www.baeldung.com/java-boolean-to-int)
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
- [Reverse a Number in Java](https://www.baeldung.com/java-reverse-number)
- [Check if BigDecimal Value Is Zero](https://www.baeldung.com/java-bigdecimal-zero)

View File

@ -4,3 +4,4 @@ This module contains articles about Servlets.
### Relevant Articles:
- [Check if a User Is Logged-in With Servlets and JSP](https://www.baeldung.com/servlets-jsp-check-user-login)
- [How to Mock HttpServletRequest](https://www.baeldung.com/java-httpservletrequest-mock)

View File

@ -41,7 +41,7 @@ public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy {
final String newName = identifier.getText()
.replaceAll(regex, replacement)
.toLowerCase();
return Identifier.toIdentifier(newName);
return Identifier.toIdentifier(newName, identifier.isQuoted());
}
}

View File

@ -5,6 +5,7 @@ hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.globally_quoted_identifiers=true
hibernate.physical_naming_strategy=com.baeldung.hibernate.namingstrategy.CustomPhysicalNamingStrategy
hibernate.implicit_naming_strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl

View File

@ -0,0 +1,13 @@
package com.baeldung.disablingkeycloak;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = { "com.baeldung.disablingkeycloak" })
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.disablingkeycloak;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "false")
public class DisableSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.permitAll();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.disablingkeycloak;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KeycloakConfiguration {
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.disablingkeycloak;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@KeycloakConfiguration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.authenticated();
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.disablingkeycloak;
public class User {
private Long id;
private String firstname;
private String lastname;
public User() {
}
public User(Long id, String firstname, String lastname) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.disablingkeycloak;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{userId}")
public User getCustomer(@PathVariable Long userId) {
return new User(userId, "John", "Doe");
}
}

View File

@ -0,0 +1,7 @@
# Keycloak authentication is enabled for production.
keycloak.enabled=true
keycloak.realm=SpringBootKeycloak
keycloak.auth-server-url=http://localhost:8180/auth
keycloak.resource=login-app
keycloak.bearer-only=true
keycloak.ssl-required=external

View File

@ -0,0 +1,33 @@
package com.baeldung.disablingkeycloak;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@ActiveProfiles("disablingkeycloak")
public class DisablingKeycloakIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenUnauthenticated_whenGettingUser_shouldReturnUser() {
ResponseEntity<User> responseEntity = restTemplate.getForEntity("/users/1", User.class);
assertEquals(HttpStatus.SC_OK, responseEntity.getStatusCodeValue());
assertNotNull(responseEntity.getBody()
.getFirstname());
}
}

View File

@ -8,5 +8,6 @@ This module contains articles about various Spring Boot libraries
- [Open API Server Implementation Using OpenAPI Generator](https://www.baeldung.com/java-openapi-generator-server)
- [An Introduction to Kong](https://www.baeldung.com/kong)
- [Getting Started With GraphQL SPQR and Spring Boot](https://www.baeldung.com/spring-boot-graphql-spqr)
- [How to Test GraphQL Using Postman](https://www.baeldung.com/graphql-postman)
More articles: [[prev -->]](/spring-boot-modules/spring-boot-libraries)

View File

@ -1,7 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-springdoc</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -112,6 +110,8 @@
<include>application.properties</include>
<include>data.sql</include>
<include>schema.sql</include>
<include>app.key</include>
<include>app.pub</include>
</includes>
</resource>
</resources>

View File

@ -52,8 +52,9 @@ public class SecurityConfiguration {
//@formatter:off
return http
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
.antMatchers("/api/auth/**", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**",
"/swagger-ui/index.html")
.antMatchers("/api/auth/**", "/swagger-ui-custom.html" ,"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**",
"/swagger-ui/index.html","/api-docs/**")
.permitAll()
.anyRequest()
.authenticated())

View File

@ -11,7 +11,6 @@ public class SecurityTokenApplication {
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(SecurityTokenApplication.class, args);
SpringApplication.run(SecurityTokenApplication.class);
}
}

View File

@ -30,7 +30,7 @@ class OpenApiJwtIntegrationTest
{
assertNotNull(authenticationApi);
String response = this.restTemplate.getForObject("http://localhost:" + port + "/swagger-ui.html", String.class);
String response = this.restTemplate.getForObject("http://localhost:" + port + "/swagger-ui/index.html", String.class);
assertNotNull(response);
assertTrue(response.contains("Swagger UI"));
@ -43,8 +43,7 @@ class OpenApiJwtIntegrationTest
{
assertNotNull(authenticationApi);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs",
String.class);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/api-docs", String.class);
assertNotNull(response);
assertEquals(HttpStatus.OK, response.getStatusCode());
@ -59,8 +58,8 @@ class OpenApiJwtIntegrationTest
{
assertNotNull(authenticationApi);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs",
String.class);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/api-docs", String.class);
assertNotNull(response);
assertNotNull(response.getBody());
@ -75,8 +74,7 @@ class OpenApiJwtIntegrationTest
{
assertNotNull(authenticationApi);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs",
String.class);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/api-docs", String.class);
assertNotNull(response);
assertNotNull(response.getBody());

View File

@ -1,3 +1,4 @@
## Relevant Articles:
- [Dockerizing a Spring Boot Application](https://www.baeldung.com/dockerizing-spring-boot-application)
- [Docker Compose Restart Policies](https://www.baeldung.com/ops/docker-compose-restart-policies)

View File

@ -50,8 +50,8 @@ class MongoAuthApplicationIntegrationTest {
setUp();
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
.apply(springSecurity())
.build();
}
private void setUp() {
@ -85,34 +85,34 @@ class MongoAuthApplicationIntegrationTest {
@Test
void givenUserCredentials_whenInvokeUserAuthorizedEndPoint_thenReturn200() throws Exception {
mvc.perform(get("/user").with(httpBasic(USER_NAME, PASSWORD)))
.andExpect(status().isOk());
.andExpect(status().isOk());
}
@Test
void givenUserNotExists_whenInvokeEndPoint_thenReturn401() throws Exception {
mvc.perform(get("/user").with(httpBasic("not_existing_user", "password")))
.andExpect(status().isUnauthorized());
.andExpect(status().isUnauthorized());
}
@Test
void givenUserExistsAndWrongPassword_whenInvokeEndPoint_thenReturn401() throws Exception {
mvc.perform(get("/user").with(httpBasic(USER_NAME, "wrong_password")))
.andExpect(status().isUnauthorized());
.andExpect(status().isUnauthorized());
}
@Test
void givenUserCredentials_whenInvokeAdminAuthorizedEndPoint_thenReturn403() throws Exception {
mvc.perform(get("/admin").with(httpBasic(USER_NAME, PASSWORD)))
.andExpect(status().isForbidden());
.andExpect(status().isForbidden());
}
@Test
void givenAdminCredentials_whenInvokeAdminAuthorizedEndPoint_thenReturn200() throws Exception {
mvc.perform(get("/admin").with(httpBasic(ADMIN_NAME, PASSWORD)))
.andExpect(status().isOk());
.andExpect(status().isOk());
mvc.perform(get("/user").with(httpBasic(ADMIN_NAME, PASSWORD)))
.andExpect(status().isOk());
.andExpect(status().isOk());
}
}

View File

@ -1,5 +1,15 @@
package com.baeldung.mockito.additionalanswers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.AdditionalAnswers.answer;
import static org.mockito.AdditionalAnswers.answerVoid;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.AdditionalAnswers;
@ -7,8 +17,6 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
@RunWith(MockitoJUnitRunner.class)
public class BookServiceUnitTest {
@ -65,4 +73,32 @@ public class BookServiceUnitTest {
assertEquals(bookOnIndex, book2);
}
@Test
public void givenMockedMethod_whenMethodInvoked_thenReturnBook() {
Long id = 1L;
when(bookRepository.getByBookId(anyLong())).thenAnswer(answer(BookServiceUnitTest::buildBook));
assertNotNull(bookService.getByBookId(id));
assertEquals("The Stranger", bookService.getByBookId(id).getTitle());
}
@Test
public void givenMockedMethod_whenMethodInvoked_thenReturnVoid() {
Long id = 2L;
when(bookRepository.getByBookId(anyLong())).thenAnswer(answerVoid(BookServiceUnitTest::printBookId));
bookService.getByBookId(id);
verify(bookRepository, times(1)).getByBookId(id);
}
private static Book buildBook(Long bookId) {
return new Book(bookId, "The Stranger", "Albert Camus", 456);
}
private static void printBookId(Long bookId) {
System.out.println(bookId);
}
}