Merge remote-tracking branch 'upstream/master' into craedel-spring-cloud-hystrix
This commit is contained in:
commit
33fc42103a
53
core-java-8/src/test/java/com/baeldung/CharToStringTest.java
Normal file
53
core-java-8/src/test/java/com/baeldung/CharToStringTest.java
Normal file
@ -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.io.StringWriter;
|
||||||
import java.nio.charset.Charset;
|
import java.nio.charset.Charset;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.Scanner;
|
import java.util.Scanner;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.io.FileUtils;
|
||||||
@ -191,6 +192,16 @@ public class JavaInputStreamToXUnitTest {
|
|||||||
IOUtils.closeQuietly(outStream);
|
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
|
@Test
|
||||||
public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
|
public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
|
12
hystrix/.gitignore
vendored
Normal file
12
hystrix/.gitignore
vendored
Normal file
@ -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>
|
<artifactId>hystrix-metrics-event-stream</artifactId>
|
||||||
<version>${hystrix-metrics-event-stream.version}</version>
|
<version>${hystrix-metrics-event-stream.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<!--<dependency>
|
||||||
<groupId>com.netflix.hystrix</groupId>
|
<groupId>com.netflix.hystrix</groupId>
|
||||||
<artifactId>hystrix-dashboard</artifactId>
|
<artifactId>hystrix-dashboard</artifactId>
|
||||||
<version>${hystrix-dashboard.version}</version>
|
<version>${hystrix-dashboard.version}</version>
|
||||||
</dependency>
|
</dependency>-->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.netflix.rxjava</groupId>
|
<groupId>com.netflix.rxjava</groupId>
|
||||||
<artifactId>rxjava-core</artifactId>
|
<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.HystrixCommandProperties;
|
||||||
import com.netflix.hystrix.HystrixThreadPoolProperties;
|
import com.netflix.hystrix.HystrixThreadPoolProperties;
|
||||||
import com.netflix.hystrix.exception.HystrixRuntimeException;
|
import com.netflix.hystrix.exception.HystrixRuntimeException;
|
||||||
import org.junit.*;
|
import org.junit.Test;
|
||||||
import org.junit.rules.ExpectedException;
|
|
||||||
import org.junit.runners.MethodSorters;
|
|
||||||
|
|
||||||
import static org.hamcrest.MatcherAssert.assertThat;
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
|
||||||
@FixMethodOrder(MethodSorters.JVM)
|
|
||||||
public class HystrixTimeoutTest {
|
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
|
@Test
|
||||||
public void givenInputBobAndDefaultSettings_whenExecuted_thenReturnHelloBob(){
|
public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob(){
|
||||||
assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!"));
|
assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSvcTimeoutOf100AndDefaultSettings_whenExecuted_thenReturnSuccess()
|
public void givenSvcTimeoutOf100AndDefaultSettings_whenRemoteSvcExecuted_thenReturnSuccess()
|
||||||
throws InterruptedException {
|
throws InterruptedException {
|
||||||
|
|
||||||
HystrixCommand.Setter config = HystrixCommand
|
HystrixCommand.Setter config = HystrixCommand
|
||||||
.Setter
|
.Setter
|
||||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1"));
|
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2"));
|
||||||
|
|
||||||
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(),
|
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(),
|
||||||
equalTo("Success"));
|
equalTo("Success"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test(expected = HystrixRuntimeException.class)
|
||||||
public void givenSvcTimeoutOf10000AndDefaultSettings__whenExecuted_thenExpectHRE() throws InterruptedException {
|
public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException {
|
||||||
exception.expect(HystrixRuntimeException.class);
|
HystrixCommand.Setter config = HystrixCommand
|
||||||
|
.Setter
|
||||||
|
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3"));
|
||||||
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute();
|
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSvcTimeoutOf5000AndExecTimeoutOf10000__whenExecuted_thenReturnSuccess()
|
public void givenSvcTimeoutOf5000AndExecTimeoutOf10000_whenRemoteSvcExecuted_thenReturnSuccess()
|
||||||
throws InterruptedException {
|
throws InterruptedException {
|
||||||
|
|
||||||
|
HystrixCommand.Setter config = HystrixCommand
|
||||||
|
.Setter
|
||||||
|
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4"));
|
||||||
|
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
|
||||||
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
|
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
|
||||||
config.andCommandPropertiesDefaults(commandProperties);
|
config.andCommandPropertiesDefaults(commandProperties);
|
||||||
|
|
||||||
@ -63,10 +51,13 @@ public class HystrixTimeoutTest {
|
|||||||
equalTo("Success"));
|
equalTo("Success"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test(expected = HystrixRuntimeException.class)
|
||||||
public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE()
|
public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE()
|
||||||
throws InterruptedException {
|
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);
|
commandProperties.withExecutionTimeoutInMilliseconds(5_000);
|
||||||
config.andCommandPropertiesDefaults(commandProperties);
|
config.andCommandPropertiesDefaults(commandProperties);
|
||||||
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(15_000)).execute();
|
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(15_000)).execute();
|
||||||
@ -75,6 +66,11 @@ public class HystrixTimeoutTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess()
|
public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess()
|
||||||
throws InterruptedException {
|
throws InterruptedException {
|
||||||
|
|
||||||
|
HystrixCommand.Setter config = HystrixCommand
|
||||||
|
.Setter
|
||||||
|
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool"));
|
||||||
|
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
|
||||||
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
|
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
|
||||||
config.andCommandPropertiesDefaults(commandProperties);
|
config.andCommandPropertiesDefaults(commandProperties);
|
||||||
config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
|
config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
|
||||||
@ -85,4 +81,52 @@ public class HystrixTimeoutTest {
|
|||||||
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
|
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
|
||||||
equalTo("Success"));
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
49
mapstruct/bin/pom.xml
Normal file
49
mapstruct/bin/pom.xml
Normal file
@ -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>
|
<version>4.12</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</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>
|
</dependencies>
|
||||||
<build>
|
<build>
|
||||||
<finalName>mapstruct</finalName>
|
<finalName>mapstruct</finalName>
|
||||||
|
33
mapstruct/src/main/java/org/baeldung/dto/DivisionDTO.java
Normal file
33
mapstruct/src/main/java/org/baeldung/dto/DivisionDTO.java
Normal file
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -2,41 +2,41 @@ package org.baeldung.dto;
|
|||||||
|
|
||||||
public class EmployeeDTO {
|
public class EmployeeDTO {
|
||||||
|
|
||||||
private int employeeId;
|
private int employeeId;
|
||||||
private String employeeName;
|
private String employeeName;
|
||||||
private int divisionId;
|
private DivisionDTO division;
|
||||||
private String divisionName;
|
private String employeeStartDt;
|
||||||
|
|
||||||
public int getEmployeeId() {
|
public int getEmployeeId() {
|
||||||
return employeeId;
|
return employeeId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setEmployeeId(int employeeId) {
|
public void setEmployeeId(int employeeId) {
|
||||||
this.employeeId = employeeId;
|
this.employeeId = employeeId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getEmployeeName() {
|
public String getEmployeeName() {
|
||||||
return employeeName;
|
return employeeName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setEmployeeName(String employeeName) {
|
public void setEmployeeName(String employeeName) {
|
||||||
this.employeeName = employeeName;
|
this.employeeName = employeeName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getDivisionId() {
|
public DivisionDTO getDivision() {
|
||||||
return divisionId;
|
return division;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDivisionId(int divisionId) {
|
public void setDivision(DivisionDTO division) {
|
||||||
this.divisionId = divisionId;
|
this.division = division;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDivisionName() {
|
public String getEmployeeStartDt() {
|
||||||
return divisionName;
|
return employeeStartDt;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDivisionName(String divisionName) {
|
public void setEmployeeStartDt(String employeeStartDt) {
|
||||||
this.divisionName = divisionName;
|
this.employeeStartDt = employeeStartDt;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,23 +2,23 @@ package org.baeldung.dto;
|
|||||||
|
|
||||||
public class SimpleSource {
|
public class SimpleSource {
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
private String description;
|
private String description;
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
public String getName() {
|
||||||
this.name = name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDescription() {
|
public void setName(String name) {
|
||||||
return description;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,32 +2,32 @@ package org.baeldung.entity;
|
|||||||
|
|
||||||
public class Division {
|
public class Division {
|
||||||
|
|
||||||
public Division() {
|
public Division() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public Division(int id, String name) {
|
public Division(int id, String name) {
|
||||||
super();
|
super();
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int id;
|
private int id;
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
public int getId() {
|
public int getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(int id) {
|
public void setId(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,33 +1,44 @@
|
|||||||
package org.baeldung.entity;
|
package org.baeldung.entity;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
public class Employee {
|
public class Employee {
|
||||||
|
|
||||||
private int id;
|
private int id;
|
||||||
private String name;
|
private String name;
|
||||||
private Division division;
|
private Division division;
|
||||||
|
private Date startDt;
|
||||||
|
|
||||||
public int getId() {
|
public int getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(int id) {
|
public void setId(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Division getDivision() {
|
public Division getDivision() {
|
||||||
return division;
|
return division;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDivision(Division division) {
|
public void setDivision(Division division) {
|
||||||
this.division = division;
|
this.division = division;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Date getStartDt() {
|
||||||
|
return startDt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStartDt(Date startDt) {
|
||||||
|
this.startDt = startDt;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,23 +2,23 @@ package org.baeldung.entity;
|
|||||||
|
|
||||||
public class SimpleDestination {
|
public class SimpleDestination {
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
private String description;
|
private String description;
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
public String getName() {
|
||||||
this.name = name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDescription() {
|
public void setName(String name) {
|
||||||
return description;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDescription(String description) {
|
public String getDescription() {
|
||||||
this.description = description;
|
return description;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,10 @@
|
|||||||
package org.baeldung.mapper;
|
package org.baeldung.mapper;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.dto.DivisionDTO;
|
||||||
import org.baeldung.dto.EmployeeDTO;
|
import org.baeldung.dto.EmployeeDTO;
|
||||||
|
import org.baeldung.entity.Division;
|
||||||
import org.baeldung.entity.Employee;
|
import org.baeldung.entity.Employee;
|
||||||
import org.mapstruct.Mapper;
|
import org.mapstruct.Mapper;
|
||||||
import org.mapstruct.Mapping;
|
import org.mapstruct.Mapping;
|
||||||
@ -9,19 +13,18 @@ import org.mapstruct.Mappings;
|
|||||||
@Mapper
|
@Mapper
|
||||||
public interface EmployeeMapper {
|
public interface EmployeeMapper {
|
||||||
|
|
||||||
@Mappings({
|
@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") })
|
||||||
@Mapping(target="divisionId",source="entity.division.id"),
|
EmployeeDTO employeeToEmployeeDTO(Employee entity);
|
||||||
@Mapping(target="divisionName",source="entity.division.name"),
|
|
||||||
@Mapping(target="employeeId",source="entity.id"),
|
@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") })
|
||||||
@Mapping(target="employeeName",source="entity.name")
|
Employee employeeDTOtoEmployee(EmployeeDTO dto);
|
||||||
})
|
|
||||||
EmployeeDTO employeeToEmployeeDTO(Employee entity);
|
DivisionDTO divisionToDivisionDTO(Division entity);
|
||||||
|
|
||||||
@Mappings({
|
Division divisionDTOtoDivision(DivisionDTO dto);
|
||||||
@Mapping(target="id",source="dto.employeeId"),
|
|
||||||
@Mapping(target="name",source="dto.employeeName"),
|
List<Employee> convertEmployeeDTOListToEmployeeList(List<EmployeeDTO> list);
|
||||||
@Mapping(target="division",expression="java(new org.baeldung.entity.Division(dto.getDivisionId(),dto.getDivisionName()))")
|
|
||||||
})
|
List<EmployeeDTO> convertEmployeeListToEmployeeDTOList(List<Employee> list);
|
||||||
Employee employeeDTOtoEmployee(EmployeeDTO dto);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -4,10 +4,11 @@ import org.baeldung.dto.SimpleSource;
|
|||||||
import org.baeldung.entity.SimpleDestination;
|
import org.baeldung.entity.SimpleDestination;
|
||||||
import org.mapstruct.Mapper;
|
import org.mapstruct.Mapper;
|
||||||
|
|
||||||
@Mapper
|
@Mapper(componentModel = "spring")
|
||||||
public interface SimpleSourceDestinationMapper {
|
public interface SimpleSourceDestinationMapper {
|
||||||
|
|
||||||
SimpleDestination sourceToDestination(SimpleSource source);
|
SimpleDestination sourceToDestination(SimpleSource source);
|
||||||
|
|
||||||
SimpleSource destinationToSource(SimpleDestination destination);
|
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);
|
|
||||||
|
|
||||||
}
|
|
15
mapstruct/src/main/resources/applicationContext.xml
Normal file
15
mapstruct/src/main/resources/applicationContext.xml
Normal file
@ -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;
|
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.dto.EmployeeDTO;
|
||||||
import org.baeldung.entity.Division;
|
import org.baeldung.entity.Division;
|
||||||
import org.baeldung.entity.Employee;
|
import org.baeldung.entity.Employee;
|
||||||
@ -9,40 +16,108 @@ import org.junit.Test;
|
|||||||
import org.mapstruct.factory.Mappers;
|
import org.mapstruct.factory.Mappers;
|
||||||
|
|
||||||
public class EmployeeMapperTest {
|
public class EmployeeMapperTest {
|
||||||
|
|
||||||
@Test
|
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
|
||||||
public void givenEmployeeDTOtoEmployee_whenMaps_thenCorrect(){
|
|
||||||
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
|
private static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss";
|
||||||
|
|
||||||
EmployeeDTO dto = new EmployeeDTO();
|
@Test
|
||||||
dto.setDivisionId(1);
|
public void givenEmployeeDTOwithDiffNametoEmployee_whenMaps_thenCorrect() {
|
||||||
dto.setDivisionName("IT Division");
|
EmployeeDTO dto = new EmployeeDTO();
|
||||||
dto.setEmployeeId(1);
|
dto.setEmployeeId(1);
|
||||||
dto.setEmployeeName("John");
|
dto.setEmployeeName("John");
|
||||||
|
|
||||||
Employee entity = mapper.employeeDTOtoEmployee(dto);
|
Employee entity = mapper.employeeDTOtoEmployee(dto);
|
||||||
|
|
||||||
assertEquals(dto.getDivisionId(), entity.getDivision().getId());
|
assertEquals(dto.getEmployeeId(), entity.getId());
|
||||||
assertEquals(dto.getDivisionName(), entity.getDivision().getName());
|
assertEquals(dto.getEmployeeName(), entity.getName());
|
||||||
assertEquals(dto.getEmployeeId(),entity.getId());
|
}
|
||||||
assertEquals(dto.getEmployeeName(),entity.getName());
|
|
||||||
}
|
@Test
|
||||||
|
public void givenEmployeewithDiffNametoEmployeeDTO_whenMaps_thenCorrect() {
|
||||||
@Test
|
Employee entity = new Employee();
|
||||||
public void givenEmployeetoEmployeeDTO_whenMaps_thenCorrect(){
|
entity.setId(1);
|
||||||
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
|
entity.setName("John");
|
||||||
|
|
||||||
Employee entity = new Employee();
|
EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity);
|
||||||
entity.setDivision(new Division(1,"IT Division"));
|
|
||||||
entity.setId(1);
|
assertEquals(dto.getEmployeeId(), entity.getId());
|
||||||
entity.setName("John");
|
assertEquals(dto.getEmployeeName(), entity.getName());
|
||||||
|
}
|
||||||
EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity);
|
|
||||||
|
@Test
|
||||||
assertEquals(dto.getDivisionId(), entity.getDivision().getId());
|
public void givenEmployeeDTOwithNestedMappingToEmployee_whenMaps_thenCorrect() {
|
||||||
assertEquals(dto.getDivisionName(), entity.getDivision().getName());
|
EmployeeDTO dto = new EmployeeDTO();
|
||||||
assertEquals(dto.getEmployeeId(),entity.getId());
|
dto.setDivision(new DivisionDTO(1, "Division1"));
|
||||||
assertEquals(dto.getEmployeeName(),entity.getName());
|
|
||||||
}
|
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,44 +1,44 @@
|
|||||||
package org.baeldung.mapper;
|
package org.baeldung.mapper;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import org.baeldung.dto.SimpleSource;
|
import org.baeldung.dto.SimpleSource;
|
||||||
import org.baeldung.entity.SimpleDestination;
|
import org.baeldung.entity.SimpleDestination;
|
||||||
import org.junit.Test;
|
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 {
|
public class SimpleSourceDestinationMapperTest {
|
||||||
|
|
||||||
@Test
|
@Autowired
|
||||||
public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() {
|
SimpleSourceDestinationMapper simpleSourceDestinationMapper;
|
||||||
SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers
|
|
||||||
.getMapper(SimpleSourceDestinationMapper.class);
|
@Test
|
||||||
|
public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() {
|
||||||
SimpleSource simpleSource = new SimpleSource();
|
SimpleSource simpleSource = new SimpleSource();
|
||||||
simpleSource.setName("SourceName");
|
simpleSource.setName("SourceName");
|
||||||
simpleSource.setDescription("SourceDescription");
|
simpleSource.setDescription("SourceDescription");
|
||||||
|
|
||||||
SimpleDestination destination =
|
SimpleDestination destination = simpleSourceDestinationMapper.sourceToDestination(simpleSource);
|
||||||
simpleSourceDestinationMapper.sourceToDestination(simpleSource);
|
|
||||||
|
assertEquals(simpleSource.getName(), destination.getName());
|
||||||
assertEquals(simpleSource.getName(), destination.getName());
|
assertEquals(simpleSource.getDescription(), destination.getDescription());
|
||||||
assertEquals(simpleSource.getDescription(), destination.getDescription());
|
}
|
||||||
}
|
|
||||||
|
@Test
|
||||||
@Test
|
public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() {
|
||||||
public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() {
|
SimpleDestination destination = new SimpleDestination();
|
||||||
SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers
|
destination.setName("DestinationName");
|
||||||
.getMapper(SimpleSourceDestinationMapper.class);
|
destination.setDescription("DestinationDescription");
|
||||||
|
|
||||||
SimpleDestination destination = new SimpleDestination();
|
SimpleSource source = simpleSourceDestinationMapper.destinationToSource(destination);
|
||||||
destination.setName("DestinationName");
|
|
||||||
destination.setDescription("DestinationDescription");
|
assertEquals(destination.getName(), source.getName());
|
||||||
|
assertEquals(destination.getDescription(), source.getDescription());
|
||||||
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>
|
</goals>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
<configuration>
|
|
||||||
<verbose>true</verbose>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
</plugins>
|
</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.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
public class CommitInfoController {
|
public class CommitInfoController {
|
||||||
|
|
||||||
@ -17,7 +20,11 @@ public class CommitInfoController {
|
|||||||
private String commitId;
|
private String commitId;
|
||||||
|
|
||||||
@RequestMapping("/commitId")
|
@RequestMapping("/commitId")
|
||||||
public GitInfoDto getCommitId() {
|
public Map<String, String> getCommitId() {
|
||||||
return new GitInfoDto(commitMessage, branch, commitId);
|
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;
|
package com.baeldung.hibernate.fetching.model;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.sql.Date;
|
import java.sql.Date;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table (name = "USER_ORDER")
|
||||||
public class OrderDetail implements Serializable{
|
public class OrderDetail implements Serializable{
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
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) {
|
public OrderDetail(Date orderDate, String orderDesc) {
|
||||||
super();
|
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
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
@ -62,6 +46,7 @@ public class OrderDetail implements Serializable{
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Long getOrderId() {
|
public Long getOrderId() {
|
||||||
return orderId;
|
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
|
//two config files are there
|
||||||
//one with lazy loading enabled
|
//one with lazy loading enabled
|
||||||
//another lazy = false
|
//another lazy = false
|
||||||
SessionFactory sf = null;
|
SessionFactory sf;
|
||||||
if ("lazy".equals(fetchMethod)) {
|
if ("lazy".equals(fetchMethod)) {
|
||||||
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
|
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
|
||||||
} else {
|
} else {
|
||||||
@ -19,8 +19,7 @@ public class HibernateUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// fetching.cfg.xml is used for this example
|
// fetching.cfg.xml is used for this example
|
||||||
final Session session = sf.openSession();
|
return sf.openSession();
|
||||||
return session;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Session getHibernateSession() {
|
public static Session getHibernateSession() {
|
||||||
|
@ -1,111 +1,68 @@
|
|||||||
package com.baeldung.hibernate.fetching.view;
|
package com.baeldung.hibernate.fetching.view;
|
||||||
|
|
||||||
import java.sql.Date;
|
import com.baeldung.hibernate.fetching.model.OrderDetail;
|
||||||
import java.util.List;
|
import com.baeldung.hibernate.fetching.model.UserEager;
|
||||||
import java.util.Set;
|
import com.baeldung.hibernate.fetching.model.UserLazy;
|
||||||
|
import com.baeldung.hibernate.fetching.util.HibernateUtil;
|
||||||
import org.hibernate.Hibernate;
|
|
||||||
import org.hibernate.Session;
|
import org.hibernate.Session;
|
||||||
import org.hibernate.Transaction;
|
import org.hibernate.Transaction;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import com.baeldung.hibernate.fetching.util.HibernateUtil;
|
import java.util.Set;
|
||||||
|
|
||||||
import com.baeldung.hibernate.fetching.model.OrderDetail;
|
|
||||||
|
|
||||||
import com.baeldung.hibernate.fetching.model.User;
|
|
||||||
|
|
||||||
|
|
||||||
public class FetchingAppView {
|
public class FetchingAppView {
|
||||||
|
|
||||||
public FetchingAppView(){
|
public FetchingAppView() {
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
//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);
|
|
||||||
}
|
|
||||||
|
|
||||||
//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;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
//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();
|
|
||||||
|
|
||||||
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();
|
// lazily loaded
|
||||||
final OrderDetail order2 = new OrderDetail();
|
public Set<OrderDetail> lazyLoaded() {
|
||||||
final OrderDetail order3 = new OrderDetail();
|
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
|
||||||
final OrderDetail order4 = new OrderDetail();
|
List<UserLazy> users = sessionLazy.createQuery("From UserLazy").list();
|
||||||
final OrderDetail order5 = new OrderDetail();
|
UserLazy userLazyLoaded = users.get(3);
|
||||||
|
// since data is lazyloaded so data won't be initialized
|
||||||
|
return (userLazyLoaded.getOrderDetail());
|
||||||
|
}
|
||||||
|
|
||||||
order1.setOrderDesc("First Order");
|
// eagerly loaded
|
||||||
order1.setOrderDate(new Date(2014, 10, 12));
|
public Set<OrderDetail> eagerLoaded() {
|
||||||
order1.setUser(user1);
|
final Session sessionEager = HibernateUtil.getHibernateSession();
|
||||||
|
// data should be loaded in the following line
|
||||||
order2.setOrderDesc("Second Order");
|
// also note the queries generated
|
||||||
order2.setOrderDate(new Date(2016, 10, 25));
|
List<UserEager> user = sessionEager.createQuery("From UserEager").list();
|
||||||
order2.setUser(user1);
|
UserEager userEagerLoaded = user.get(3);
|
||||||
|
return userEagerLoaded.getOrderDetail();
|
||||||
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);
|
|
||||||
|
|
||||||
tx.commit();
|
// creates test data
|
||||||
session.close();
|
// 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();
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,10 @@
|
|||||||
<property name="hibernate.connection.password">iamtheking</property>
|
<property name="hibernate.connection.password">iamtheking</property>
|
||||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||||
<property name="show_sql">true</property>
|
<property name="show_sql">true</property>
|
||||||
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
|
<property name="hbm2ddl.auto">validate</property>
|
||||||
<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>
|
</session-factory>
|
||||||
</hibernate-configuration>
|
</hibernate-configuration>
|
@ -11,7 +11,7 @@
|
|||||||
<property name="hibernate.connection.password">iamtheking</property>
|
<property name="hibernate.connection.password">iamtheking</property>
|
||||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||||
<property name="show_sql">true</property>
|
<property name="show_sql">true</property>
|
||||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
|
||||||
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
|
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
|
||||||
</session-factory>
|
</session-factory>
|
||||||
</hibernate-configuration>
|
</hibernate-configuration>
|
@ -1,17 +1,12 @@
|
|||||||
CREATE TABLE `user` (
|
CREATE TABLE `user` (
|
||||||
`user_id` int(10) NOT NULL AUTO_INCREMENT,
|
`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`)
|
PRIMARY KEY (`user_id`)
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ;
|
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ;
|
||||||
|
|
||||||
|
|
||||||
CREATE TABLE `user_order` (
|
CREATE TABLE `user_order` (
|
||||||
`ORDER_ID` int(10) NOT NULL AUTO_INCREMENT,
|
`ORDER_ID` int(10) NOT NULL AUTO_INCREMENT,
|
||||||
`ORDER_DATE` date DEFAULT NULL,
|
|
||||||
`USER_ID` int(10) NOT NULL DEFAULT '0',
|
`USER_ID` int(10) NOT NULL DEFAULT '0',
|
||||||
`ORDER_DESC` varchar(1024) DEFAULT NULL,
|
|
||||||
PRIMARY KEY (`ORDER_ID`,`USER_ID`),
|
PRIMARY KEY (`ORDER_ID`,`USER_ID`),
|
||||||
KEY `USER_ID` (`USER_ID`),
|
KEY `USER_ID` (`USER_ID`),
|
||||||
CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`)
|
CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`)
|
||||||
|
@ -1,21 +1,21 @@
|
|||||||
package com.baeldung.hibernate.fetching;
|
package com.baeldung.hibernate.fetching;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import com.baeldung.hibernate.fetching.model.OrderDetail;
|
||||||
import java.util.Set;
|
import com.baeldung.hibernate.fetching.view.FetchingAppView;
|
||||||
|
|
||||||
import org.hibernate.Hibernate;
|
import org.hibernate.Hibernate;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
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 {
|
public class HibernateFetchingTest {
|
||||||
|
|
||||||
|
|
||||||
//this loads sample data in the database
|
//this loads sample data in the database
|
||||||
@Before
|
@Before
|
||||||
public void addFecthingTestData(){
|
public void addFecthingTestData(){
|
||||||
FetchingAppView fav = new FetchingAppView();
|
FetchingAppView fav = new FetchingAppView();
|
||||||
fav.createTestData();
|
fav.createTestData();
|
||||||
|
@ -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.connection.password">iamtheking</property>
|
||||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||||
<property name="show_sql">true</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>
|
</session-factory>
|
||||||
</hibernate-configuration>
|
</hibernate-configuration>
|
@ -11,7 +11,8 @@
|
|||||||
<property name="hibernate.connection.password">iamtheking</property>
|
<property name="hibernate.connection.password">iamtheking</property>
|
||||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||||
<property name="show_sql">true</property>
|
<property name="show_sql">true</property>
|
||||||
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
|
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
|
||||||
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
|
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
|
||||||
|
|
||||||
</session-factory>
|
</session-factory>
|
||||||
</hibernate-configuration>
|
</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>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<!-- <dependency> -->
|
||||||
<groupId>org.hamcrest</groupId>
|
<!-- <groupId>org.hamcrest</groupId> -->
|
||||||
<artifactId>hamcrest-core</artifactId>
|
<!-- <artifactId>hamcrest-core</artifactId> -->
|
||||||
<scope>test</scope>
|
<!-- <scope>test</scope> -->
|
||||||
</dependency>
|
<!-- </dependency> -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hamcrest</groupId>
|
<groupId>org.hamcrest</groupId>
|
||||||
<artifactId>hamcrest-library</artifactId>
|
<artifactId>hamcrest-library</artifactId>
|
||||||
|
@ -16,29 +16,29 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
|||||||
@EnableWebMvc
|
@EnableWebMvc
|
||||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
public WebConfig() {
|
public WebConfig() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ViewResolver viewResolver() {
|
public ViewResolver viewResolver() {
|
||||||
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
|
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
|
||||||
viewResolver.setPrefix("/WEB-INF/view/");
|
viewResolver.setPrefix("/WEB-INF/view/");
|
||||||
viewResolver.setSuffix(".jsp");
|
viewResolver.setSuffix(".jsp");
|
||||||
return viewResolver;
|
return viewResolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
// API
|
||||||
@Override
|
@Override
|
||||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||||
super.addViewControllers(registry);
|
super.addViewControllers(registry);
|
||||||
registry.addViewController("/graph.html");
|
registry.addViewController("/graph.html");
|
||||||
registry.addViewController("/csrfHome.html");
|
registry.addViewController("/csrfHome.html");
|
||||||
registry.addViewController("/homepage.html");
|
registry.addViewController("/homepage.html");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addInterceptors(final InterceptorRegistry registry) {
|
public void addInterceptors(final InterceptorRegistry registry) {
|
||||||
registry.addInterceptor(new LoggerInterceptor());
|
registry.addInterceptor(new LoggerInterceptor());
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -14,20 +14,20 @@ import org.springframework.web.bind.annotation.ResponseStatus;
|
|||||||
@Controller
|
@Controller
|
||||||
@RequestMapping(value = "/auth/")
|
@RequestMapping(value = "/auth/")
|
||||||
public class BankController {
|
public class BankController {
|
||||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||||
|
|
||||||
@RequestMapping(value = "/transfer", method = RequestMethod.GET)
|
@RequestMapping(value = "/transfer", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
||||||
logger.info("Transfer to {}", accountNo);
|
logger.info("Transfer to {}", accountNo);
|
||||||
return amount;
|
return amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
// write - just for test
|
// write - just for test
|
||||||
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
|
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
|
||||||
@ResponseStatus(HttpStatus.OK)
|
@ResponseStatus(HttpStatus.OK)
|
||||||
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
||||||
logger.info("Transfer to {}", accountNo);
|
logger.info("Transfer to {}", accountNo);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -32,90 +32,90 @@ import com.google.common.base.Preconditions;
|
|||||||
@RequestMapping(value = "/auth/foos")
|
@RequestMapping(value = "/auth/foos")
|
||||||
public class FooController {
|
public class FooController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ApplicationEventPublisher eventPublisher;
|
private ApplicationEventPublisher eventPublisher;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IFooService service;
|
private IFooService service;
|
||||||
|
|
||||||
public FooController() {
|
public FooController() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
// API
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/count")
|
@RequestMapping(method = RequestMethod.GET, value = "/count")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
@ResponseStatus(value = HttpStatus.OK)
|
@ResponseStatus(value = HttpStatus.OK)
|
||||||
public long count() {
|
public long count() {
|
||||||
return 2l;
|
return 2l;
|
||||||
}
|
}
|
||||||
|
|
||||||
// read - one
|
// read - one
|
||||||
|
|
||||||
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
|
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
|
||||||
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
|
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
|
||||||
|
|
||||||
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
|
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
|
||||||
return resourceById;
|
return resourceById;
|
||||||
}
|
}
|
||||||
|
|
||||||
// read - all
|
// read - all
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET)
|
@RequestMapping(method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<Foo> findAll() {
|
public List<Foo> findAll() {
|
||||||
return service.findAll();
|
return service.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
|
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
|
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
|
||||||
final Page<Foo> resultPage = service.findPaginated(page, size);
|
final Page<Foo> resultPage = service.findPaginated(page, size);
|
||||||
if (page > resultPage.getTotalPages()) {
|
if (page > resultPage.getTotalPages()) {
|
||||||
throw new MyResourceNotFoundException();
|
throw new MyResourceNotFoundException();
|
||||||
}
|
}
|
||||||
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
|
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
|
||||||
|
|
||||||
return resultPage.getContent();
|
return resultPage.getContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
// write
|
// write
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.POST)
|
@RequestMapping(method = RequestMethod.POST)
|
||||||
@ResponseStatus(HttpStatus.CREATED)
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
|
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
|
||||||
Preconditions.checkNotNull(resource);
|
Preconditions.checkNotNull(resource);
|
||||||
final Foo foo = service.create(resource);
|
final Foo foo = service.create(resource);
|
||||||
final Long idOfCreatedResource = foo.getId();
|
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)
|
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
|
||||||
@ResponseStatus(HttpStatus.OK)
|
@ResponseStatus(HttpStatus.OK)
|
||||||
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
|
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
|
||||||
Preconditions.checkNotNull(resource);
|
Preconditions.checkNotNull(resource);
|
||||||
RestPreconditions.checkFound(service.findOne(resource.getId()));
|
RestPreconditions.checkFound(service.findOne(resource.getId()));
|
||||||
service.update(resource);
|
service.update(resource);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
|
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
|
||||||
@ResponseStatus(HttpStatus.OK)
|
@ResponseStatus(HttpStatus.OK)
|
||||||
public void delete(@PathVariable("id") final Long id) {
|
public void delete(@PathVariable("id") final Long id) {
|
||||||
service.deleteById(id);
|
service.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.HEAD)
|
@RequestMapping(method = RequestMethod.HEAD)
|
||||||
@ResponseStatus(HttpStatus.OK)
|
@ResponseStatus(HttpStatus.OK)
|
||||||
public void head(final HttpServletResponse resp) {
|
public void head(final HttpServletResponse resp) {
|
||||||
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
resp.setHeader("bar", "baz");
|
resp.setHeader("bar", "baz");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
|||||||
@RequestMapping(value = "/")
|
@RequestMapping(value = "/")
|
||||||
public class HomeController {
|
public class HomeController {
|
||||||
|
|
||||||
public String index() {
|
public String index() {
|
||||||
return "homepage";
|
return "homepage";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -23,63 +23,63 @@ import org.springframework.web.util.UriTemplate;
|
|||||||
@RequestMapping(value = "/auth/")
|
@RequestMapping(value = "/auth/")
|
||||||
public class RootController {
|
public class RootController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IMetricService metricService;
|
private IMetricService metricService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IActuatorMetricService actMetricService;
|
private IActuatorMetricService actMetricService;
|
||||||
|
|
||||||
public RootController() {
|
public RootController() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
// API
|
||||||
|
|
||||||
// discover
|
// discover
|
||||||
|
|
||||||
@RequestMapping(value = "admin", method = RequestMethod.GET)
|
@RequestMapping(value = "admin", method = RequestMethod.GET)
|
||||||
@ResponseStatus(value = HttpStatus.NO_CONTENT)
|
@ResponseStatus(value = HttpStatus.NO_CONTENT)
|
||||||
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
|
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
|
||||||
final String rootUri = request.getRequestURL().toString();
|
final String rootUri = request.getRequestURL().toString();
|
||||||
|
|
||||||
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
|
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
|
||||||
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
|
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
|
||||||
response.addHeader("Link", linkToFoo);
|
response.addHeader("Link", linkToFoo);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/metric", method = RequestMethod.GET)
|
@RequestMapping(value = "/metric", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Map getMetric() {
|
public Map getMetric() {
|
||||||
return metricService.getFullMetric();
|
return metricService.getFullMetric();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||||
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
|
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Map getStatusMetric() {
|
public Map getStatusMetric() {
|
||||||
return metricService.getStatusMetric();
|
return metricService.getStatusMetric();
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
|
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Object[][] drawMetric() {
|
public Object[][] drawMetric() {
|
||||||
final Object[][] result = metricService.getGraphData();
|
final Object[][] result = metricService.getGraphData();
|
||||||
for (int i = 1; i < result[0].length; i++) {
|
for (int i = 1; i < result[0].length; i++) {
|
||||||
result[0][i] = result[0][i].toString();
|
result[0][i] = result[0][i].toString();
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
|
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public String sampleAdminPage() {
|
public String sampleAdminPage() {
|
||||||
return "Hello";
|
return "Hello";
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
|
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public String sampleErrorPage() {
|
public String sampleErrorPage() {
|
||||||
return "Error Occurred";
|
return "Error Occurred";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -40,94 +40,94 @@ import cz.jirutka.rsql.parser.ast.Node;
|
|||||||
@RequestMapping(value = "/auth/")
|
@RequestMapping(value = "/auth/")
|
||||||
public class UserController {
|
public class UserController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IUserDAO service;
|
private IUserDAO service;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserRepository dao;
|
private UserRepository dao;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private MyUserRepository myUserRepository;
|
private MyUserRepository myUserRepository;
|
||||||
|
|
||||||
public UserController() {
|
public UserController() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
// API - READ
|
// API - READ
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/users")
|
@RequestMapping(method = RequestMethod.GET, value = "/users")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
|
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
|
||||||
final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
|
final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
|
||||||
if (search != null) {
|
if (search != null) {
|
||||||
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
||||||
final Matcher matcher = pattern.matcher(search + ",");
|
final Matcher matcher = pattern.matcher(search + ",");
|
||||||
while (matcher.find()) {
|
while (matcher.find()) {
|
||||||
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
|
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return service.searchUser(params);
|
return service.searchUser(params);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/users/spec")
|
@RequestMapping(method = RequestMethod.GET, value = "/users/spec")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
|
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
|
||||||
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
|
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
|
||||||
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
|
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
|
||||||
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
|
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
|
||||||
final Matcher matcher = pattern.matcher(search + ",");
|
final Matcher matcher = pattern.matcher(search + ",");
|
||||||
while (matcher.find()) {
|
while (matcher.find()) {
|
||||||
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
|
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
|
||||||
}
|
}
|
||||||
|
|
||||||
final Specification<User> spec = builder.build();
|
final Specification<User> spec = builder.build();
|
||||||
return dao.findAll(spec);
|
return dao.findAll(spec);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
|
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
|
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
|
||||||
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
|
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
|
||||||
if (search != null) {
|
if (search != null) {
|
||||||
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
||||||
final Matcher matcher = pattern.matcher(search + ",");
|
final Matcher matcher = pattern.matcher(search + ",");
|
||||||
while (matcher.find()) {
|
while (matcher.find()) {
|
||||||
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
|
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
final BooleanExpression exp = builder.build();
|
final BooleanExpression exp = builder.build();
|
||||||
return myUserRepository.findAll(exp);
|
return myUserRepository.findAll(exp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
|
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
|
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
|
||||||
final Node rootNode = new RSQLParser().parse(search);
|
final Node rootNode = new RSQLParser().parse(search);
|
||||||
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
|
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
|
||||||
return dao.findAll(spec);
|
return dao.findAll(spec);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
|
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
|
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
|
||||||
return myUserRepository.findAll(predicate);
|
return myUserRepository.findAll(predicate);
|
||||||
}
|
}
|
||||||
|
|
||||||
// API - WRITE
|
// API - WRITE
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.POST, value = "/users")
|
@RequestMapping(method = RequestMethod.POST, value = "/users")
|
||||||
@ResponseStatus(HttpStatus.CREATED)
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
public void create(@RequestBody final User resource) {
|
public void create(@RequestBody final User resource) {
|
||||||
Preconditions.checkNotNull(resource);
|
Preconditions.checkNotNull(resource);
|
||||||
dao.save(resource);
|
dao.save(resource);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
|
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
|
||||||
@ResponseStatus(HttpStatus.CREATED)
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
public void addMyUser(@RequestBody final MyUser resource) {
|
public void addMyUser(@RequestBody final MyUser resource) {
|
||||||
Preconditions.checkNotNull(resource);
|
Preconditions.checkNotNull(resource);
|
||||||
myUserRepository.save(resource);
|
myUserRepository.save(resource);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -27,8 +27,7 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter {
|
|||||||
* Executed before after handler is executed
|
* Executed before after handler is executed
|
||||||
**/
|
**/
|
||||||
@Override
|
@Override
|
||||||
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
|
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
|
||||||
final ModelAndView modelAndView) throws Exception {
|
|
||||||
log.info("[postHandle][" + request + "]");
|
log.info("[postHandle][" + request + "]");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,8 +35,7 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter {
|
|||||||
* Executed after complete request is finished
|
* Executed after complete request is finished
|
||||||
**/
|
**/
|
||||||
@Override
|
@Override
|
||||||
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
|
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
|
||||||
throws Exception {
|
|
||||||
if (ex != null)
|
if (ex != null)
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
log.info("[afterCompletion][" + request + "][exception: " + ex + "]");
|
log.info("[afterCompletion][" + request + "][exception: " + ex + "]");
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package org.baeldung.security;
|
package org.baeldung.security;
|
||||||
|
|
||||||
|
|
||||||
import org.baeldung.security.csrf.CsrfDisabledIntegrationTest;
|
import org.baeldung.security.csrf.CsrfDisabledIntegrationTest;
|
||||||
import org.baeldung.security.csrf.CsrfEnabledIntegrationTest;
|
import org.baeldung.security.csrf.CsrfEnabledIntegrationTest;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
|
@ -23,30 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
public class CsrfAbstractIntegrationTest {
|
public class CsrfAbstractIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private WebApplicationContext context;
|
private WebApplicationContext context;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Filter springSecurityFilterChain;
|
private Filter springSecurityFilterChain;
|
||||||
|
|
||||||
protected MockMvc mvc;
|
protected MockMvc mvc;
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
|
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected RequestPostProcessor testUser() {
|
protected RequestPostProcessor testUser() {
|
||||||
return user("user").password("userPass").roles("USER");
|
return user("user").password("userPass").roles("USER");
|
||||||
}
|
}
|
||||||
|
|
||||||
protected RequestPostProcessor testAdmin() {
|
protected RequestPostProcessor testAdmin() {
|
||||||
return user("admin").password("adminPass").roles("USER", "ADMIN");
|
return user("admin").password("adminPass").roles("USER", "ADMIN");
|
||||||
}
|
}
|
||||||
|
|
||||||
protected String createFoo() throws JsonProcessingException {
|
protected String createFoo() throws JsonProcessingException {
|
||||||
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
|
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,33 +14,31 @@ import org.springframework.test.context.ContextConfiguration;
|
|||||||
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
||||||
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
|
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
|
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
|
||||||
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
|
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
|
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
|
||||||
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
|
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void accessMainPageWithoutAuthorization() throws Exception {
|
public void accessMainPageWithoutAuthorization() throws Exception {
|
||||||
mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
|
mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void accessOtherPages() throws Exception {
|
public void accessOtherPages() throws Exception {
|
||||||
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100"))
|
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100")).andExpect(status().isUnauthorized()); // without authorization
|
||||||
.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").with(testUser()))
|
}
|
||||||
.andExpect(status().isOk()); // with authorization
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void accessAdminPage() throws Exception {
|
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)).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).with(testAdmin())).andExpect(status().isOk()); // with authorization
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -25,27 +25,27 @@ import org.springframework.web.context.WebApplicationContext;
|
|||||||
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
||||||
public class LoggerInterceptorTest {
|
public class LoggerInterceptorTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
WebApplicationContext wac;
|
WebApplicationContext wac;
|
||||||
@Autowired
|
@Autowired
|
||||||
MockHttpSession session;
|
MockHttpSession session;
|
||||||
|
|
||||||
private MockMvc mockMvc;
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* After execution of HTTP GET logs from interceptor will be displayed in
|
* After execution of HTTP GET logs from interceptor will be displayed in
|
||||||
* the console
|
* the console
|
||||||
*
|
*
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void testInterceptors() throws Exception {
|
public void testInterceptors() throws Exception {
|
||||||
mockMvc.perform(get("/graph.html")).andExpect(status().isOk());
|
mockMvc.perform(get("/graph.html")).andExpect(status().isOk());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
package com.baeldung.spring.security.x509;
|
package com.baeldung.spring.security.x509;
|
||||||
|
|
||||||
|
import java.security.Principal;
|
||||||
|
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
@ -7,8 +9,6 @@ import org.springframework.stereotype.Controller;
|
|||||||
import org.springframework.ui.Model;
|
import org.springframework.ui.Model;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
import java.security.Principal;
|
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
public class UserController {
|
public class UserController {
|
||||||
@PreAuthorize("hasAuthority('ROLE_USER')")
|
@PreAuthorize("hasAuthority('ROLE_USER')")
|
||||||
|
@ -2,21 +2,15 @@ package com.baeldung.spring.security.x509;
|
|||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
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.EnableWebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
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
|
@SpringBootApplication
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {
|
public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(X509AuthenticationServer.class, args);
|
SpringApplication.run(X509AuthenticationServer.class, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
package com.baeldung.spring.security.x509;
|
package com.baeldung.spring.security.x509;
|
||||||
|
|
||||||
|
import java.security.Principal;
|
||||||
|
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
@ -7,8 +9,6 @@ import org.springframework.stereotype.Controller;
|
|||||||
import org.springframework.ui.Model;
|
import org.springframework.ui.Model;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
import java.security.Principal;
|
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
public class UserController {
|
public class UserController {
|
||||||
@PreAuthorize("hasAuthority('ROLE_USER')")
|
@PreAuthorize("hasAuthority('ROLE_USER')")
|
||||||
|
@ -23,9 +23,7 @@ public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http.authorizeRequests().anyRequest().authenticated()
|
http.authorizeRequests().anyRequest().authenticated().and().x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService());
|
||||||
.and()
|
|
||||||
.x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
Loading…
x
Reference in New Issue
Block a user