Merge remote-tracking branch 'upstream/master' into craedel-spring-cloud-hystrix
This commit is contained in:
commit
33fc42103a
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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<Integer> givenList = Arrays.asList(1, 2, 3);
|
||||
Random rand = new Random();
|
||||
givenList.get(rand.nextInt(givenList.size()));
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
line 1
|
||||
a second line
|
|
@ -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"));
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.iml
|
|
@ -62,11 +62,11 @@
|
|||
<artifactId>hystrix-metrics-event-stream</artifactId>
|
||||
<version>${hystrix-metrics-event-stream.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<!--<dependency>
|
||||
<groupId>com.netflix.hystrix</groupId>
|
||||
<artifactId>hystrix-dashboard</artifactId>
|
||||
<version>${hystrix-dashboard.version}</version>
|
||||
</dependency>
|
||||
</dependency>-->
|
||||
<dependency>
|
||||
<groupId>com.netflix.rxjava</groupId>
|
||||
<artifactId>rxjava-core</artifactId>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,49 @@
|
|||
<?xml version="1.0"?>
|
||||
<project
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>mapstruct</artifactId>
|
||||
<name>mapstruct</name>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<org.mapstruct.version>1.0.0.Final</org.mapstruct.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-jdk8</artifactId>
|
||||
<version>${org.mapstruct.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>mapstruct</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>${org.mapstruct.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -24,6 +24,17 @@
|
|||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>4.3.2.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>4.3.2.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>mapstruct</finalName>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -4,8 +4,8 @@ public class EmployeeDTO {
|
|||
|
||||
private int employeeId;
|
||||
private String employeeName;
|
||||
private int divisionId;
|
||||
private String divisionName;
|
||||
private DivisionDTO division;
|
||||
private String employeeStartDt;
|
||||
|
||||
public int getEmployeeId() {
|
||||
return employeeId;
|
||||
|
@ -23,20 +23,20 @@ public class EmployeeDTO {
|
|||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,10 +1,13 @@
|
|||
package org.baeldung.entity;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
private Division division;
|
||||
private Date startDt;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
|
@ -30,4 +33,12 @@ public class Employee {
|
|||
this.division = division;
|
||||
}
|
||||
|
||||
public Date getStartDt() {
|
||||
return startDt;
|
||||
}
|
||||
|
||||
public void setStartDt(Date startDt) {
|
||||
this.startDt = startDt;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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")
|
||||
})
|
||||
@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="division",expression="java(new org.baeldung.entity.Division(dto.getDivisionId(),dto.getDivisionName()))")
|
||||
})
|
||||
@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<Employee> convertEmployeeDTOListToEmployeeList(List<EmployeeDTO> list);
|
||||
|
||||
List<EmployeeDTO> convertEmployeeListToEmployeeDTOList(List<Employee> list);
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
||||
SimpleSource destinationToSource(SimpleDestination destination);
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
|
||||
xmlns:aop="http://www.springframework.org/schema/aop"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
|
||||
http://www.springframework.org/schema/aop
|
||||
http://www.springframework.org/schema/aop/spring-aop.xsd">
|
||||
|
||||
<context:component-scan base-package="org.baeldung" />
|
||||
|
||||
</beans>
|
|
@ -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;
|
||||
|
@ -10,39 +17,107 @@ import org.mapstruct.factory.Mappers;
|
|||
|
||||
public class EmployeeMapperTest {
|
||||
|
||||
@Test
|
||||
public void givenEmployeeDTOtoEmployee_whenMaps_thenCorrect(){
|
||||
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.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());
|
||||
assertEquals(dto.getEmployeeId(), entity.getId());
|
||||
assertEquals(dto.getEmployeeName(), entity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeetoEmployeeDTO_whenMaps_thenCorrect(){
|
||||
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
|
||||
|
||||
public void givenEmployeewithDiffNametoEmployeeDTO_whenMaps_thenCorrect() {
|
||||
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());
|
||||
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<Employee> employeeList = new ArrayList<>();
|
||||
Employee emp = new Employee();
|
||||
emp.setId(1);
|
||||
emp.setName("EmpName");
|
||||
emp.setDivision(new Division(1, "Division1"));
|
||||
employeeList.add(emp);
|
||||
|
||||
List<EmployeeDTO> 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<EmployeeDTO> employeeDTOList = new ArrayList<>();
|
||||
EmployeeDTO empDTO = new EmployeeDTO();
|
||||
empDTO.setEmployeeId(1);
|
||||
empDTO.setEmployeeName("EmpName");
|
||||
empDTO.setDivision(new DivisionDTO(1, "Division1"));
|
||||
employeeDTOList.add(empDTO);
|
||||
|
||||
List<Employee> 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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,25 +1,29 @@
|
|||
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 {
|
||||
|
||||
@Autowired
|
||||
SimpleSourceDestinationMapper simpleSourceDestinationMapper;
|
||||
|
||||
@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);
|
||||
SimpleDestination destination = simpleSourceDestinationMapper.sourceToDestination(simpleSource);
|
||||
|
||||
assertEquals(simpleSource.getName(), destination.getName());
|
||||
assertEquals(simpleSource.getDescription(), destination.getDescription());
|
||||
|
@ -27,15 +31,11 @@ public class SimpleSourceDestinationMapperTest {
|
|||
|
||||
@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);
|
||||
SimpleSource source = simpleSourceDestinationMapper.destinationToSource(destination);
|
||||
|
||||
assertEquals(destination.getName(), source.getName());
|
||||
assertEquals(destination.getDescription(), source.getDescription());
|
||||
|
|
|
@ -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++;
|
||||
}
|
||||
}
|
|
@ -124,9 +124,6 @@
|
|||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<verbose>true</verbose>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
|
|
@ -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<String, String> getCommitId() {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
result.put("Commit message",commitMessage);
|
||||
result.put("Commit branch", branch);
|
||||
result.put("Commit id", commitId);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
@Column(name="ORDER_ID")
|
||||
private Long orderId;
|
||||
private Date orderDate;
|
||||
private String orderDesc;
|
||||
private User user;
|
||||
|
||||
public OrderDetail(){
|
||||
}
|
||||
|
||||
public OrderDetail(Date orderDate, String orderDesc) {
|
||||
super();
|
||||
this.orderDate = orderDate;
|
||||
this.orderDesc = orderDesc;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
|
@ -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> orderDetail = new HashSet<OrderDetail>();
|
||||
|
||||
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<OrderDetail> getOrderDetail() {
|
||||
return orderDetail;
|
||||
}
|
||||
|
||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||
this.orderDetail = orderDetail;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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> 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<OrderDetail> getOrderDetail() {
|
||||
return orderDetail;
|
||||
}
|
||||
|
||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||
this.orderDetail = orderDetail;
|
||||
}
|
||||
|
||||
}
|
|
@ -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> 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<OrderDetail> getOrderDetail() {
|
||||
return orderDetail;
|
||||
}
|
||||
|
||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||
this.orderDetail = orderDetail;
|
||||
}
|
||||
|
||||
}
|
|
@ -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() {
|
||||
|
|
|
@ -1,75 +1,52 @@
|
|||
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(){
|
||||
public FetchingAppView() {
|
||||
|
||||
}
|
||||
|
||||
//lazily loaded
|
||||
public Set<OrderDetail> lazyLoaded(){
|
||||
// lazily loaded
|
||||
public Set<OrderDetail> lazyLoaded() {
|
||||
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
|
||||
List<User> 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<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail();
|
||||
return (orderDetailSet);
|
||||
List<UserLazy> users = sessionLazy.createQuery("From UserLazy").list();
|
||||
UserLazy userLazyLoaded = users.get(3);
|
||||
// since data is lazyloaded so data won't be initialized
|
||||
return (userLazyLoaded.getOrderDetail());
|
||||
}
|
||||
|
||||
//eagerly loaded
|
||||
public Set<OrderDetail> eagerLoaded(){
|
||||
// eagerly loaded
|
||||
public Set<OrderDetail> eagerLoaded() {
|
||||
final Session sessionEager = HibernateUtil.getHibernateSession();
|
||||
//data should be loaded in the following line
|
||||
//also note the queries generated
|
||||
List<User> users =sessionEager.createQuery("From User").list();
|
||||
User userEagerLoaded = new User();
|
||||
userEagerLoaded = users.get(3);
|
||||
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
|
||||
return orderDetailSet;
|
||||
// data should be loaded in the following line
|
||||
// also note the queries generated
|
||||
List<UserEager> user = sessionEager.createQuery("From UserEager").list();
|
||||
UserEager userEagerLoaded = user.get(3);
|
||||
return userEagerLoaded.getOrderDetail();
|
||||
}
|
||||
|
||||
|
||||
//creates test data
|
||||
//call this method to create the data in the database
|
||||
// creates test data
|
||||
// call this method to create the data in the database
|
||||
public void createTestData() {
|
||||
|
||||
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();
|
||||
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();
|
||||
|
||||
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();
|
||||
|
@ -78,26 +55,6 @@ public class FetchingAppView {
|
|||
final OrderDetail order4 = new OrderDetail();
|
||||
final OrderDetail order5 = new OrderDetail();
|
||||
|
||||
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);
|
||||
|
|
|
@ -11,7 +11,10 @@
|
|||
<property name="hibernate.connection.password">iamtheking</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="show_sql">true</property>
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
||||
<property name="hbm2ddl.auto">validate</property>
|
||||
|
||||
|
||||
<mapping class="com.baeldung.hibernate.fetching.model.UserEager" />
|
||||
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetailEager" />
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
|
@ -11,7 +11,7 @@
|
|||
<property name="hibernate.connection.password">iamtheking</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="show_sql">true</property>
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
|
||||
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
|
||||
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
|
@ -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`)
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
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 {
|
||||
|
||||
|
|
|
@ -1,26 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE hibernate-mapping PUBLIC
|
||||
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
|
||||
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
|
||||
|
||||
<hibernate-mapping>
|
||||
<class name="com.baeldung.hibernate.fetching.model.OrderDetail" table="USER_ORDER">
|
||||
|
||||
<id name="orderId" type="java.lang.Long" column="ORDER_ID" >
|
||||
<generator class="native" />
|
||||
</id>
|
||||
|
||||
<property name="orderDate" type="date">
|
||||
<column name="ORDER_DATE" />
|
||||
</property>
|
||||
<property name="orderDesc" type="string">
|
||||
<column name="ORDER_DESC" not-null="true" />
|
||||
</property>
|
||||
|
||||
|
||||
<many-to-one name="user" class="com.baeldung.hibernate.fetching.model.User" fetch="select">
|
||||
<column name="user_id" not-null="true" />
|
||||
</many-to-one>
|
||||
|
||||
</class>
|
||||
</hibernate-mapping>
|
|
@ -1,31 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE hibernate-mapping PUBLIC
|
||||
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
|
||||
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
|
||||
<hibernate-mapping>
|
||||
<class name="com.baeldung.hibernate.fetching.model.User" table="USER">
|
||||
<id name="userId" type="long" unsaved-value="null">
|
||||
<column name="USER_ID" />
|
||||
<generator class="native" />
|
||||
</id>
|
||||
|
||||
<property name="userName" type="string">
|
||||
<column name="USERNAME" length="100" />
|
||||
</property>
|
||||
<property name="firstName" type="string">
|
||||
<column name="FIRST_NAME" not-null="true" />
|
||||
</property>
|
||||
<property name="lastName" type="string">
|
||||
<column name="LAST_NAME" not-null="true" />
|
||||
</property>
|
||||
|
||||
<set name="orderDetail" table="USER_ORDER"
|
||||
inverse="true" lazy="false" fetch="select">
|
||||
<key>
|
||||
<column name="USER_ID" not-null="true" />
|
||||
</key>
|
||||
<one-to-many class="com.baeldung.hibernate.fetching.model.OrderDetail" />
|
||||
</set>
|
||||
|
||||
</class>
|
||||
</hibernate-mapping>
|
|
@ -1,31 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE hibernate-mapping PUBLIC
|
||||
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
|
||||
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
|
||||
<hibernate-mapping>
|
||||
<class name="com.baeldung.hibernate.fetching.model.User" table="USER">
|
||||
<id name="userId" type="long" unsaved-value="null">
|
||||
<column name="USER_ID" />
|
||||
<generator class="native" />
|
||||
</id>
|
||||
|
||||
<property name="userName" type="string">
|
||||
<column name="USERNAME" length="100" />
|
||||
</property>
|
||||
<property name="firstName" type="string">
|
||||
<column name="FIRST_NAME" not-null="true" />
|
||||
</property>
|
||||
<property name="lastName" type="string">
|
||||
<column name="LAST_NAME" not-null="true" />
|
||||
</property>
|
||||
|
||||
<set name="orderDetail" table="USER_ORDER"
|
||||
inverse="true" lazy="true" fetch="select">
|
||||
<key>
|
||||
<column name="USER_ID" not-null="true" />
|
||||
</key>
|
||||
<one-to-many class="com.baeldung.hibernate.fetching.model.OrderDetail" />
|
||||
</set>
|
||||
|
||||
</class>
|
||||
</hibernate-mapping>
|
|
@ -11,7 +11,8 @@
|
|||
<property name="hibernate.connection.password">iamtheking</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="show_sql">true</property>
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
||||
|
||||
<mapping class="com.baeldung.hibernate.fetching.model.UserEager" />
|
||||
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetailEager" />
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
|
@ -11,7 +11,8 @@
|
|||
<property name="hibernate.connection.password">iamtheking</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="show_sql">true</property>
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
||||
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
|
||||
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
|
||||
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
|
||||
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -248,11 +248,11 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- <dependency> -->
|
||||
<!-- <groupId>org.hamcrest</groupId> -->
|
||||
<!-- <artifactId>hamcrest-core</artifactId> -->
|
||||
<!-- <scope>test</scope> -->
|
||||
<!-- </dependency> -->
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
|
|
|
@ -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 + "]");
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -31,16 +31,14 @@ public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
|
|||
|
||||
@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
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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')")
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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')")
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue