Merge remote-tracking branch 'upstream/master' into craedel-spring-cloud-hystrix

This commit is contained in:
Christian Raedel 2016-08-22 23:45:39 +02:00
commit 33fc42103a
59 changed files with 1217 additions and 979 deletions

View 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");
}
}

View File

@ -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()));
}
}

View File

@ -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);
}
}

View File

@ -1,2 +0,0 @@
line 1
a second line

View File

@ -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
View File

@ -0,0 +1,12 @@
*.class
#folders#
/target
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
*.iml

View File

@ -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>

View File

@ -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;
}
}

View File

@ -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
View 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>

View File

@ -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>

View 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;
}
}

View File

@ -4,8 +4,8 @@ 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;
@ -23,20 +23,20 @@ public class EmployeeDTO {
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;
} }
} }

View File

@ -1,10 +1,13 @@
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;
@ -30,4 +33,12 @@ public class Employee {
this.division = division; this.division = division;
} }
public Date getStartDt() {
return startDt;
}
public void setStartDt(Date startDt) {
this.startDt = startDt;
}
} }

View File

@ -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"),
@Mapping(target="divisionName",source="entity.division.name"),
@Mapping(target="employeeId",source="entity.id"),
@Mapping(target="employeeName",source="entity.name")
})
EmployeeDTO employeeToEmployeeDTO(Employee entity); EmployeeDTO employeeToEmployeeDTO(Employee entity);
@Mappings({ @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="id",source="dto.employeeId"),
@Mapping(target="name",source="dto.employeeName"),
@Mapping(target="division",expression="java(new org.baeldung.entity.Division(dto.getDivisionId(),dto.getDivisionName()))")
})
Employee employeeDTOtoEmployee(EmployeeDTO dto); Employee employeeDTOtoEmployee(EmployeeDTO dto);
DivisionDTO divisionToDivisionDTO(Division entity);
Division divisionDTOtoDivision(DivisionDTO dto);
List<Employee> convertEmployeeDTOListToEmployeeList(List<EmployeeDTO> list);
List<EmployeeDTO> convertEmployeeListToEmployeeDTOList(List<Employee> list);
} }

View File

@ -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);
} }

View File

@ -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);
}

View 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>

View File

