Merge branch 'eugenp:master' into master

This commit is contained in:
Swapan Pramanick 2021-11-05 13:25:54 +01:00 committed by GitHub
commit 807618b5a8
136 changed files with 1595 additions and 1078 deletions

View File

@ -12,3 +12,4 @@ This module contains articles about Apache POI
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula) - [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas) - [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- [Insert a Row in Excel Using Apache POI](https://www.baeldung.com/apache-poi-insert-excel-row) - [Insert a Row in Excel Using Apache POI](https://www.baeldung.com/apache-poi-insert-excel-row)
- [Multiline Text in Excel Cell Using Apache POI](https://www.baeldung.com/apache-poi-write-multiline-text)

View File

@ -0,0 +1,30 @@
package com.baeldung.poi.excel.cellstyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
public class CellStyleHandler {
public void changeCellBackgroundColor(Cell cell) {
CellStyle cellStyle = cell.getCellStyle();
if(cellStyle == null) {
cellStyle = cell.getSheet().getWorkbook().createCellStyle();
}
cellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
}
public void changeCellBackgroundColorWithPattern(Cell cell) {
CellStyle cellStyle = cell.getCellStyle();
if(cellStyle == null) {
cellStyle = cell.getSheet().getWorkbook().createCellStyle();
}
cellStyle.setFillBackgroundColor(IndexedColors.BLACK.index);
cellStyle.setFillPattern(FillPatternType.BIG_SPOTS);
cellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
cell.setCellStyle(cellStyle);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.poi.excel.cellstyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
public class CellStyleHandlerUnitTest {
private static final String FILE_NAME = "cellstyle/CellStyleHandlerTest.xlsx";
private static final int SHEET_INDEX = 0;
private static final int ROW_INDEX = 0;
private static final int CELL_INDEX = 0;
private String fileLocation;
private CellStyleHandler cellStyleHandler;
@Before
public void setup() throws URISyntaxException {
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
cellStyleHandler = new CellStyleHandler();
}
@Test
public void givenWorkbookCell_whenChangeCellBackgroundColor() throws IOException {
Workbook workbook = new XSSFWorkbook(fileLocation);
Sheet sheet = workbook.getSheetAt(SHEET_INDEX);
Row row = sheet.getRow(ROW_INDEX);
Cell cell = row.getCell(CELL_INDEX);
cellStyleHandler.changeCellBackgroundColor(cell);
assertEquals(IndexedColors.LIGHT_BLUE.index, cell.getCellStyle().getFillForegroundColor());
workbook.close();
}
@Test
public void givenWorkbookCell_whenChangeCellBackgroundColorWithPattern() throws IOException {
Workbook workbook = new XSSFWorkbook(fileLocation);
Sheet sheet = workbook.getSheetAt(SHEET_INDEX);
Row row = sheet.getRow(ROW_INDEX);
Cell cell = row.getCell(CELL_INDEX + 1);
cellStyleHandler.changeCellBackgroundColorWithPattern(cell);
assertEquals(IndexedColors.LIGHT_BLUE.index, cell.getCellStyle().getFillForegroundColor());
workbook.close();
}
}

View File

@ -32,24 +32,6 @@
<artifactId>mockserver-junit-jupiter</artifactId> <artifactId>mockserver-junit-jupiter</artifactId>
<version>${mockserver.version}</version> <version>${mockserver.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>

View File

@ -22,18 +22,6 @@
<version>${assertj.version}</version> <version>${assertj.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -27,18 +27,6 @@
<version>${assertj.version}</version> <version>${assertj.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -28,18 +28,6 @@
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <version>3.12.0</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -23,18 +23,6 @@
<version>${assertj.version}</version> <version>${assertj.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -15,11 +15,6 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>com.googlecode.thread-weaver</groupId> <groupId>com.googlecode.thread-weaver</groupId>
<artifactId>threadweaver</artifactId> <artifactId>threadweaver</artifactId>
@ -31,6 +26,12 @@
<artifactId>tempus-fugit</artifactId> <artifactId>tempus-fugit</artifactId>
<version>${tempus-fugit.version}</version> <version>${tempus-fugit.version}</version>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.googlecode.multithreadedtc</groupId> <groupId>com.googlecode.multithreadedtc</groupId>

View File

@ -2,3 +2,4 @@
### Relevant Articles: ### Relevant Articles:
- [Java Naming and Directory Interface Overview](https://www.baeldung.com/jndi) - [Java Naming and Directory Interface Overview](https://www.baeldung.com/jndi)
- [LDAP Authentication Using Pure Java](https://www.baeldung.com/java-ldap-auth)

View File

@ -15,23 +15,6 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId> <artifactId>spring-core</artifactId>
@ -58,6 +41,18 @@
<artifactId>h2</artifactId> <artifactId>h2</artifactId>
<version>${h2.version}</version> <version>${h2.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-test-framework</artifactId>
<version>${apacheds.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.21.0</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -76,6 +71,7 @@
<properties> <properties>
<spring.version>5.0.9.RELEASE</spring.version> <spring.version>5.0.9.RELEASE</spring.version>
<h2.version>1.4.199</h2.version> <h2.version>1.4.199</h2.version>
<apacheds.version>2.0.0.AM26</apacheds.version>
<source.version>1.8</source.version> <source.version>1.8</source.version>
<target.version>1.8</target.version> <target.version>1.8</target.version>
</properties> </properties>

View File

@ -0,0 +1,165 @@
package com.baeldung.jndi.ldap.auth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifFiles;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(FrameworkRunner.class)
@CreateLdapServer(transports = { @CreateTransport(protocol = "LDAP", address = "localhost", port = 10390)})
@CreateDS(
allowAnonAccess = false, partitions = {@CreatePartition(name = "TestPartition", suffix = "dc=baeldung,dc=com")})
@ApplyLdifFiles({"users.ldif"})
// class marked as manual test, as it has to run independently from the other unit tests in the module
public class JndiLdapAuthManualTest extends AbstractLdapTestUnit {
private static void authenticateUser(Hashtable<String, String> environment) throws Exception {
DirContext context = new InitialDirContext(environment);
context.close();
}
@Test
public void givenPreloadedLDAPUserJoe_whenAuthUserWithCorrectPW_thenAuthSucceeds() throws Exception {
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10390");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
environment.put(Context.SECURITY_CREDENTIALS, "12345");
assertThatCode(() -> authenticateUser(environment)).doesNotThrowAnyException();
}
@Test
public void givenPreloadedLDAPUserJoe_whenAuthUserWithWrongPW_thenAuthFails() throws Exception {
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10390");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
environment.put(Context.SECURITY_CREDENTIALS, "wronguserpw");
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> authenticateUser(environment));
}
@Test
public void givenPreloadedLDAPUserJoe_whenSearchAndAuthUserWithCorrectPW_thenAuthSucceeds() throws Exception {
// first authenticate against LDAP as admin to search up DN of user : Joe Simms
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10390");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
environment.put(Context.SECURITY_CREDENTIALS, "secret");
DirContext adminContext = new InitialDirContext(environment);
// define the search filter to find the person with CN : Joe Simms
String filter = "(&(objectClass=person)(cn=Joe Simms))";
// declare the attributes we want returned for the object being searched
String[] attrIDs = { "cn" };
// define the search controls
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(attrIDs);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// search for User with filter cn=Joe Simms
NamingEnumeration<SearchResult> searchResults = adminContext.search("dc=baeldung,dc=com", filter, searchControls);
if (searchResults.hasMore()) {
SearchResult result = (SearchResult) searchResults.next();
Attributes attrs = result.getAttributes();
String distinguishedName = result.getNameInNamespace();
assertThat(distinguishedName).isEqualTo("cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
String commonName = attrs.get("cn").toString();
assertThat(commonName).isEqualTo("cn: Joe Simms");
// authenticate new context with DN for user Joe Simms, using correct password
environment.put(Context.SECURITY_PRINCIPAL, distinguishedName);
environment.put(Context.SECURITY_CREDENTIALS, "12345");
assertThatCode(() -> authenticateUser(environment)).doesNotThrowAnyException();
}
adminContext.close();
}
@Test
public void givenPreloadedLDAPUserJoe_whenSearchAndAuthUserWithWrongPW_thenAuthFails() throws Exception {
// first authenticate against LDAP as admin to search up DN of user : Joe Simms
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10390");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
environment.put(Context.SECURITY_CREDENTIALS, "secret");
DirContext adminContext = new InitialDirContext(environment);
// define the search filter to find the person with CN : Joe Simms
String filter = "(&(objectClass=person)(cn=Joe Simms))";
// declare the attributes we want returned for the object being searched
String[] attrIDs = { "cn" };
// define the search controls
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(attrIDs);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// search for User with filter cn=Joe Simms
NamingEnumeration<SearchResult> searchResults = adminContext.search("dc=baeldung,dc=com", filter, searchControls);
if (searchResults.hasMore()) {
SearchResult result = (SearchResult) searchResults.next();
Attributes attrs = result.getAttributes();
String distinguishedName = result.getNameInNamespace();
assertThat(distinguishedName).isEqualTo("cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
String commonName = attrs.get("cn").toString();
assertThat(commonName).isEqualTo("cn: Joe Simms");
// authenticate new context with DN for user Joe Simms, using wrong password
environment.put(Context.SECURITY_PRINCIPAL, distinguishedName);
environment.put(Context.SECURITY_CREDENTIALS, "wronguserpassword");
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> authenticateUser(environment));
}
adminContext.close();
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,20 @@
version: 1
dn: dc=baeldung,dc=com
objectClass: domain
objectClass: top
dc: baeldung
dn: ou=Users,dc=baeldung,dc=com
objectClass: organizationalUnit
objectClass: top
ou: Users
dn: cn=Joe Simms,ou=Users,dc=baeldung,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: Joe Simms
sn: Simms
uid: user1
userPassword: 12345

View File

@ -15,11 +15,6 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>

View File

@ -16,11 +16,6 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>

View File

@ -0,0 +1,34 @@
package com.baeldung.constructorchaining;
import java.util.Objects;
public class Customer extends Person {
private final String loyaltyCardId;
public Customer(String firstName, String lastName, int age, String loyaltyCardId) {
this(firstName, null, lastName, age, loyaltyCardId);
}
public Customer(String firstName, String middleName, String lastName, int age, String loyaltyCardId) {
super(firstName, middleName, lastName, age);
this.loyaltyCardId = loyaltyCardId;
}
public String getLoyaltyCardId() {
return loyaltyCardId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Customer customer = (Customer) o;
return Objects.equals(loyaltyCardId, customer.loyaltyCardId);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), loyaltyCardId);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.constructorchaining;
import java.util.Objects;
public class Person {
private final String firstName;
private final String middleName;
private final String lastName;
private final int age;
public Person(String firstName, String lastName, int age) {
this(firstName, null, lastName, age);
}
public Person(String firstName, String middleName, String lastName, int age) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getMiddleName() {
return middleName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(firstName, person.firstName) && Objects.equals(middleName, person.middleName) && Objects.equals(lastName, person.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, middleName, lastName, age);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.constructorchaining;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class CustomerUnitTest {
@Test
public void givenNameLastNameAndAge_whenUsingDedicatedConstructor_shouldInitializeFieldsAndNullifyMiddleName() {
Customer mark = new Customer("Mark", "Johnson", 23, "abcd1234");
assertEquals(23, mark.getAge());
assertEquals("Mark", mark.getFirstName());
assertEquals("Johnson", mark.getLastName());
assertEquals("abcd1234", mark.getLoyaltyCardId());
assertNull(mark.getMiddleName());
}
@Test
public void givenAllFieldsRequired_whenUsingDedicatedConstructor_shouldInitializeAllFields() {
Customer mark = new Customer("Mark", "Andrew", "Johnson", 23, "abcd1234");
assertEquals(23, mark.getAge());
assertEquals("Mark", mark.getFirstName());
assertEquals("Andrew", mark.getMiddleName());
assertEquals("Johnson", mark.getLastName());
assertEquals("abcd1234", mark.getLoyaltyCardId());
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.constructorchaining;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class PersonUnitTest {
@Test
public void givenNameLastNameAndAge_whenUsingDedicatedConstructor_shouldInitializeFieldsAndNullifyMiddleName() {
Person mark = new Person("Mark", "Johnson", 23);
assertEquals(23, mark.getAge());
assertEquals("Mark", mark.getFirstName());
assertEquals("Johnson", mark.getLastName());
assertNull(mark.getMiddleName());
}
@Test
public void givenAllFieldsRequired_whenUsingDedicatedConstructor_shouldInitializeAllFields() {
Person mark = new Person("Mark", "Andrew", "Johnson", 23);
assertEquals(23, mark.getAge());
assertEquals("Mark", mark.getFirstName());
assertEquals("Andrew", mark.getMiddleName());
assertEquals("Johnson", mark.getLastName());
}
}

View File

@ -35,11 +35,6 @@
<version>${assertj.version}</version> <version>${assertj.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>com.sun.mail</groupId> <groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId> <artifactId>javax.mail</artifactId>

View File

@ -16,12 +16,6 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId> <artifactId>commons-collections4</artifactId>

View File

@ -30,11 +30,6 @@
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
<version>${log4j.version}</version> <version>${log4j.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>

View File

@ -26,11 +26,6 @@
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>commons-validator</groupId> <groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId> <artifactId>commons-validator</artifactId>

View File

@ -20,11 +20,6 @@
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId> <artifactId>hamcrest</artifactId>

View File

@ -7,3 +7,5 @@
- [Validate String as Filename in Java](https://www.baeldung.com/java-validate-filename) - [Validate String as Filename in Java](https://www.baeldung.com/java-validate-filename)
- [Count Spaces in a Java String](https://www.baeldung.com/java-string-count-spaces) - [Count Spaces in a Java String](https://www.baeldung.com/java-string-count-spaces)
- [Remove Accents and Diacritics From a String in Java](https://www.baeldung.com/java-remove-accents-from-text) - [Remove Accents and Diacritics From a String in Java](https://www.baeldung.com/java-remove-accents-from-text)
- [Remove Beginning and Ending Double Quotes from a String](https://www.baeldung.com/java-remove-start-end-double-quote)
- [Splitting a Java String by Multiple Delimiters](https://www.baeldung.com/java-string-split-multiple-delimiters)

View File

@ -52,6 +52,11 @@
<artifactId>semver4j</artifactId> <artifactId>semver4j</artifactId>
<version>${semver4j.version}</version> <version>${semver4j.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -80,6 +85,7 @@
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<spring-core.version>5.3.9</spring-core.version> <spring-core.version>5.3.9</spring-core.version>
<apache-commons-lang3.version>3.12.0</apache-commons-lang3.version> <apache-commons-lang3.version>3.12.0</apache-commons-lang3.version>
<guava.version>31.0.1-jre</guava.version>
<maven-artifact.version>3.6.3</maven-artifact.version> <maven-artifact.version>3.6.3</maven-artifact.version>
<gradle-core.version>6.1.1</gradle-core.version> <gradle-core.version>6.1.1</gradle-core.version>
<jackson-core.version>2.11.1</jackson-core.version> <jackson-core.version>2.11.1</jackson-core.version>

View File

@ -0,0 +1,66 @@
package com.baeldung.multipledelimiterssplit;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterators;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.Arrays;
import java.util.regex.Pattern;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MultipleDelimitersSplitUnitTest {
@Test
public void givenString_whenSplittingByMultipleDelimitersWithRegEx_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] names = example.split(";|:|-");
String[] expectedNames = new String[]{"Mary", "Thomas", "Jane", "Kate"};
Assertions.assertEquals(4, names.length);
Assertions.assertArrayEquals(expectedNames, names);
}
@Test
public void givenString_whenSplittingByWithCharMatcherAndOnMethod_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] expectedArray = new String[]{"Mary", "Thomas", "Jane", "Kate"};
Iterable<String> expected = Arrays.asList(expectedArray);
Iterable<String> names = Splitter.on(CharMatcher.anyOf(";:-")).split(example);
Assertions.assertEquals(4, Iterators.size(names.iterator()));
Assertions.assertIterableEquals(expected, names);
}
@Test
public void givenString_whenSplittingByWithRegexAndOnPatternMethod_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] expectedArray = new String[]{"Mary", "Thomas", "Jane", "Kate"};
Iterable<String> expected = Arrays.asList(expectedArray);
Iterable<String> names = Splitter.on(Pattern.compile(";|:|-")).split(example);
Assertions.assertEquals(4, Iterators.size(names.iterator()));
Assertions.assertIterableEquals(expected, names);
}
@Test
public void givenString_whenSplittingByMultipleDelimitersWithGuava_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] expectedArray = new String[]{"Mary", "Thomas", "Jane", "Kate"};
Iterable<String> expected = Arrays.asList(expectedArray);
Iterable<String> names = Splitter.onPattern(";|:|-").split(example);
Assertions.assertEquals(4, Iterators.size(names.iterator()));
Assertions.assertIterableEquals(expected, names);
}
@Test
public void givenString_whenSplittingByMultipleDelimitersWithApache_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] expectedNames = new String[]{"Mary", "Thomas", "Jane", "Kate"};
String[] names = StringUtils.split(example, ";:-");
Assertions.assertEquals(4, names.length);
Assertions.assertArrayEquals(expectedNames, names);
}
}

View File

@ -75,8 +75,8 @@
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration> <configuration>
<argLine> <argLine>
-javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
@ -97,8 +97,6 @@
<asspectj.version>1.8.9</asspectj.version> <asspectj.version>1.8.9</asspectj.version>
<powermock.version>2.0.7</powermock.version> <powermock.version>2.0.7</powermock.version>
<jmockit.version>1.44</jmockit.version> <jmockit.version>1.44</jmockit.version>
<!-- plugins -->
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -134,8 +134,4 @@
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
</properties>
</project> </project>

View File

@ -144,18 +144,6 @@
</exclusions> </exclusions>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId> <artifactId>hamcrest</artifactId>

View File

@ -27,18 +27,6 @@
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>

View File

@ -15,21 +15,6 @@
<relativePath>../</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build> <build>
<finalName>guava-collections-map</finalName> <finalName>guava-collections-map</finalName>
<resources> <resources>

View File

@ -16,18 +16,6 @@
<dependencies> <dependencies>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>

View File

@ -32,18 +32,6 @@
<version>${jool.version}</version> <version>${jool.version}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>

View File

@ -14,21 +14,6 @@
<relativePath>../</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build> <build>
<finalName>guava-io</finalName> <finalName>guava-io</finalName>
<resources> <resources>

View File

@ -21,18 +21,6 @@
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>

View File

@ -34,22 +34,9 @@
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<guava.version>29.0-jre</guava.version> <guava.version>29.0-jre</guava.version>
</properties> </properties>

View File

@ -10,4 +10,5 @@ This module contains articles about Jackson conversions.
- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml) - [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml)
- [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api) - [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api)
- [Jackson: java.util.LinkedHashMap cannot be cast to X](https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast) - [Jackson: java.util.LinkedHashMap cannot be cast to X](https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast)
- [Deserialize Snake Case to Camel Case With Jackson](https://www.baeldung.com/jackson-deserialize-snake-to-camel-case)
- More articles: [[<-- prev]](../jackson-conversions) - More articles: [[<-- prev]](../jackson-conversions)

View File

@ -0,0 +1,22 @@
package com.baeldung.jackson.snakecase;
public class User {
private String firstName;
private String lastName;
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,26 @@
package com.baeldung.jackson.snakecase;
import com.fasterxml.jackson.annotation.JsonProperty;
public class UserWithPropertyNames {
@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
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,26 @@
package com.baeldung.jackson.snakecase;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class UserWithSnakeStrategy {
private String firstName;
private String lastName;
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,44 @@
package com.baeldung.jackson.snakecase;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SnakeCaseUnitTest {
private static final String JSON = "{\"first_name\": \"Jackie\", \"last_name\": \"Chan\"}";
@Test(expected = UnrecognizedPropertyException.class)
public void whenExceptionThrown_thenExpectationSatisfied() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(JSON, User.class);
}
@Test
public void givenSnakeCaseJson_whenParseWithJsonPropertyAnnotation_thenGetExpectedObject() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
UserWithPropertyNames user = objectMapper.readValue(JSON, UserWithPropertyNames.class);
assertEquals("Jackie", user.getFirstName());
assertEquals("Chan", user.getLastName());
}
@Test
public void givenSnakeCaseJson_whenParseWithJsonNamingAnnotation_thenGetExpectedObject() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
UserWithSnakeStrategy user = objectMapper.readValue(JSON, UserWithSnakeStrategy.class);
assertEquals("Jackie", user.getFirstName());
assertEquals("Chan", user.getLastName());
}
@Test
public void givenSnakeCaseJson_whenParseWithCustomMapper_thenGetExpectedObject() throws Exception {
ObjectMapper objectMapper = new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
User user = objectMapper.readValue(JSON, User.class);
assertEquals("Jackie", user.getFirstName());
assertEquals("Chan", user.getLastName());
}
}

View File

@ -35,18 +35,6 @@
<artifactId>jackson-dataformat-xml</artifactId> <artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version> <version>${jackson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -22,18 +22,6 @@
<version>${jackson.version}</version> <version>${jackson.version}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>

View File

@ -32,12 +32,6 @@
<artifactId>modelmapper</artifactId> <artifactId>modelmapper</artifactId>
<version>${modelmapper.version}</version> <version>${modelmapper.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId> <artifactId>hamcrest</artifactId>

View File

@ -1136,7 +1136,7 @@
<maven-enforcer-plugin.version>3.0.0-M2</maven-enforcer-plugin.version> <maven-enforcer-plugin.version>3.0.0-M2</maven-enforcer-plugin.version>
<maven-idea-plugin.version>2.2.1</maven-idea-plugin.version> <maven-idea-plugin.version>2.2.1</maven-idea-plugin.version>
<maven-resources-plugin.version>3.1.0</maven-resources-plugin.version> <maven-resources-plugin.version>3.1.0</maven-resources-plugin.version>
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<maven-war-plugin.version>3.2.2</maven-war-plugin.version> <maven-war-plugin.version>3.2.2</maven-war-plugin.version>
<jib-maven-plugin.version>0.9.11</jib-maven-plugin.version> <jib-maven-plugin.version>0.9.11</jib-maven-plugin.version>
<frontend-maven-plugin.version>1.6</frontend-maven-plugin.version> <frontend-maven-plugin.version>1.6</frontend-maven-plugin.version>

6
junit5/README.md Normal file
View File

@ -0,0 +1,6 @@
## JUnit5
This module contains articles about the JUnit 5
### Relevant Articles:

36
junit5/pom.xml Normal file
View File

@ -0,0 +1,36 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>junit5</artifactId>
<name>junit5</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Test;
public class A_UnitTest {
@Test
public void first() throws Exception{
System.out.println("Test A first() start => " + Thread.currentThread().getName());
Thread.sleep(500);
System.out.println("Test A first() end => " + Thread.currentThread().getName());
}
@Test
public void second() throws Exception{
System.out.println("Test A second() start => " + Thread.currentThread().getName());
Thread.sleep(500);
System.out.println("Test A second() end => " + Thread.currentThread().getName());
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
public class B_UnitTest {
@Test
public void first() throws Exception{
System.out.println("Test B first() start => " + Thread.currentThread().getName());
Thread.sleep(500);
System.out.println("Test B first() end => " + Thread.currentThread().getName());
}
@Test
public void second() throws Exception{
System.out.println("Test B second() start => " + Thread.currentThread().getName());
Thread.sleep(500);
System.out.println("Test B second() end => " + Thread.currentThread().getName());
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceLock;
import java.util.ArrayList;
import java.util.List;
public class C_UnitTest {
private List<String> resources;
@BeforeEach
void before() {
resources = new ArrayList<>();
resources.add("test");
}
@AfterEach
void after() {
resources.clear();
}
@Test
@ResourceLock(value = "resources")
public void first() throws Exception {
System.out.println("Test C first() start => " + Thread.currentThread().getName());
resources.add("first");
System.out.println(resources);
Thread.sleep(500);
System.out.println("Test C first() end => " + Thread.currentThread().getName());
}
@Test
@ResourceLock(value = "resources")
public void second() throws Exception {
System.out.println("Test C second() start => " + Thread.currentThread().getName());
resources.add("second");
System.out.println(resources);
Thread.sleep(500);
System.out.println("Test C second() end => " + Thread.currentThread().getName());
}
}

View File

@ -0,0 +1,4 @@
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.config.strategy=dynamic
junit.jupiter.execution.parallel.mode.default = concurrent
junit.jupiter.execution.parallel.mode.classes.default = concurrent

View File

@ -48,11 +48,6 @@
<artifactId>bcpkix-jdk15on</artifactId> <artifactId>bcpkix-jdk15on</artifactId>
<version>${bouncycastle.version}</version> <version>${bouncycastle.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.passay</groupId> <groupId>org.passay</groupId>
<artifactId>passay</artifactId> <artifactId>passay</artifactId>

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>parent-java</artifactId> <artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
@ -40,10 +40,23 @@
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties> <properties>
<guava.version>31.0.1-jre</guava.version> <guava.version>31.0.1-jre</guava.version>
<modelmapper.version>2.3.7</modelmapper.version> <modelmapper.version>2.3.7</modelmapper.version>
<hamcrest.version>2.2</hamcrest.version> <hamcrest.version>2.2</hamcrest.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -21,15 +21,18 @@
<artifactId>spring-core</artifactId> <artifactId>spring-core</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.codehaus.cargo</groupId> <groupId>org.codehaus.cargo</groupId>
@ -54,6 +57,7 @@
<properties> <properties>
<spring.version>4.3.27.RELEASE</spring.version> <spring.version>4.3.27.RELEASE</spring.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version> <cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -21,18 +21,25 @@
<artifactId>spring-core</artifactId> <artifactId>spring-core</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties> <properties>
<spring.version>5.3.9</spring.version> <spring.version>5.3.9</spring.version>
<spring-security.version>5.2.3.RELEASE</spring-security.version> <spring-security.version>5.2.3.RELEASE</spring-security.version>
<spring-boot-starter-test.version>1.5.10.RELEASE</spring-boot-starter-test.version> <spring-boot-starter-test.version>1.5.10.RELEASE</spring-boot-starter-test.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -29,11 +29,6 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
@ -54,14 +49,6 @@
<groupId>org.junit.platform</groupId> <groupId>org.junit.platform</groupId>
<artifactId>junit-platform-engine</artifactId> <artifactId>junit-platform-engine</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.junit.platform</groupId> <groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId> <artifactId>junit-platform-runner</artifactId>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Getting Started With Apache Derby](https://www.baeldung.com/java-apache-derby)

View File

@ -74,6 +74,12 @@
<version>${junit-jupiter.version}</version> <version>${junit-jupiter.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.16.0</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -0,0 +1,30 @@
package com.baeldung.jpa.postgresql_schema;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "product", schema = "store")
public class Product {
@Id
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -149,4 +149,15 @@
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/> <property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties> </properties>
</persistence-unit> </persistence-unit>
<persistence-unit name="postgresql_schema_unit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.postgresql_schema.Product</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver" value="org.postgresql.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL10Dialect"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence> </persistence>

View File

@ -0,0 +1,85 @@
package com.baeldung.jpa.postgresql_schema;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.postgresql.ds.PGSimpleDataSource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class PostgresqlSchemaLiveTest {
//This tests require running Docker application with working internet connection to fetch
//Postgres image if the image is not available locally.
@ClassRule
public static PostgresqlTestContainer container = PostgresqlTestContainer.getInstance();
@BeforeClass
public static void setup() throws Exception {
Properties properties = new Properties();
properties.setProperty("user", container.getUsername());
properties.setProperty("password", container.getPassword());
Connection connection = DriverManager.getConnection(container.getJdbcUrl(), properties);
connection.createStatement().execute("CREATE SCHEMA store");
connection.createStatement().execute("CREATE TABLE store.product(id SERIAL PRIMARY KEY, name VARCHAR(20))");
connection.createStatement().execute("INSERT INTO store.product VALUES(1, 'test product')");
}
@Test
public void settingUpSchemaUsingJdbcURL() throws Exception {
Properties properties = new Properties();
properties.setProperty("user", container.getUsername());
properties.setProperty("password", container.getPassword());
Connection connection = DriverManager.getConnection(container.getJdbcUrl().concat("&currentSchema=store"), properties);
ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM product");
resultSet.next();
assertThat(resultSet.getInt(1), equalTo(1));
assertThat(resultSet.getString(2), equalTo("test product"));
}
@Test
public void settingUpSchemaUsingPGSimpleDataSource() throws Exception {
int port = Integer.parseInt(container.getJdbcUrl().substring(container.getJdbcUrl().lastIndexOf(":") + 1, container.getJdbcUrl().lastIndexOf("/")));
PGSimpleDataSource ds = new PGSimpleDataSource();
ds.setServerNames(new String[]{container.getHost()});
ds.setPortNumbers(new int[]{port});
ds.setUser(container.getUsername());
ds.setPassword(container.getPassword());
ds.setDatabaseName("test");
ds.setCurrentSchema("store");
ResultSet resultSet = ds.getConnection().createStatement().executeQuery("SELECT * FROM product");
resultSet.next();
assertThat(resultSet.getInt(1), equalTo(1));
assertThat(resultSet.getString(2), equalTo("test product"));
}
@Test
public void settingUpSchemaUsingTableAnnotation() {
Map<String, String> props = new HashMap<>();
props.put("hibernate.connection.url", container.getJdbcUrl());
props.put("hibernate.connection.user", container.getUsername());
props.put("hibernate.connection.password", container.getPassword());
EntityManagerFactory emf = Persistence.createEntityManagerFactory("postgresql_schema_unit", props);
EntityManager entityManager = emf.createEntityManager();
Product product = entityManager.find(Product.class, 1);
assertThat(product.getName(), equalTo("test product"));
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.jpa.postgresql_schema;
import org.testcontainers.containers.PostgreSQLContainer;
public class PostgresqlTestContainer extends PostgreSQLContainer<PostgresqlTestContainer> {
private static final String IMAGE_VERSION = "postgres";
private static PostgresqlTestContainer container;
private PostgresqlTestContainer() {
super(IMAGE_VERSION);
}
public static PostgresqlTestContainer getInstance() {
if (container == null) {
container = new PostgresqlTestContainer();
}
return container;
}
}

View File

@ -42,10 +42,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.junit.platform</groupId> <groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId> <artifactId>junit-platform-runner</artifactId>
@ -78,7 +74,6 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration> <configuration>
<verbose>true</verbose> <verbose>true</verbose>
<fork>false</fork> <fork>false</fork>

View File

@ -76,7 +76,6 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration> <configuration>
<forkCount>0</forkCount> <forkCount>0</forkCount>
</configuration> </configuration>

View File

@ -7,6 +7,7 @@
- [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database) - [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database)
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) - [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
- More articles: [[next -->]](/spring-jpa-2) - More articles: [[next -->]](/spring-jpa-2)
### Eclipse Config ### Eclipse Config

View File

@ -472,6 +472,7 @@
<module>json-path</module> <module>json-path</module>
<module>jsoup</module> <module>jsoup</module>
<module>jta</module> <module>jta</module>
<module>junit5</module>
<module>kubernetes</module> <module>kubernetes</module>
<module>ksqldb</module> <module>ksqldb</module>
<!-- <module>lagom</module> --> <!-- Not a maven project --> <!-- <module>lagom</module> --> <!-- Not a maven project -->

View File

@ -46,7 +46,7 @@
<module>spring-boot-groovy</module> <module>spring-boot-groovy</module>
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project --> <!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
<module>spring-boot-jasypt</module> <module>spring-boot-jasypt</module>
<module>spring-boot-keycloak</module> <!-- <module>spring-boot-keycloak</module> --> <!-- Fixing under JAVA-8271 -->
<module>spring-boot-libraries</module> <module>spring-boot-libraries</module>
<module>spring-boot-libraries-2</module> <module>spring-boot-libraries-2</module>
<module>spring-boot-logging-log4j2</module> <module>spring-boot-logging-log4j2</module>
@ -95,19 +95,4 @@
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</dependency>
</dependencies>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
</properties>
</project> </project>

View File

@ -30,17 +30,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>

View File

@ -40,11 +40,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -1,24 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@ -1 +0,0 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip

View File

@ -8,4 +8,4 @@ This module contains articles about Keycloak in Spring Boot projects.
- [Customizing the Login Page for Keycloak](https://www.baeldung.com/keycloak-custom-login-page) - [Customizing the Login Page for Keycloak](https://www.baeldung.com/keycloak-custom-login-page)
- [Keycloak User Self-Registration](https://www.baeldung.com/keycloak-user-registration) - [Keycloak User Self-Registration](https://www.baeldung.com/keycloak-user-registration)
- [Customizing Themes for Keycloak](https://www.baeldung.com/spring-keycloak-custom-themes) - [Customizing Themes for Keycloak](https://www.baeldung.com/spring-keycloak-custom-themes)
- [Securing SOAP Web Services With Keycloak](https://www.baeldung.com/soap-keycloak)

View File

@ -1,225 +0,0 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
echo $MAVEN_PROJECTBASEDIR
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

View File

@ -1,143 +0,0 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@ -64,6 +64,28 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.21.0</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -72,11 +94,31 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.5.0</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<packageName>com.baeldung</packageName>
<sources>
<source>src/main/resources/products.xsd</source>
</sources>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<properties> <properties>
<keycloak-adapter-bom.version>13.0.1</keycloak-adapter-bom.version> <keycloak-adapter-bom.version>15.0.2</keycloak-adapter-bom.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,54 @@
package com.baeldung.keycloaksoap;
import org.keycloak.adapters.KeycloakConfigResolver;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
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.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@KeycloakConfiguration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true")
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
//@formatter:off
http
.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.permitAll();
//@formatter:on
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Bean
public KeycloakConfigResolver keycloakSpringBootConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.keycloaksoap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KeycloakSoapServicesApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(KeycloakSoapServicesApplication.class);
application.setAdditionalProfiles("keycloak");
application.run(args);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.keycloaksoap;
import com.baeldung.DeleteProductRequest;
import com.baeldung.DeleteProductResponse;
import com.baeldung.GetProductDetailsRequest;
import com.baeldung.GetProductDetailsResponse;
import com.baeldung.Product;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import javax.annotation.security.RolesAllowed;
import java.util.Map;
@Endpoint
public class ProductsEndpoint {
private final Map<String, Product> productMap;
public ProductsEndpoint(Map<String, Product> productMap) {
this.productMap = productMap;
}
@RolesAllowed("user")
@PayloadRoot(namespace = "http://www.baeldung.com/springbootsoap/keycloak", localPart = "getProductDetailsRequest")
@ResponsePayload
public GetProductDetailsResponse getProductDetails(@RequestPayload GetProductDetailsRequest request) {
GetProductDetailsResponse response = new GetProductDetailsResponse();
response.setProduct(productMap.get(request.getId()));
return response;
}
@RolesAllowed("admin")
@PayloadRoot(namespace = "http://www.baeldung.com/springbootsoap/keycloak", localPart = "deleteProductRequest")
@ResponsePayload
public DeleteProductResponse deleteProduct(@RequestPayload DeleteProductRequest request) {
DeleteProductResponse response = new DeleteProductResponse();
response.setMessage("Success! Deleted the product with the id - "+request.getId());
return response;
}
}

View File

@ -0,0 +1,75 @@
package com.baeldung.keycloaksoap;
import com.baeldung.Product;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
import java.util.HashMap;
import java.util.Map;
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
@Value("${ws.api.path:/ws/api/v1/*}")
private String webserviceApiPath;
@Value("${ws.port.type.name:ProductsPort}")
private String webservicePortTypeName;
@Value("${ws.target.namespace:http://www.baeldung.com/springbootsoap/keycloak}")
private String webserviceTargetNamespace;
@Value("${ws.location.uri:http://localhost:18080/ws/api/v1/}")
private String locationUri;
@Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean<>(servlet, webserviceApiPath);
}
@Bean(name = "products")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema productsSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName(webservicePortTypeName);
wsdl11Definition.setTargetNamespace(webserviceTargetNamespace);
wsdl11Definition.setLocationUri(locationUri);
wsdl11Definition.setSchema(productsSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema productsSchema() {
return new SimpleXsdSchema(new ClassPathResource("products.xsd"));
}
@Bean
public Map<String, Product> getProducts()
{
Map<String, Product> map = new HashMap<>();
Product foldsack= new Product();
foldsack.setId("1");
foldsack.setName("Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops");
foldsack.setDescription("Your perfect pack for everyday use and walks in the forest. ");
Product shirt= new Product();
shirt.setId("2");
shirt.setName("Mens Casual Premium Slim Fit T-Shirts");
shirt.setDescription("Slim-fitting style, contrast raglan long sleeve, three-button henley placket.");
map.put("1", foldsack);
map.put("2", shirt);
return map;
}
}

View File

@ -0,0 +1,17 @@
server.port=18080
keycloak.enabled=true
keycloak.realm=baeldung-soap-services
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.bearer-only=true
keycloak.credentials.secret=14da6f9e-261f-489a-9bf0-1441e4a9ddc4
keycloak.ssl-required=external
keycloak.resource=baeldung-soap-services
keycloak.use-resource-role-mappings=true
# Custom properties begin here
ws.api.path=/ws/api/v1/*
ws.port.type.name=ProductsPort
ws.target.namespace=http://www.baeldung.com/springbootsoap/keycloak
ws.location.uri=http://localhost:18080/ws/api/v1/

View File

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.baeldung.com/springbootsoap/keycloak"
targetNamespace="http://www.baeldung.com/springbootsoap/keycloak" elementFormDefault="qualified">
<xs:element name="getProductDetailsRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="deleteProductRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="getProductDetailsResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="product" type="tns:product"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="deleteProductResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="message" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<!-- Define the complex object Product -->
<xs:complexType name="product">
<xs:sequence>
<xs:element name="id" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="description" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

View File

@ -0,0 +1,153 @@
package com.baeldung.keycloaksoap;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
/**
* The class contains Live/Integration tests.
* These tests expect that the Keycloak server is up and running on port 8080.
* The tests may fail without a Keycloak server.
*/
@DisplayName("Keycloak SOAP Webservice Unit Tests")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@AutoConfigureMockMvc
class KeycloakSoapIntegrationTest {
private static final Logger logger = LoggerFactory.getLogger(KeycloakSoapIntegrationTest.class);
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private ObjectMapper objectMapper;
@Value("${grant.type}")
private String grantType;
@Value("${client.id}")
private String clientId;
@Value("${client.secret}")
private String clientSecret;
@Value("${url}")
private String keycloakUrl;
/**
* Test a happy flow. Test the <i>janedoe</i> user.
* This user should be configured in Keycloak server with a role <i>user</i>
*/
@Test
@DisplayName("Get Products With Access Token")
void givenAccessToken_whenGetProducts_thenReturnProduct() {
HttpHeaders headers = new HttpHeaders();
headers.set("content-type", "text/xml");
headers.set("Authorization", "Bearer " + generateToken("janedoe", "password"));
HttpEntity<String> request = new HttpEntity<>(Utility.getGetProductDetailsRequest(), headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:" + port + "/ws/api/v1/", request, String.class);
assertThat(responseEntity).isNotNull();
assertThat(responseEntity.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
assertThat(responseEntity.getBody()).isNotBlank();
assertThat(responseEntity.getBody()).containsIgnoringCase(":id>1</");
}
/**
* A negative test. Deliberately pass wrong credentials to Keycloak. Test the invalid <i>janeadoe</i> user.
* Keycloak returns Unauthorized. Assert 401 status and empty body.
*/
@Test
@DisplayName("Get Products With Wrong Access Token")
void givenWrongAccessToken_whenGetProducts_thenReturnError() {
HttpHeaders headers = new HttpHeaders();
headers.set("content-type", "text/xml");
headers.set("Authorization", "Bearer " + generateToken("janeadoe", "password"));
HttpEntity<String> request = new HttpEntity<>(Utility.getGetProductDetailsRequest(), headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:" + port + "/ws/api/v1/", request, String.class);
assertThat(responseEntity).isNotNull();
assertThat(responseEntity.getStatusCodeValue()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(responseEntity.getBody()).isBlank();
}
/**
* Happy flow to test <i>deleteProduct</i> operation. Test the <i>jhondoe</i> user.
* This user should be configured in Keycloak server with a role <i>user</i>
*/
@Test
@DisplayName("Delete Product With Access Token")
void givenAccessToken_whenDeleteProduct_thenReturnSuccess() {
HttpHeaders headers = new HttpHeaders();
headers.set("content-type", "text/xml");
headers.set("Authorization", "Bearer " + generateToken("jhondoe", "password"));
HttpEntity<String> request = new HttpEntity<>(Utility.getDeleteProductsRequest(), headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:" + port + "/ws/api/v1/", request, String.class);
assertThat(responseEntity).isNotNull();
assertThat(responseEntity.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
assertThat(responseEntity.getBody()).isNotBlank();
assertThat(responseEntity.getBody()).containsIgnoringCase("Deleted the product with the id");
}
/**
* Negative flow to test <i></i>. Test the <i>janedoe</i> user.
* Obtain the access token of <i>janedoe</i> and access the admin operation <i>deleteProduct</i>
* Assume <i>janedoe</i> has restricted access to <i>deleteProduct</i> operation
*/
@Test
@DisplayName("Delete Products With Unauthorized Access Token")
void givenUnauthorizedAccessToken_whenDeleteProduct_thenReturnUnauthorized() {
HttpHeaders headers = new HttpHeaders();
headers.set("content-type", "text/xml");
headers.set("Authorization", "Bearer " + generateToken("janedoe", "password"));
HttpEntity<String> request = new HttpEntity<>(Utility.getDeleteProductsRequest(), headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:" + port + "/ws/api/v1/", request, String.class);
assertThat(responseEntity).isNotNull();
assertThat(responseEntity.getStatusCodeValue()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(responseEntity.getBody()).isNotBlank();
assertThat(responseEntity.getBody()).containsIgnoringCase("Access is denied");
}
private String generateToken(String username, String password) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", grantType);
map.add("client_id", clientId);
map.add("client_secret", clientSecret);
map.add("username", username);
map.add("password", password);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.exchange(keycloakUrl, HttpMethod.POST, entity, String.class);
return Objects.requireNonNull(response.getBody()).contains("access_token") ? objectMapper.readTree(response.getBody()).get("access_token").asText() : "";
} catch (Exception ex) {
logger.error("There is an internal server error. Returning an empty access token", ex);
return "";
}
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.keycloaksoap;
public class Utility {
public static String getGetProductDetailsRequest() {
return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:key=\"http://www.baeldung.com/springbootsoap/keycloak\">\n" + " <soapenv:Header/>\n" + " <soapenv:Body>\n" + " <key:getProductDetailsRequest>\n"
+ " <key:id>1</key:id>\n" + " </key:getProductDetailsRequest>\n" + " </soapenv:Body>\n" + "</soapenv:Envelope>";
}
public static String getDeleteProductsRequest() {
return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:key=\"http://www.baeldung.com/springbootsoap/keycloak\">\n" + " <soapenv:Header/>\n" + " <soapenv:Body>\n" + " <key:deleteProductRequest>\n"
+ " <key:id>1</key:id>\n" + " </key:deleteProductRequest>\n" + " </soapenv:Body>\n" + "</soapenv:Envelope>";
}
}

View File

@ -0,0 +1,4 @@
grant.type=password
client.id=baeldung-soap-services
client.secret=d2ba7af8-f7d2-4c97-b4a5-3c88b59920ae
url=http://localhost:8080/auth/realms/baeldung-soap-services/protocol/openid-connect/token

View File

@ -49,17 +49,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Embedded Redis Server --> <!-- Embedded Redis Server -->
<dependency> <dependency>
<groupId>it.ozimov</groupId> <groupId>it.ozimov</groupId>

View File

@ -54,17 +54,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>io.dropwizard.metrics</groupId> <groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId> <artifactId>metrics-core</artifactId>

View File

@ -26,17 +26,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -30,17 +30,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -23,17 +23,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -23,17 +23,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -45,7 +45,6 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration> <configuration>
<forkCount>0</forkCount> <forkCount>0</forkCount>
</configuration> </configuration>

View File

@ -55,18 +55,6 @@
<version>${spring.version}</version> <version>${spring.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>

View File

@ -55,18 +55,6 @@
<version>${spring.version}</version> <version>${spring.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.awaitility</groupId> <groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId> <artifactId>awaitility</artifactId>

View File

@ -1,18 +1,20 @@
package com.baeldung.spring; package com.baeldung.spring;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc @EnableWebMvc
@Configuration @Configuration
public class MvcConfig extends WebMvcConfigurerAdapter { @ComponentScan(basePackages = { "com.baeldung.spring" })
public class MvcConfig implements WebMvcConfigurer {
public MvcConfig() { public MvcConfig() {
super(); super();
@ -22,8 +24,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
@Override @Override
public void addViewControllers(final ViewControllerRegistry registry) { public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/anonymous.html"); registry.addViewController("/anonymous.html");
registry.addViewController("/login.html"); registry.addViewController("/login.html");

View File

@ -0,0 +1,31 @@
package com.baeldung.spring;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/rest")
public class RestController {
private static final Logger LOGGER = LoggerFactory.getLogger(RestController.class);
@GetMapping
public ResponseEntity<Void> get(HttpServletRequest request) {
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
LOGGER.info("{}={}", token.getHeaderName(), token.getToken());
return ResponseEntity.ok().build();
}
@PostMapping
public ResponseEntity<Void> post(HttpServletRequest request) {
// Same impl as GET for testing purpose
return this.get(request);
}
}

View File

@ -7,6 +7,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@ -21,11 +22,11 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final AuthenticationManagerBuilder auth) throws Exception { protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off // @formatter:off
auth.inMemoryAuthentication() auth.inMemoryAuthentication()
.withUser("user1").password("user1Pass").roles("USER") .withUser("user1").password("{noop}user1Pass").roles("USER")
.and() .and()
.withUser("user2").password("user2Pass").roles("USER") .withUser("user2").password("{noop}user2Pass").roles("USER")
.and() .and()
.withUser("admin").password("admin0Pass").roles("ADMIN"); .withUser("admin").password("{noop}admin0Pass").roles("ADMIN");
// @formatter:on // @formatter:on
} }
@ -33,11 +34,11 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final HttpSecurity http) throws Exception { protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off // @formatter:off
http http
.csrf().disable() .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.authorizeRequests() .authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/anonymous*").anonymous() .antMatchers("/anonymous*").anonymous()
.antMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico").permitAll() .antMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico", "/rest").permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()
.formLogin() .formLogin()

Some files were not shown because too many files have changed in this diff Show More