diff --git a/core-java-8/src/test/java/com/baeldung/CharToStringTest.java b/core-java-8/src/test/java/com/baeldung/CharToStringTest.java new file mode 100644 index 0000000000..d91016d104 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/CharToStringTest.java @@ -0,0 +1,53 @@ +package com.baeldung; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CharToStringTest { + + @Test + public void givenChar_whenCallingStringValueOf_shouldConvertToString(){ + final char givenChar = 'x'; + + final String result = String.valueOf(givenChar); + + assertThat(result).isEqualTo("x"); + } + + @Test + public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString(){ + final char givenChar = 'x'; + + final String result = Character.toString(givenChar); + + assertThat(result).isEqualTo("x"); + } + + @Test + public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3(){ + final char givenChar = 'x'; + + final String result = new Character(givenChar).toString(); + + assertThat(result).isEqualTo("x"); + } + + @Test + public void givenChar_whenConcatenated_shouldConvertToString4(){ + final char givenChar = 'x'; + + final String result = givenChar + ""; + + assertThat(result).isEqualTo("x"); + } + + @Test + public void givenChar_whenFormated_shouldConvertToString5(){ + final char givenChar = 'x'; + + final String result = String.format("%c", givenChar); + + assertThat(result).isEqualTo("x"); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java new file mode 100644 index 0000000000..8143da5794 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +public class RandomListElementTest { + + @Test + public void givenList_whenRandomNumberChosen_shouldReturnARandomElement() { + List givenList = Arrays.asList(1, 2, 3); + Random rand = new Random(); + givenList.get(rand.nextInt(givenList.size())); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java b/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java new file mode 100644 index 0000000000..6c1493d89b --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java @@ -0,0 +1,62 @@ +package com.baeldung; + +import com.google.common.primitives.Ints; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StringToIntOrIntegerTest { + + @Test + public void givenString_whenParsingInt_shouldConvertToInt() { + String givenString = "42"; + + int result = Integer.parseInt(givenString); + + assertThat(result).isEqualTo(42); + } + + + @Test + public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() { + String givenString = "42"; + + Integer result = Integer.valueOf(givenString); + + assertThat(result).isEqualTo(new Integer(42)); + } + + @Test + public void givenString_whenCallingIntegerConstructor_shouldConvertToInt() { + String givenString = "42"; + + Integer result = new Integer(givenString); + + assertThat(result).isEqualTo(new Integer(42)); + } + + @Test + public void givenString_whenCallingIntegerDecode_shouldConvertToInt() { + String givenString = "42"; + + int result = Integer.decode(givenString); + + assertThat(result).isEqualTo(42); + } + + @Test + public void givenString_whenTryParse_shouldConvertToInt() { + String givenString = "42"; + + Integer result = Ints.tryParse(givenString); + + assertThat(result).isEqualTo(42); + } + + @Test(expected = NumberFormatException.class) + public void givenInvalidInput_whenParsingInt_shouldThrow() { + String givenString = "nan"; + Integer.parseInt(givenString); + } + +} diff --git a/core-java/src/main/resources/targetFile.tmp b/core-java/src/main/resources/targetFile.tmp deleted file mode 100644 index 20f137b416..0000000000 --- a/core-java/src/main/resources/targetFile.tmp +++ /dev/null @@ -1,2 +0,0 @@ -line 1 -a second line \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java index 55a0904499..1a6ac5f8ce 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java @@ -19,6 +19,7 @@ import java.io.Reader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.file.StandardCopyOption; import java.util.Scanner; import org.apache.commons.io.FileUtils; @@ -191,6 +192,16 @@ public class JavaInputStreamToXUnitTest { IOUtils.closeQuietly(outStream); } + @Test + public final void givenUsingPlainJava8_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException { + final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); + final File targetFile = new File("src/main/resources/targetFile.tmp"); + + java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + IOUtils.closeQuietly(initialStream); + } + @Test public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException { final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); diff --git a/hystrix/.gitignore b/hystrix/.gitignore new file mode 100644 index 0000000000..b092c8122f --- /dev/null +++ b/hystrix/.gitignore @@ -0,0 +1,12 @@ +*.class + +#folders# +/target +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear +*.iml \ No newline at end of file diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 7867bbb955..42828e1c97 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -62,11 +62,11 @@ hystrix-metrics-event-stream ${hystrix-metrics-event-stream.version} - + com.netflix.rxjava rxjava-core diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java deleted file mode 100644 index a5303e6c0d..0000000000 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.hystrix; - -import com.netflix.hystrix.HystrixCommand; -import com.netflix.hystrix.HystrixCommandGroupKey; -import com.netflix.hystrix.HystrixCommandProperties; -import com.netflix.hystrix.HystrixThreadPoolProperties; -import com.netflix.hystrix.exception.HystrixRuntimeException; -import org.junit.*; -import org.junit.rules.ExpectedException; -import org.junit.runners.MethodSorters; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; - -@FixMethodOrder(MethodSorters.JVM) -public class HystrixTimeShortCircuitTest { - - private HystrixCommand.Setter config; - private HystrixCommandProperties.Setter commandProperties; - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Before - public void setup() { - commandProperties = HystrixCommandProperties.Setter(); - config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); - } - - @Test - public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess() - throws InterruptedException { - - commandProperties.withExecutionTimeoutInMilliseconds(1000); - - commandProperties.withCircuitBreakerSleepWindowInMilliseconds(4000); - commandProperties.withExecutionIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); - commandProperties.withCircuitBreakerEnabled(true); - commandProperties.withCircuitBreakerRequestVolumeThreshold(1); - - config.andCommandPropertiesDefaults(commandProperties); - - config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() - .withMaxQueueSize(1) - .withCoreSize(1) - .withQueueSizeRejectionThreshold(1)); - - assertThat(this.invokeRemoteService(10000), equalTo(null)); - assertThat(this.invokeRemoteService(10000), equalTo(null)); - Thread.sleep(5000); - - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); - } - - String invokeRemoteService(long timeout) throws InterruptedException { - String response = null; - try { - response = new RemoteServiceTestCommand(config, - new RemoteServiceTestSimulator(timeout)).execute(); - } catch (HystrixRuntimeException ex) { - System.out.println("ex = " + ex); - } - return response; - } - -} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java index 878d7808a0..8dd620ddd9 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -5,57 +5,45 @@ import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.exception.HystrixRuntimeException; -import org.junit.*; -import org.junit.rules.ExpectedException; -import org.junit.runners.MethodSorters; +import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -@FixMethodOrder(MethodSorters.JVM) public class HystrixTimeoutTest { - private HystrixCommand.Setter config; - private HystrixCommandProperties.Setter commandProperties; - - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Before - public void setup() { - commandProperties = HystrixCommandProperties.Setter(); - config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); - } - @Test - public void givenInputBobAndDefaultSettings_whenExecuted_thenReturnHelloBob(){ + public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob(){ assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!")); } @Test - public void givenSvcTimeoutOf100AndDefaultSettings_whenExecuted_thenReturnSuccess() + public void givenSvcTimeoutOf100AndDefaultSettings_whenRemoteSvcExecuted_thenReturnSuccess() throws InterruptedException { - HystrixCommand.Setter config = HystrixCommand .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2")); assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), equalTo("Success")); } - @Test - public void givenSvcTimeoutOf10000AndDefaultSettings__whenExecuted_thenExpectHRE() throws InterruptedException { - exception.expect(HystrixRuntimeException.class); + @Test(expected = HystrixRuntimeException.class) + public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException { + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3")); new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute(); } @Test - public void givenSvcTimeoutOf5000AndExecTimeoutOf10000__whenExecuted_thenReturnSuccess() + public void givenSvcTimeoutOf5000AndExecTimeoutOf10000_whenRemoteSvcExecuted_thenReturnSuccess() throws InterruptedException { + + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4")); + HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); @@ -63,10 +51,13 @@ public class HystrixTimeoutTest { equalTo("Success")); } - @Test + @Test(expected = HystrixRuntimeException.class) public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE() throws InterruptedException { - exception.expect(HystrixRuntimeException.class); + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5")); + HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); commandProperties.withExecutionTimeoutInMilliseconds(5_000); config.andCommandPropertiesDefaults(commandProperties); new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(15_000)).execute(); @@ -75,6 +66,11 @@ public class HystrixTimeoutTest { @Test public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess() throws InterruptedException { + + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool")); + HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() @@ -85,4 +81,52 @@ public class HystrixTimeoutTest { assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), equalTo("Success")); } + + @Test + public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess() + throws InterruptedException { + + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker")); + HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); + commandProperties.withExecutionTimeoutInMilliseconds(1000); + + commandProperties.withCircuitBreakerSleepWindowInMilliseconds(4000); + commandProperties.withExecutionIsolationStrategy( + HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); + commandProperties.withCircuitBreakerEnabled(true); + commandProperties.withCircuitBreakerRequestVolumeThreshold(1); + + config.andCommandPropertiesDefaults(commandProperties); + + config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() + .withMaxQueueSize(1) + .withCoreSize(1) + .withQueueSizeRejectionThreshold(1)); + + assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); + assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); + assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); + Thread.sleep(5000); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + } + + public String invokeRemoteService(HystrixCommand.Setter config, int timeout) + throws InterruptedException { + String response = null; + try { + response = new RemoteServiceTestCommand(config, + new RemoteServiceTestSimulator(timeout)).execute(); + } catch (HystrixRuntimeException ex) { + System.out.println("ex = " + ex); + } + return response; + } } diff --git a/mapstruct/bin/pom.xml b/mapstruct/bin/pom.xml new file mode 100644 index 0000000000..8a28ae9511 --- /dev/null +++ b/mapstruct/bin/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + mapstruct + mapstruct + com.baeldung + 1.0 + jar + + + 1.0.0.Final + + + + org.mapstruct + mapstruct-jdk8 + ${org.mapstruct.version} + + + junit + junit + 4.12 + test + + + + mapstruct + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + + diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index 8a28ae9511..4159ef35c9 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -24,6 +24,17 @@ 4.12 test + + org.springframework + spring-context + 4.3.2.RELEASE + + + org.springframework + spring-test + 4.3.2.RELEASE + test + mapstruct diff --git a/mapstruct/src/main/java/org/baeldung/dto/DivisionDTO.java b/mapstruct/src/main/java/org/baeldung/dto/DivisionDTO.java new file mode 100644 index 0000000000..01a5792176 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/dto/DivisionDTO.java @@ -0,0 +1,33 @@ +package org.baeldung.dto; + +public class DivisionDTO { + + public DivisionDTO() { + } + + public DivisionDTO(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + 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; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java b/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java index 67b9ffc024..24d6950cab 100644 --- a/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java +++ b/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java @@ -2,41 +2,41 @@ package org.baeldung.dto; public class EmployeeDTO { - private int employeeId; - private String employeeName; - private int divisionId; - private String divisionName; + private int employeeId; + private String employeeName; + private DivisionDTO division; + private String employeeStartDt; - public int getEmployeeId() { - return employeeId; - } + public int getEmployeeId() { + return employeeId; + } - public void setEmployeeId(int employeeId) { - this.employeeId = employeeId; - } + public void setEmployeeId(int employeeId) { + this.employeeId = employeeId; + } - public String getEmployeeName() { - return employeeName; - } + public String getEmployeeName() { + return employeeName; + } - public void setEmployeeName(String employeeName) { - this.employeeName = employeeName; - } + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } - public int getDivisionId() { - return divisionId; - } + public DivisionDTO getDivision() { + return division; + } - public void setDivisionId(int divisionId) { - this.divisionId = divisionId; - } + public void setDivision(DivisionDTO division) { + this.division = division; + } - public String getDivisionName() { - return divisionName; - } + public String getEmployeeStartDt() { + return employeeStartDt; + } - public void setDivisionName(String divisionName) { - this.divisionName = divisionName; - } + public void setEmployeeStartDt(String employeeStartDt) { + this.employeeStartDt = employeeStartDt; + } } diff --git a/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java b/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java index fc0c75dea3..4c169461c8 100644 --- a/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java +++ b/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java @@ -2,23 +2,23 @@ package org.baeldung.dto; public class SimpleSource { - private String name; - private String description; - - public String getName() { - return name; - } + private String name; + private String description; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getDescription() { - return description; - } + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } - public void setDescription(String description) { - this.description = description; - } - } diff --git a/mapstruct/src/main/java/org/baeldung/entity/Division.java b/mapstruct/src/main/java/org/baeldung/entity/Division.java index 04f1ab2c23..83b0916eb4 100644 --- a/mapstruct/src/main/java/org/baeldung/entity/Division.java +++ b/mapstruct/src/main/java/org/baeldung/entity/Division.java @@ -2,32 +2,32 @@ package org.baeldung.entity; public class Division { - public Division() { - } + public Division() { + } - public Division(int id, String name) { - super(); - this.id = id; - this.name = name; - } + public Division(int id, String name) { + super(); + this.id = id; + this.name = name; + } - private int id; - private String name; + private int id; + private String name; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/mapstruct/src/main/java/org/baeldung/entity/Employee.java b/mapstruct/src/main/java/org/baeldung/entity/Employee.java index 55599a17f9..8c441813b6 100644 --- a/mapstruct/src/main/java/org/baeldung/entity/Employee.java +++ b/mapstruct/src/main/java/org/baeldung/entity/Employee.java @@ -1,33 +1,44 @@ package org.baeldung.entity; +import java.util.Date; + public class Employee { - private int id; - private String name; - private Division division; + private int id; + private String name; + private Division division; + private Date startDt; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Division getDivision() { - return division; - } + public Division getDivision() { + return division; + } - public void setDivision(Division division) { - this.division = division; - } + public void setDivision(Division division) { + this.division = division; + } + + public Date getStartDt() { + return startDt; + } + + public void setStartDt(Date startDt) { + this.startDt = startDt; + } } diff --git a/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java b/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java index 901257c11b..9fdbd7f054 100644 --- a/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java +++ b/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java @@ -2,23 +2,23 @@ package org.baeldung.entity; public class SimpleDestination { - private String name; - private String description; - - public String getName() { - return name; - } + private String name; + private String description; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getDescription() { - return description; - } + public void setName(String name) { + this.name = name; + } - public void setDescription(String description) { - this.description = description; - } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } } diff --git a/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java index 28faffec45..013c332e6e 100644 --- a/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java +++ b/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java @@ -1,6 +1,10 @@ package org.baeldung.mapper; +import java.util.List; + +import org.baeldung.dto.DivisionDTO; import org.baeldung.dto.EmployeeDTO; +import org.baeldung.entity.Division; import org.baeldung.entity.Employee; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @@ -9,19 +13,18 @@ import org.mapstruct.Mappings; @Mapper public interface EmployeeMapper { - @Mappings({ - @Mapping(target="divisionId",source="entity.division.id"), - @Mapping(target="divisionName",source="entity.division.name"), - @Mapping(target="employeeId",source="entity.id"), - @Mapping(target="employeeName",source="entity.name") - }) - EmployeeDTO employeeToEmployeeDTO(Employee entity); - - @Mappings({ - @Mapping(target="id",source="dto.employeeId"), - @Mapping(target="name",source="dto.employeeName"), - @Mapping(target="division",expression="java(new org.baeldung.entity.Division(dto.getDivisionId(),dto.getDivisionName()))") - }) - Employee employeeDTOtoEmployee(EmployeeDTO dto); - + @Mappings({ @Mapping(target = "employeeId", source = "entity.id"), @Mapping(target = "employeeName", source = "entity.name"), @Mapping(target = "employeeStartDt", source = "entity.startDt", dateFormat = "dd-MM-yyyy HH:mm:ss") }) + EmployeeDTO employeeToEmployeeDTO(Employee entity); + + @Mappings({ @Mapping(target = "id", source = "dto.employeeId"), @Mapping(target = "name", source = "dto.employeeName"), @Mapping(target = "startDt", source = "dto.employeeStartDt", dateFormat = "dd-MM-yyyy HH:mm:ss") }) + Employee employeeDTOtoEmployee(EmployeeDTO dto); + + DivisionDTO divisionToDivisionDTO(Division entity); + + Division divisionDTOtoDivision(DivisionDTO dto); + + List convertEmployeeDTOListToEmployeeList(List list); + + List convertEmployeeListToEmployeeDTOList(List list); + } diff --git a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java index f3210288d2..3e872e68a3 100644 --- a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java +++ b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java @@ -4,10 +4,11 @@ import org.baeldung.dto.SimpleSource; import org.baeldung.entity.SimpleDestination; import org.mapstruct.Mapper; -@Mapper +@Mapper(componentModel = "spring") public interface SimpleSourceDestinationMapper { - SimpleDestination sourceToDestination(SimpleSource source); + SimpleDestination sourceToDestination(SimpleSource source); + SimpleSource destinationToSource(SimpleDestination destination); - + } diff --git a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java deleted file mode 100644 index 2077eabf51..0000000000 --- a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.mapper; - -import org.baeldung.dto.SimpleSource; -import org.baeldung.entity.SimpleDestination; -import org.mapstruct.Mapper; - -@Mapper(componentModel="spring") -public interface SimpleSourceDestinationSpringMapper { - - SimpleDestination sourceToDestination(SimpleSource source); - SimpleSource destinationToSource(SimpleDestination destination); - -} diff --git a/mapstruct/src/main/resources/applicationContext.xml b/mapstruct/src/main/resources/applicationContext.xml new file mode 100644 index 0000000000..1e6649139c --- /dev/null +++ b/mapstruct/src/main/resources/applicationContext.xml @@ -0,0 +1,15 @@ + + + + + + \ No newline at end of file diff --git a/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java b/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java index 0433013f2e..c5998f89ef 100644 --- a/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java +++ b/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java @@ -1,7 +1,14 @@ package org.baeldung.mapper; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.baeldung.dto.DivisionDTO; import org.baeldung.dto.EmployeeDTO; import org.baeldung.entity.Division; import org.baeldung.entity.Employee; @@ -9,40 +16,108 @@ import org.junit.Test; import org.mapstruct.factory.Mappers; public class EmployeeMapperTest { - - @Test - public void givenEmployeeDTOtoEmployee_whenMaps_thenCorrect(){ - EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class); - - EmployeeDTO dto = new EmployeeDTO(); - dto.setDivisionId(1); - dto.setDivisionName("IT Division"); - dto.setEmployeeId(1); - dto.setEmployeeName("John"); - - Employee entity = mapper.employeeDTOtoEmployee(dto); - - assertEquals(dto.getDivisionId(), entity.getDivision().getId()); - assertEquals(dto.getDivisionName(), entity.getDivision().getName()); - assertEquals(dto.getEmployeeId(),entity.getId()); - assertEquals(dto.getEmployeeName(),entity.getName()); - } - - @Test - public void givenEmployeetoEmployeeDTO_whenMaps_thenCorrect(){ - EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class); - - Employee entity = new Employee(); - entity.setDivision(new Division(1,"IT Division")); - entity.setId(1); - entity.setName("John"); - - EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); - - assertEquals(dto.getDivisionId(), entity.getDivision().getId()); - assertEquals(dto.getDivisionName(), entity.getDivision().getName()); - assertEquals(dto.getEmployeeId(),entity.getId()); - assertEquals(dto.getEmployeeName(),entity.getName()); - } - + + EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class); + + private static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss"; + + @Test + public void givenEmployeeDTOwithDiffNametoEmployee_whenMaps_thenCorrect() { + EmployeeDTO dto = new EmployeeDTO(); + dto.setEmployeeId(1); + dto.setEmployeeName("John"); + + Employee entity = mapper.employeeDTOtoEmployee(dto); + + assertEquals(dto.getEmployeeId(), entity.getId()); + assertEquals(dto.getEmployeeName(), entity.getName()); + } + + @Test + public void givenEmployeewithDiffNametoEmployeeDTO_whenMaps_thenCorrect() { + Employee entity = new Employee(); + entity.setId(1); + entity.setName("John"); + + EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); + + assertEquals(dto.getEmployeeId(), entity.getId()); + assertEquals(dto.getEmployeeName(), entity.getName()); + } + + @Test + public void givenEmployeeDTOwithNestedMappingToEmployee_whenMaps_thenCorrect() { + EmployeeDTO dto = new EmployeeDTO(); + dto.setDivision(new DivisionDTO(1, "Division1")); + + Employee entity = mapper.employeeDTOtoEmployee(dto); + + assertEquals(dto.getDivision().getId(), entity.getDivision().getId()); + assertEquals(dto.getDivision().getName(), entity.getDivision().getName()); + } + + @Test + public void givenEmployeeWithNestedMappingToEmployeeDTO_whenMaps_thenCorrect() { + Employee entity = new Employee(); + entity.setDivision(new Division(1, "Division1")); + + EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); + + assertEquals(dto.getDivision().getId(), entity.getDivision().getId()); + assertEquals(dto.getDivision().getName(), entity.getDivision().getName()); + } + + @Test + public void givenEmployeeListToEmployeeDTOList_whenMaps_thenCorrect() { + List employeeList = new ArrayList<>(); + Employee emp = new Employee(); + emp.setId(1); + emp.setName("EmpName"); + emp.setDivision(new Division(1, "Division1")); + employeeList.add(emp); + + List employeeDtoList = mapper.convertEmployeeListToEmployeeDTOList(employeeList); + EmployeeDTO employeeDTO = employeeDtoList.get(0); + assertEquals(employeeDTO.getEmployeeId(), emp.getId()); + assertEquals(employeeDTO.getEmployeeName(), emp.getName()); + assertEquals(employeeDTO.getDivision().getId(), emp.getDivision().getId()); + assertEquals(employeeDTO.getDivision().getName(), emp.getDivision().getName()); + } + + @Test + public void givenEmployeeDTOListToEmployeeList_whenMaps_thenCorrect() { + List employeeDTOList = new ArrayList<>(); + EmployeeDTO empDTO = new EmployeeDTO(); + empDTO.setEmployeeId(1); + empDTO.setEmployeeName("EmpName"); + empDTO.setDivision(new DivisionDTO(1, "Division1")); + employeeDTOList.add(empDTO); + + List employeeList = mapper.convertEmployeeDTOListToEmployeeList(employeeDTOList); + Employee employee = employeeList.get(0); + assertEquals(employee.getId(), empDTO.getEmployeeId()); + assertEquals(employee.getName(), empDTO.getEmployeeName()); + assertEquals(employee.getDivision().getId(), empDTO.getDivision().getId()); + assertEquals(employee.getDivision().getName(), empDTO.getDivision().getName()); + } + + @Test + public void givenEmployeeWithStartDateMappingToEmployeeDTO_whenMaps_thenCorrect() throws ParseException { + Employee entity = new Employee(); + entity.setStartDt(new Date()); + + EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); + SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); + assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString()); + } + + @Test + public void givenEmployeeDTOWithStartDateMappingToEmployee_whenMaps_thenCorrect() throws ParseException { + EmployeeDTO dto = new EmployeeDTO(); + dto.setEmployeeStartDt("01-04-2016 01:00:00"); + + Employee entity = mapper.employeeDTOtoEmployee(dto); + SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); + assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString()); + } } diff --git a/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java b/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java index a7e3b05dc6..226603b16a 100644 --- a/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java +++ b/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java @@ -1,44 +1,44 @@ package org.baeldung.mapper; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.baeldung.dto.SimpleSource; import org.baeldung.entity.SimpleDestination; import org.junit.Test; -import org.mapstruct.factory.Mappers; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext.xml") public class SimpleSourceDestinationMapperTest { - @Test - public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() { - SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers - .getMapper(SimpleSourceDestinationMapper.class); - - SimpleSource simpleSource = new SimpleSource(); - simpleSource.setName("SourceName"); - simpleSource.setDescription("SourceDescription"); - - SimpleDestination destination = - simpleSourceDestinationMapper.sourceToDestination(simpleSource); - - assertEquals(simpleSource.getName(), destination.getName()); - assertEquals(simpleSource.getDescription(), destination.getDescription()); - } - - @Test - public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() { - SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers - .getMapper(SimpleSourceDestinationMapper.class); - - SimpleDestination destination = new SimpleDestination(); - destination.setName("DestinationName"); - destination.setDescription("DestinationDescription"); - - SimpleSource source = - simpleSourceDestinationMapper.destinationToSource(destination); - - assertEquals(destination.getName(), source.getName()); - assertEquals(destination.getDescription(), source.getDescription()); - } + @Autowired + SimpleSourceDestinationMapper simpleSourceDestinationMapper; + + @Test + public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() { + SimpleSource simpleSource = new SimpleSource(); + simpleSource.setName("SourceName"); + simpleSource.setDescription("SourceDescription"); + + SimpleDestination destination = simpleSourceDestinationMapper.sourceToDestination(simpleSource); + + assertEquals(simpleSource.getName(), destination.getName()); + assertEquals(simpleSource.getDescription(), destination.getDescription()); + } + + @Test + public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() { + SimpleDestination destination = new SimpleDestination(); + destination.setName("DestinationName"); + destination.setDescription("DestinationDescription"); + + SimpleSource source = simpleSourceDestinationMapper.destinationToSource(destination); + + assertEquals(destination.getName(), source.getName()); + assertEquals(destination.getDescription(), source.getDescription()); + } } diff --git a/spring-all/src/main/java/org/baeldung/startup/EventListenerExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/EventListenerExampleBean.java new file mode 100644 index 0000000000..e9cd1a159d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/EventListenerExampleBean.java @@ -0,0 +1,19 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +public class EventListenerExampleBean { + private static final Logger LOG = Logger.getLogger(EventListenerExampleBean.class); + + public static int counter; + + @EventListener + public void onApplicationEvent(ContextRefreshedEvent event) { + LOG.info("Increment counter"); + counter++; + } +} diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 66197feacd..a3181eb895 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -124,9 +124,6 @@ - - true - diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java index 226ba44dd5..1da2bd2989 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java @@ -4,6 +4,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.HashMap; +import java.util.Map; + @RestController public class CommitInfoController { @@ -17,7 +20,11 @@ public class CommitInfoController { private String commitId; @RequestMapping("/commitId") - public GitInfoDto getCommitId() { - return new GitInfoDto(commitMessage, branch, commitId); + public Map getCommitId() { + Map result = new HashMap<>(); + result.put("Commit message",commitMessage); + result.put("Commit branch", branch); + result.put("Commit id", commitId); + return result; } } diff --git a/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java b/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java deleted file mode 100644 index b8b58f55e8..0000000000 --- a/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.git; - -public class GitInfoDto { - private String commitMessage; - private String branch; - private String commitId; - - public GitInfoDto(String commitMessage, String branch, String commitId) { - this.commitMessage = commitMessage; - this.branch = branch; - this.commitId = commitId; - } - - public String getCommitMessage() { - return commitMessage; - } - - public String getBranch() { - return branch; - } - - public String getCommitId() { - return commitId; - } -} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index 80cb915e52..ec8dc32200 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -1,43 +1,27 @@ package com.baeldung.hibernate.fetching.model; +import javax.persistence.*; import java.io.Serializable; import java.sql.Date; +@Entity +@Table (name = "USER_ORDER") public class OrderDetail implements Serializable{ private static final long serialVersionUID = 1L; - private Long orderId; - private Date orderDate; - private String orderDesc; - private User user; - public OrderDetail(){ + @Id + @GeneratedValue + @Column(name="ORDER_ID") + private Long orderId; + + public OrderDetail(){ } public OrderDetail(Date orderDate, String orderDesc) { - super(); - this.orderDate = orderDate; - this.orderDesc = orderDesc; + super(); } - public Date getOrderDate() { - return orderDate; - } - public void setOrderDate(Date orderDate) { - this.orderDate = orderDate; - } - public String getOrderDesc() { - return orderDesc; - } - public void setOrderDesc(String orderDesc) { - this.orderDesc = orderDesc; - } - public User getUser() { - return user; - } - public void setUser(User user) { - this.user = user; - } @Override public int hashCode() { final int prime = 31; @@ -62,6 +46,7 @@ public class OrderDetail implements Serializable{ return true; } + public Long getOrderId() { return orderId; } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java deleted file mode 100644 index fa995319fd..0000000000 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.baeldung.hibernate.fetching.model; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - private Long userId; - private String userName; - private String firstName; - private String lastName; - private Set orderDetail = new HashSet(); - - public User() { - } - - public User(final Long userId, final String userName, final String firstName, final String lastName) { - super(); - this.userId = userId; - this.userName = userName; - this.firstName = firstName; - this.lastName = lastName; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final User other = (User) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(final Long userId) { - this.userId = userId; - } - - public String getUserName() { - return userName; - } - - public void setUserName(final String userName) { - this.userName = userName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(final String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(final String lastName) { - this.lastName = lastName; - } - - public Set getOrderDetail() { - return orderDetail; - } - - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } - - -} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java new file mode 100644 index 0000000000..22b4fdc76c --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table (name = "USER") +public class UserEager implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name="USER_ID") + private Long userId; + + @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") + private Set orderDetail = new HashSet(); + + public UserEager() { + } + + public UserEager(final Long userId) { + super(); + this.userId = userId; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserEager other = (UserEager) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java new file mode 100644 index 0000000000..5038fb90ef --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table (name = "USER") +public class UserLazy implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name="USER_ID") + private Long userId; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + private Set orderDetail = new HashSet(); + + public UserLazy() { + } + + public UserLazy(final Long userId) { + super(); + this.userId = userId; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserLazy other = (UserLazy) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index 27af8c9b8b..bbd7729232 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -11,7 +11,7 @@ public class HibernateUtil { //two config files are there //one with lazy loading enabled //another lazy = false - SessionFactory sf = null; + SessionFactory sf; if ("lazy".equals(fetchMethod)) { sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); } else { @@ -19,8 +19,7 @@ public class HibernateUtil { } // fetching.cfg.xml is used for this example - final Session session = sf.openSession(); - return session; + return sf.openSession(); } public static Session getHibernateSession() { diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java index c55f65cdbf..1a5142c5c2 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -1,111 +1,68 @@ package com.baeldung.hibernate.fetching.view; -import java.sql.Date; -import java.util.List; -import java.util.Set; - -import org.hibernate.Hibernate; +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.model.UserEager; +import com.baeldung.hibernate.fetching.model.UserLazy; +import com.baeldung.hibernate.fetching.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; - -import com.baeldung.hibernate.fetching.util.HibernateUtil; - -import com.baeldung.hibernate.fetching.model.OrderDetail; - -import com.baeldung.hibernate.fetching.model.User; - +import java.util.List; +import java.util.Set; public class FetchingAppView { - public FetchingAppView(){ - - } - - //lazily loaded - public Set lazyLoaded(){ - final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); - List users = sessionLazy.createQuery("From User").list(); - User userLazyLoaded = new User(); - userLazyLoaded = users.get(3); - //since data is lazyloaded so data won't be initialized - Set orderDetailSet = userLazyLoaded.getOrderDetail(); - return (orderDetailSet); - } - - //eagerly loaded - public Set eagerLoaded(){ - final Session sessionEager = HibernateUtil.getHibernateSession(); - //data should be loaded in the following line - //also note the queries generated - List users =sessionEager.createQuery("From User").list(); - User userEagerLoaded = new User(); - userEagerLoaded = users.get(3); - Set orderDetailSet = userEagerLoaded.getOrderDetail(); - return orderDetailSet; - } - - - //creates test data - //call this method to create the data in the database - public void createTestData() { + public FetchingAppView() { - final Session session = HibernateUtil.getHibernateSession(); - Transaction tx = null; - tx = session.beginTransaction(); - final User user1 = new User(); - final User user2 = new User(); - final User user3 = new User(); - - user1.setFirstName("Priyam"); - user1.setLastName("Banerjee"); - user1.setUserName("priyambanerjee"); - session.save(user1); - - user2.setFirstName("Navneeta"); - user2.setLastName("Mukherjee"); - user2.setUserName("nmukh"); - session.save(user2); - - user3.setFirstName("Molly"); - user3.setLastName("Banerjee"); - user3.setUserName("mollyb"); - session.save(user3); + } - final OrderDetail order1 = new OrderDetail(); - final OrderDetail order2 = new OrderDetail(); - final OrderDetail order3 = new OrderDetail(); - final OrderDetail order4 = new OrderDetail(); - final OrderDetail order5 = new OrderDetail(); + // lazily loaded + public Set lazyLoaded() { + final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); + List users = sessionLazy.createQuery("From UserLazy").list(); + UserLazy userLazyLoaded = users.get(3); + // since data is lazyloaded so data won't be initialized + return (userLazyLoaded.getOrderDetail()); + } - order1.setOrderDesc("First Order"); - order1.setOrderDate(new Date(2014, 10, 12)); - order1.setUser(user1); - - order2.setOrderDesc("Second Order"); - order2.setOrderDate(new Date(2016, 10, 25)); - order2.setUser(user1); - - order3.setOrderDesc("Third Order"); - order3.setOrderDate(new Date(2015, 2, 17)); - order3.setUser(user2); - - order4.setOrderDesc("Fourth Order"); - order4.setOrderDate(new Date(2014, 10, 1)); - order4.setUser(user2); - - order5.setOrderDesc("Fifth Order"); - order5.setOrderDate(new Date(2014, 9, 11)); - order5.setUser(user3); - - session.saveOrUpdate(order1); - session.saveOrUpdate(order2); - session.saveOrUpdate(order3); - session.saveOrUpdate(order4); - session.saveOrUpdate(order5); + // eagerly loaded + public Set eagerLoaded() { + final Session sessionEager = HibernateUtil.getHibernateSession(); + // data should be loaded in the following line + // also note the queries generated + List user = sessionEager.createQuery("From UserEager").list(); + UserEager userEagerLoaded = user.get(3); + return userEagerLoaded.getOrderDetail(); + } - tx.commit(); - session.close(); + // creates test data + // call this method to create the data in the database + public void createTestData() { - } + final Session session = HibernateUtil.getHibernateSession("lazy"); + Transaction tx = session.beginTransaction(); + final UserLazy user1 = new UserLazy(); + final UserLazy user2 = new UserLazy(); + final UserLazy user3 = new UserLazy(); + + session.save(user1); + session.save(user2); + session.save(user3); + + final OrderDetail order1 = new OrderDetail(); + final OrderDetail order2 = new OrderDetail(); + final OrderDetail order3 = new OrderDetail(); + final OrderDetail order4 = new OrderDetail(); + final OrderDetail order5 = new OrderDetail(); + + session.saveOrUpdate(order1); + session.saveOrUpdate(order2); + session.saveOrUpdate(order3); + session.saveOrUpdate(order4); + session.saveOrUpdate(order5); + + tx.commit(); + session.close(); + + } } diff --git a/spring-hibernate4/src/main/resources/fetching.cfg.xml b/spring-hibernate4/src/main/resources/fetching.cfg.xml index 4a7e574dda..1b9a4a191c 100644 --- a/spring-hibernate4/src/main/resources/fetching.cfg.xml +++ b/spring-hibernate4/src/main/resources/fetching.cfg.xml @@ -11,7 +11,10 @@ iamtheking org.hibernate.dialect.MySQLDialect true - - + validate + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml index 1f9a7df94e..c5f608e1a7 100644 --- a/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml +++ b/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml @@ -11,7 +11,7 @@ iamtheking org.hibernate.dialect.MySQLDialect true - - + + \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/fetching_create_queries.sql b/spring-hibernate4/src/main/resources/fetching_create_queries.sql index 11a4239e0d..b36d9828f1 100644 --- a/spring-hibernate4/src/main/resources/fetching_create_queries.sql +++ b/spring-hibernate4/src/main/resources/fetching_create_queries.sql @@ -1,17 +1,12 @@ CREATE TABLE `user` ( `user_id` int(10) NOT NULL AUTO_INCREMENT, - `USERNAME` varchar(100) DEFAULT NULL, - `FIRST_NAME` varchar(255) NOT NULL, - `LAST_NAME` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ; CREATE TABLE `user_order` ( `ORDER_ID` int(10) NOT NULL AUTO_INCREMENT, - `ORDER_DATE` date DEFAULT NULL, `USER_ID` int(10) NOT NULL DEFAULT '0', - `ORDER_DESC` varchar(1024) DEFAULT NULL, PRIMARY KEY (`ORDER_ID`,`USER_ID`), KEY `USER_ID` (`USER_ID`), CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`) diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java index fb3d0f92fc..a650f8eb37 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -1,21 +1,21 @@ package com.baeldung.hibernate.fetching; -import static org.junit.Assert.*; -import java.util.Set; - +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.view.FetchingAppView; import org.hibernate.Hibernate; import org.junit.Before; import org.junit.Test; -import com.baeldung.hibernate.fetching.model.OrderDetail; +import java.util.Set; -import com.baeldung.hibernate.fetching.view.FetchingAppView; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class HibernateFetchingTest { //this loads sample data in the database - @Before + @Before public void addFecthingTestData(){ FetchingAppView fav = new FetchingAppView(); fav.createTestData(); diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml deleted file mode 100644 index e0b6516b47..0000000000 --- a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml deleted file mode 100644 index 88882b973e..0000000000 --- a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml deleted file mode 100644 index 2f941fe8b0..0000000000 --- a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetching.cfg.xml b/spring-hibernate4/src/test/resources/fetching.cfg.xml index 4a7e574dda..acee7008ba 100644 --- a/spring-hibernate4/src/test/resources/fetching.cfg.xml +++ b/spring-hibernate4/src/test/resources/fetching.cfg.xml @@ -11,7 +11,8 @@ iamtheking org.hibernate.dialect.MySQLDialect true - - + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml index 1f9a7df94e..1dc37d0cf8 100644 --- a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml +++ b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml @@ -11,7 +11,8 @@ iamtheking org.hibernate.dialect.MySQLDialect true - - + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java new file mode 100644 index 0000000000..c1e79a2a63 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java @@ -0,0 +1,42 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.spring.web.config.WebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class EmployeeTest { + + @Autowired + private WebApplicationContext webAppContext; + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); + } + + @Test + public void whenEmployeeGETisPerformed_thenRetrievedStatusAndViewNameAndAttributeAreCorrect() throws Exception { + mockMvc.perform(get("/employee")).andExpect(status().isOk()).andExpect(view().name("employeeHome")).andExpect(model().attributeExists("employee")).andDo(print()); + } +} diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index bc415d0455..77b11f1cb1 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -248,11 +248,11 @@ test - - org.hamcrest - hamcrest-core - test - + + + + + org.hamcrest hamcrest-library diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java index e1a83eeeb5..5718a827c9 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java @@ -16,29 +16,29 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { - public WebConfig() { - super(); - } + public WebConfig() { + super(); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/WEB-INF/view/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/WEB-INF/view/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } - // API - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/graph.html"); - registry.addViewController("/csrfHome.html"); - registry.addViewController("/homepage.html"); - } + // API + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/graph.html"); + registry.addViewController("/csrfHome.html"); + registry.addViewController("/homepage.html"); + } - @Override - public void addInterceptors(final InterceptorRegistry registry) { - registry.addInterceptor(new LoggerInterceptor()); - } + @Override + public void addInterceptors(final InterceptorRegistry registry) { + registry.addInterceptor(new LoggerInterceptor()); + } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java index 64a29f20d3..e87d5f3dd4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java @@ -14,20 +14,20 @@ import org.springframework.web.bind.annotation.ResponseStatus; @Controller @RequestMapping(value = "/auth/") public class BankController { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @RequestMapping(value = "/transfer", method = RequestMethod.GET) - @ResponseBody - public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { - logger.info("Transfer to {}", accountNo); - return amount; - } + @RequestMapping(value = "/transfer", method = RequestMethod.GET) + @ResponseBody + public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { + logger.info("Transfer to {}", accountNo); + return amount; + } - // write - just for test - @RequestMapping(value = "/transfer", method = RequestMethod.POST) - @ResponseStatus(HttpStatus.OK) - public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { - logger.info("Transfer to {}", accountNo); + // write - just for test + @RequestMapping(value = "/transfer", method = RequestMethod.POST) + @ResponseStatus(HttpStatus.OK) + public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { + logger.info("Transfer to {}", accountNo); - } + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index 1e00d6350b..c50e80bec2 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -32,90 +32,90 @@ import com.google.common.base.Preconditions; @RequestMapping(value = "/auth/foos") public class FooController { - @Autowired - private ApplicationEventPublisher eventPublisher; + @Autowired + private ApplicationEventPublisher eventPublisher; - @Autowired - private IFooService service; + @Autowired + private IFooService service; - public FooController() { - super(); - } + public FooController() { + super(); + } - // API + // API - @RequestMapping(method = RequestMethod.GET, value = "/count") - @ResponseBody - @ResponseStatus(value = HttpStatus.OK) - public long count() { - return 2l; - } + @RequestMapping(method = RequestMethod.GET, value = "/count") + @ResponseBody + @ResponseStatus(value = HttpStatus.OK) + public long count() { + return 2l; + } - // read - one + // read - one - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); - eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); - return resourceById; - } + eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); + return resourceById; + } - // read - all + // read - all - @RequestMapping(method = RequestMethod.GET) - @ResponseBody - public List findAll() { - return service.findAll(); - } + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List findAll() { + return service.findAll(); + } - @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) - @ResponseBody - public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { - final Page resultPage = service.findPaginated(page, size); - if (page > resultPage.getTotalPages()) { - throw new MyResourceNotFoundException(); - } - eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size)); + @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) + @ResponseBody + public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { + final Page resultPage = service.findPaginated(page, size); + if (page > resultPage.getTotalPages()) { + throw new MyResourceNotFoundException(); + } + eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size)); - return resultPage.getContent(); - } + return resultPage.getContent(); + } - // write + // write - @RequestMapping(method = RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { - Preconditions.checkNotNull(resource); - final Foo foo = service.create(resource); - final Long idOfCreatedResource = foo.getId(); + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + Preconditions.checkNotNull(resource); + final Foo foo = service.create(resource); + final Long idOfCreatedResource = foo.getId(); - eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); + eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); - return foo; - } + return foo; + } - @RequestMapping(value = "/{id}", method = RequestMethod.PUT) - @ResponseStatus(HttpStatus.OK) - public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { - Preconditions.checkNotNull(resource); - RestPreconditions.checkFound(service.findOne(resource.getId())); - service.update(resource); - } + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + @ResponseStatus(HttpStatus.OK) + public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { + Preconditions.checkNotNull(resource); + RestPreconditions.checkFound(service.findOne(resource.getId())); + service.update(resource); + } - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) - @ResponseStatus(HttpStatus.OK) - public void delete(@PathVariable("id") final Long id) { - service.deleteById(id); - } + @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) + @ResponseStatus(HttpStatus.OK) + public void delete(@PathVariable("id") final Long id) { + service.deleteById(id); + } - @RequestMapping(method = RequestMethod.HEAD) - @ResponseStatus(HttpStatus.OK) - public void head(final HttpServletResponse resp) { - resp.setContentType(MediaType.APPLICATION_JSON_VALUE); - resp.setHeader("bar", "baz"); - } + @RequestMapping(method = RequestMethod.HEAD) + @ResponseStatus(HttpStatus.OK) + public void head(final HttpServletResponse resp) { + resp.setContentType(MediaType.APPLICATION_JSON_VALUE); + resp.setHeader("bar", "baz"); + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java index 3e6a6627df..9c4d14cae3 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java @@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping(value = "/") public class HomeController { - public String index() { - return "homepage"; - } + public String index() { + return "homepage"; + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java index bcf0ceb5e6..8b63275b66 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java @@ -23,63 +23,63 @@ import org.springframework.web.util.UriTemplate; @RequestMapping(value = "/auth/") public class RootController { - @Autowired - private IMetricService metricService; + @Autowired + private IMetricService metricService; - @Autowired - private IActuatorMetricService actMetricService; + @Autowired + private IActuatorMetricService actMetricService; - public RootController() { - super(); - } + public RootController() { + super(); + } - // API + // API - // discover + // discover - @RequestMapping(value = "admin", method = RequestMethod.GET) - @ResponseStatus(value = HttpStatus.NO_CONTENT) - public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { - final String rootUri = request.getRequestURL().toString(); + @RequestMapping(value = "admin", method = RequestMethod.GET) + @ResponseStatus(value = HttpStatus.NO_CONTENT) + public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { + final String rootUri = request.getRequestURL().toString(); - final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); - final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); - response.addHeader("Link", linkToFoo); - } + final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); + final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); + response.addHeader("Link", linkToFoo); + } - @RequestMapping(value = "/metric", method = RequestMethod.GET) - @ResponseBody - public Map getMetric() { - return metricService.getFullMetric(); - } + @RequestMapping(value = "/metric", method = RequestMethod.GET) + @ResponseBody + public Map getMetric() { + return metricService.getFullMetric(); + } - @PreAuthorize("hasRole('ROLE_ADMIN')") - @RequestMapping(value = "/status-metric", method = RequestMethod.GET) - @ResponseBody - public Map getStatusMetric() { - return metricService.getStatusMetric(); - } + @PreAuthorize("hasRole('ROLE_ADMIN')") + @RequestMapping(value = "/status-metric", method = RequestMethod.GET) + @ResponseBody + public Map getStatusMetric() { + return metricService.getStatusMetric(); + } - @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) - @ResponseBody - public Object[][] drawMetric() { - final Object[][] result = metricService.getGraphData(); - for (int i = 1; i < result[0].length; i++) { - result[0][i] = result[0][i].toString(); - } - return result; - } + @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) + @ResponseBody + public Object[][] drawMetric() { + final Object[][] result = metricService.getGraphData(); + for (int i = 1; i < result[0].length; i++) { + result[0][i] = result[0][i].toString(); + } + return result; + } - @RequestMapping(value = "/admin/x", method = RequestMethod.GET) - @ResponseBody - public String sampleAdminPage() { - return "Hello"; - } + @RequestMapping(value = "/admin/x", method = RequestMethod.GET) + @ResponseBody + public String sampleAdminPage() { + return "Hello"; + } - @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) - @ResponseBody - public String sampleErrorPage() { - return "Error Occurred"; - } + @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) + @ResponseBody + public String sampleErrorPage() { + return "Error Occurred"; + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java index 2228287f4d..cf46e35e57 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java @@ -40,94 +40,94 @@ import cz.jirutka.rsql.parser.ast.Node; @RequestMapping(value = "/auth/") public class UserController { - @Autowired - private IUserDAO service; + @Autowired + private IUserDAO service; - @Autowired - private UserRepository dao; + @Autowired + private UserRepository dao; - @Autowired - private MyUserRepository myUserRepository; + @Autowired + private MyUserRepository myUserRepository; - public UserController() { - super(); - } + public UserController() { + super(); + } - // API - READ + // API - READ - @RequestMapping(method = RequestMethod.GET, value = "/users") - @ResponseBody - public List findAll(@RequestParam(value = "search", required = false) final String search) { - final List params = new ArrayList(); - if (search != null) { - final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); - } - } - return service.searchUser(params); - } + @RequestMapping(method = RequestMethod.GET, value = "/users") + @ResponseBody + public List findAll(@RequestParam(value = "search", required = false) final String search) { + final List params = new ArrayList(); + if (search != null) { + final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); + } + } + return service.searchUser(params); + } - @RequestMapping(method = RequestMethod.GET, value = "/users/spec") - @ResponseBody - public List findAllBySpecification(@RequestParam(value = "search") final String search) { - final UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); - final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET); - final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5)); - } + @RequestMapping(method = RequestMethod.GET, value = "/users/spec") + @ResponseBody + public List findAllBySpecification(@RequestParam(value = "search") final String search) { + final UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); + final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET); + final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5)); + } - final Specification spec = builder.build(); - return dao.findAll(spec); - } + final Specification spec = builder.build(); + return dao.findAll(spec); + } - @RequestMapping(method = RequestMethod.GET, value = "/myusers") - @ResponseBody - public Iterable findAllByQuerydsl(@RequestParam(value = "search") final String search) { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); - if (search != null) { - final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); - } - } - final BooleanExpression exp = builder.build(); - return myUserRepository.findAll(exp); - } + @RequestMapping(method = RequestMethod.GET, value = "/myusers") + @ResponseBody + public Iterable findAllByQuerydsl(@RequestParam(value = "search") final String search) { + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); + if (search != null) { + final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); + } + } + final BooleanExpression exp = builder.build(); + return myUserRepository.findAll(exp); + } - @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") - @ResponseBody - public List findAllByRsql(@RequestParam(value = "search") final String search) { - final Node rootNode = new RSQLParser().parse(search); - final Specification spec = rootNode.accept(new CustomRsqlVisitor()); - return dao.findAll(spec); - } + @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") + @ResponseBody + public List findAllByRsql(@RequestParam(value = "search") final String search) { + final Node rootNode = new RSQLParser().parse(search); + final Specification spec = rootNode.accept(new CustomRsqlVisitor()); + return dao.findAll(spec); + } - @RequestMapping(method = RequestMethod.GET, value = "/api/myusers") - @ResponseBody - public Iterable findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) { - return myUserRepository.findAll(predicate); - } + @RequestMapping(method = RequestMethod.GET, value = "/api/myusers") + @ResponseBody + public Iterable findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) { + return myUserRepository.findAll(predicate); + } - // API - WRITE + // API - WRITE - @RequestMapping(method = RequestMethod.POST, value = "/users") - @ResponseStatus(HttpStatus.CREATED) - public void create(@RequestBody final User resource) { - Preconditions.checkNotNull(resource); - dao.save(resource); - } + @RequestMapping(method = RequestMethod.POST, value = "/users") + @ResponseStatus(HttpStatus.CREATED) + public void create(@RequestBody final User resource) { + Preconditions.checkNotNull(resource); + dao.save(resource); + } - @RequestMapping(method = RequestMethod.POST, value = "/myusers") - @ResponseStatus(HttpStatus.CREATED) - public void addMyUser(@RequestBody final MyUser resource) { - Preconditions.checkNotNull(resource); - myUserRepository.save(resource); + @RequestMapping(method = RequestMethod.POST, value = "/myusers") + @ResponseStatus(HttpStatus.CREATED) + public void addMyUser(@RequestBody final MyUser resource) { + Preconditions.checkNotNull(resource); + myUserRepository.save(resource); - } + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java index 6afbd921ec..7c68d3e9c7 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java @@ -27,8 +27,7 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter { * Executed before after handler is executed **/ @Override - public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, - final ModelAndView modelAndView) throws Exception { + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception { log.info("[postHandle][" + request + "]"); } @@ -36,8 +35,7 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter { * Executed after complete request is finished **/ @Override - public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) - throws Exception { + public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception { if (ex != null) ex.printStackTrace(); log.info("[afterCompletion][" + request + "][exception: " + ex + "]"); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/SecurityTestSuite.java b/spring-security-rest-full/src/test/java/org/baeldung/security/SecurityTestSuite.java index 5b19d9fbcc..8b754a03ff 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/SecurityTestSuite.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/SecurityTestSuite.java @@ -1,6 +1,5 @@ package org.baeldung.security; - import org.baeldung.security.csrf.CsrfDisabledIntegrationTest; import org.baeldung.security.csrf.CsrfEnabledIntegrationTest; import org.junit.runner.RunWith; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 35b840a649..1b5f7cd894 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -23,30 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper; @WebAppConfiguration public class CsrfAbstractIntegrationTest { - @Autowired - private WebApplicationContext context; + @Autowired + private WebApplicationContext context; - @Autowired - private Filter springSecurityFilterChain; + @Autowired + private Filter springSecurityFilterChain; - protected MockMvc mvc; + protected MockMvc mvc; - // + // - @Before - public void setup() { - mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); - } + @Before + public void setup() { + mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); + } - protected RequestPostProcessor testUser() { - return user("user").password("userPass").roles("USER"); - } + protected RequestPostProcessor testUser() { + return user("user").password("userPass").roles("USER"); + } - protected RequestPostProcessor testAdmin() { - return user("admin").password("adminPass").roles("USER", "ADMIN"); - } + protected RequestPostProcessor testAdmin() { + return user("admin").password("adminPass").roles("USER", "ADMIN"); + } - protected String createFoo() throws JsonProcessingException { - return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); - } + protected String createFoo() throws JsonProcessingException { + return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java index 1f5cf078f3..63efd870cd 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java @@ -14,33 +14,31 @@ import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest { - @Test - public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception { - mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized()); - } + @Test + public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception { + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized()); + } - @Test - public void givenAuth_whenAddFoo_thenCreated() throws Exception { - mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated()); - } + @Test + public void givenAuth_whenAddFoo_thenCreated() throws Exception { + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated()); + } - @Test - public void accessMainPageWithoutAuthorization() throws Exception { - mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); - } + @Test + public void accessMainPageWithoutAuthorization() throws Exception { + mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + } - @Test - public void accessOtherPages() throws Exception { - mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100")) - .andExpect(status().isUnauthorized()); // without authorization - mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser())) - .andExpect(status().isOk()); // with authorization - } + @Test + public void accessOtherPages() throws Exception { + mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100")).andExpect(status().isUnauthorized()); // without authorization + mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser())).andExpect(status().isOk()); // with authorization + } - @Test - public void accessAdminPage() throws Exception { - mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); //without authorization - mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); //with authorization - } + @Test + public void accessAdminPage() throws Exception { + mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); // without authorization + mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); // with authorization + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java index 8aa9162edc..930ab20262 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java @@ -25,27 +25,27 @@ import org.springframework.web.context.WebApplicationContext; @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) public class LoggerInterceptorTest { - @Autowired - WebApplicationContext wac; - @Autowired - MockHttpSession session; + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; - private MockMvc mockMvc; + private MockMvc mockMvc; - @Before - public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); - } + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } - /** - * After execution of HTTP GET logs from interceptor will be displayed in - * the console - * - * @throws Exception - */ - @Test - public void testInterceptors() throws Exception { - mockMvc.perform(get("/graph.html")).andExpect(status().isOk()); - } + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + * + * @throws Exception + */ + @Test + public void testInterceptors() throws Exception { + mockMvc.perform(get("/graph.html")).andExpect(status().isOk()); + } } diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java index af1c103739..d4616dd5a6 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java @@ -1,5 +1,7 @@ package com.baeldung.spring.security.x509; +import java.security.Principal; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; @@ -7,8 +9,6 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; -import java.security.Principal; - @Controller public class UserController { @PreAuthorize("hasAuthority('ROLE_USER')") diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java index edcacfda15..b99c242408 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java @@ -2,21 +2,15 @@ package com.baeldung.spring.security.x509; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; @SpringBootApplication @EnableWebSecurity public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { + public static void main(String[] args) { SpringApplication.run(X509AuthenticationServer.class, args); } + } diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java index af1c103739..d4616dd5a6 100644 --- a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java @@ -1,5 +1,7 @@ package com.baeldung.spring.security.x509; +import java.security.Principal; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; @@ -7,8 +9,6 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; -import java.security.Principal; - @Controller public class UserController { @PreAuthorize("hasAuthority('ROLE_USER')") diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java index 7d8413589e..050423238e 100644 --- a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java @@ -23,9 +23,7 @@ public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated() - .and() - .x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService()); + http.authorizeRequests().anyRequest().authenticated().and().x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService()); } @Bean