@ -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;
@ -10,39 +17,107 @@ import org.mapstruct.factory.Mappers;
public class EmployeeMapperTest { public class EmployeeMapperTest {
@Test
public void givenEmployeeDTOtoEmployee_whenMaps_thenCorrect(){
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class); EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
private static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss";
@Test
public void givenEmployeeDTOwithDiffNametoEmployee_whenMaps_thenCorrect() {
EmployeeDTO dto = new EmployeeDTO(); EmployeeDTO dto = new EmployeeDTO();
dto.setDivisionId(1);
dto.setDivisionName("IT Division");
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.getDivisionName(), entity.getDivision().getName());
assertEquals(dto.getEmployeeId(), entity.getId()); assertEquals(dto.getEmployeeId(), entity.getId());
assertEquals(dto.getEmployeeName(), entity.getName()); assertEquals(dto.getEmployeeName(), entity.getName());
} }
@Test @Test
public void givenEmployeetoEmployeeDTO_whenMaps_thenCorrect(){ public void givenEmployeewithDiffNametoEmployeeDTO_whenMaps_thenCorrect() {
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
Employee entity = new Employee(); Employee entity = new Employee();
entity.setDivision(new Division(1,"IT Division"));
entity.setId(1); entity.setId(1);
entity.setName("John"); entity.setName("John");
EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity);
assertEquals(dto.getDivisionId(), entity.getDivision().getId());
assertEquals(dto.getDivisionName(), entity.getDivision().getName());
assertEquals(dto.getEmployeeId(), entity.getId()); assertEquals(dto.getEmployeeId(), entity.getId());
assertEquals(dto.getEmployeeName(), entity.getName()); assertEquals(dto.getEmployeeName(), entity.getName());
} }
@Test
public void givenEmployeeDTOwithNestedMappingToEmployee_whenMaps_thenCorrect() {
EmployeeDTO dto = new EmployeeDTO();
dto.setDivision(new DivisionDTO(1, "Division1"));
Employee entity = mapper.employeeDTOtoEmployee(dto);
assertEquals(dto.getDivision().getId(), entity.getDivision().getId());
assertEquals(dto.getDivision().getName(), entity.getDivision().getName());
}
@Test
public void givenEmployeeWithNestedMappingToEmployeeDTO_whenMaps_thenCorrect() {
Employee entity = new Employee();
entity.setDivision(new Division(1, "Division1"));
EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity);
assertEquals(dto.getDivision().getId(), entity.getDivision().getId());
assertEquals(dto.getDivision().getName(), entity.getDivision().getName());
}
@Test
public void givenEmployeeListToEmployeeDTOList_whenMaps_thenCorrect() {
List<Employee> employeeList = new ArrayList<>();
Employee emp = new Employee();
emp.setId(1);
emp.setName("EmpName");
emp.setDivision(new Division(1, "Division1"));
employeeList.add(emp);
List<EmployeeDTO> employeeDtoList = mapper.convertEmployeeListToEmployeeDTOList(employeeList);
EmployeeDTO employeeDTO = employeeDtoList.get(0);
assertEquals(employeeDTO.getEmployeeId(), emp.getId());
assertEquals(employeeDTO.getEmployeeName(), emp.getName());
assertEquals(employeeDTO.getDivision().getId(), emp.getDivision().getId());
assertEquals(employeeDTO.getDivision().getName(), emp.getDivision().getName());
}
@Test
public void givenEmployeeDTOListToEmployeeList_whenMaps_thenCorrect() {
List<EmployeeDTO> employeeDTOList = new ArrayList<>();
EmployeeDTO empDTO = new EmployeeDTO();
empDTO.setEmployeeId(1);
empDTO.setEmployeeName("EmpName");
empDTO.setDivision(new DivisionDTO(1, "Division1"));
employeeDTOList.add(empDTO);
List<Employee> employeeList = mapper.convertEmployeeDTOListToEmployeeList(employeeDTOList);
Employee employee = employeeList.get(0);
assertEquals(employee.getId(), empDTO.getEmployeeId());
assertEquals(employee.getName(), empDTO.getEmployeeName());
assertEquals(employee.getDivision().getId(), empDTO.getDivision().getId());
assertEquals(employee.getDivision().getName(), empDTO.getDivision().getName());
}
@Test
public void givenEmployeeWithStartDateMappingToEmployeeDTO_whenMaps_thenCorrect() throws ParseException {
Employee entity = new Employee();
entity.setStartDt(new Date());
EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity);
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString());
}
@Test
public void givenEmployeeDTOWithStartDateMappingToEmployee_whenMaps_thenCorrect() throws ParseException {
EmployeeDTO dto = new EmployeeDTO();
dto.setEmployeeStartDt("01-04-2016 01:00:00");
Employee entity = mapper.employeeDTOtoEmployee(dto);
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString());
}
} }

View File

@ -1,25 +1,29 @@
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 {
@Autowired
SimpleSourceDestinationMapper simpleSourceDestinationMapper;
@Test @Test
public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() { public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() {
SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers
.getMapper(SimpleSourceDestinationMapper.class);
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());
@ -27,15 +31,11 @@ public class SimpleSourceDestinationMapperTest {
@Test @Test
public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() { public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() {
SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers
.getMapper(SimpleSourceDestinationMapper.class);
SimpleDestination destination = new SimpleDestination(); SimpleDestination destination = new SimpleDestination();
destination.setName("DestinationName"); destination.setName("DestinationName");
destination.setDescription("DestinationDescription"); destination.setDescription("DestinationDescription");
SimpleSource source = SimpleSource source = simpleSourceDestinationMapper.destinationToSource(destination);
simpleSourceDestinationMapper.destinationToSource(destination);
assertEquals(destination.getName(), source.getName()); assertEquals(destination.getName(), source.getName());
assertEquals(destination.getDescription(), source.getDescription()); assertEquals(destination.getDescription(), source.getDescription());

View File

@ -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++;
}
}

View File

@ -124,9 +124,6 @@
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration>
<verbose>true</verbose>
</configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

@ -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;
} }
} }

View File

@ -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;
}
}

View File

@ -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;
@Id
@GeneratedValue
@Column(name="ORDER_ID")
private Long orderId; private Long orderId;
private Date orderDate;
private String orderDesc;
private User user;
public OrderDetail(){ 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;
} }

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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() {

View File

@ -1,20 +1,14 @@
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 {
@ -25,12 +19,10 @@ public class FetchingAppView {
// lazily loaded // lazily loaded
public Set<OrderDetail> lazyLoaded() { public Set<OrderDetail> lazyLoaded() {
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
List<User> users = sessionLazy.createQuery("From User").list(); List<UserLazy> users = sessionLazy.createQuery("From UserLazy").list();
User userLazyLoaded = new User(); UserLazy userLazyLoaded = users.get(3);
userLazyLoaded = users.get(3);
// since data is lazyloaded so data won't be initialized // since data is lazyloaded so data won't be initialized
Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail(); return (userLazyLoaded.getOrderDetail());
return (orderDetailSet);
} }
// eagerly loaded // eagerly loaded
@ -38,38 +30,23 @@ public class FetchingAppView {
final Session sessionEager = HibernateUtil.getHibernateSession(); final Session sessionEager = HibernateUtil.getHibernateSession();
// data should be loaded in the following line // data should be loaded in the following line
// also note the queries generated // also note the queries generated
List<User> users =sessionEager.createQuery("From User").list(); List<UserEager> user = sessionEager.createQuery("From UserEager").list();
User userEagerLoaded = new User(); UserEager userEagerLoaded = user.get(3);
userEagerLoaded = users.get(3); return userEagerLoaded.getOrderDetail();
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
return orderDetailSet;
} }
// creates test data // creates test data
// call this method to create the data in the database // call this method to create the data in the database
public void createTestData() { public void createTestData() {
final Session session = HibernateUtil.getHibernateSession(); final Session session = HibernateUtil.getHibernateSession("lazy");
Transaction tx = null; Transaction tx = session.beginTransaction();
tx = session.beginTransaction(); final UserLazy user1 = new UserLazy();
final User user1 = new User(); final UserLazy user2 = new UserLazy();
final User user2 = new User(); final UserLazy user3 = new UserLazy();
final User user3 = new User();
user1.setFirstName("Priyam");
user1.setLastName("Banerjee");
user1.setUserName("priyambanerjee");
session.save(user1); session.save(user1);
user2.setFirstName("Navneeta");
user2.setLastName("Mukherjee");
user2.setUserName("nmukh");
session.save(user2); session.save(user2);
user3.setFirstName("Molly");
user3.setLastName("Banerjee");
user3.setUserName("mollyb");
session.save(user3); session.save(user3);
final OrderDetail order1 = new OrderDetail(); final OrderDetail order1 = new OrderDetail();
@ -78,26 +55,6 @@ public class FetchingAppView {
final OrderDetail order4 = new OrderDetail(); final OrderDetail order4 = new OrderDetail();
final OrderDetail order5 = new OrderDetail(); final OrderDetail order5 = new OrderDetail();
order1.setOrderDesc("First Order");
order1.setOrderDate(new Date(2014, 10, 12));
order1.setUser(user1);
order2.setOrderDesc("Second Order");
order2.setOrderDate(new Date(2016, 10, 25));
order2.setUser(user1);
order3.setOrderDesc("Third Order");
order3.setOrderDate(new Date(2015, 2, 17));
order3.setUser(user2);
order4.setOrderDesc("Fourth Order");
order4.setOrderDate(new Date(2014, 10, 1));
order4.setUser(user2);
order5.setOrderDesc("Fifth Order");
order5.setOrderDate(new Date(2014, 9, 11));
order5.setUser(user3);
session.saveOrUpdate(order1); session.saveOrUpdate(order1);
session.saveOrUpdate(order2); session.saveOrUpdate(order2);
session.saveOrUpdate(order3); session.saveOrUpdate(order3);

View File

@ -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>

View File

@ -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>

View File

@ -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`)

View File

@ -1,15 +1,15 @@
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 {

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -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());
}
}

View File

@ -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>

View File

@ -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 + "]");

View File

@ -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;

View File

@ -31,10 +31,8 @@ public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
@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

View File

@ -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')")

View File

@ -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);
} }
} }

View File

@ -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')")

View File

@ -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