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.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
@ -191,6 +192,16 @@ public class JavaInputStreamToXUnitTest {
IOUtils.closeQuietly(outStream);
}
@Test
public final void givenUsingPlainJava8_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final File targetFile = new File("src/main/resources/targetFile.tmp");
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
IOUtils.closeQuietly(initialStream);
}
@Test
public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));

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>
<version>${hystrix-metrics-event-stream.version}</version>
</dependency>
<dependency>
<!--<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-dashboard</artifactId>
<version>${hystrix-dashboard.version}</version>
</dependency>
</dependency>-->
<dependency>
<groupId>com.netflix.rxjava</groupId>
<artifactId>rxjava-core</artifactId>

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.HystrixThreadPoolProperties;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.runners.MethodSorters;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@FixMethodOrder(MethodSorters.JVM)
public class HystrixTimeoutTest {
private HystrixCommand.Setter config;
private HystrixCommandProperties.Setter commandProperties;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
commandProperties = HystrixCommandProperties.Setter();
config = HystrixCommand
.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1"));
}
@Test
public void givenInputBobAndDefaultSettings_whenExecuted_thenReturnHelloBob(){
public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob(){
assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!"));
}
@Test
public void givenSvcTimeoutOf100AndDefaultSettings_whenExecuted_thenReturnSuccess()
public void givenSvcTimeoutOf100AndDefaultSettings_whenRemoteSvcExecuted_thenReturnSuccess()
throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand
.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1"));
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2"));
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(),
equalTo("Success"));
}
@Test
public void givenSvcTimeoutOf10000AndDefaultSettings__whenExecuted_thenExpectHRE() throws InterruptedException {
exception.expect(HystrixRuntimeException.class);
@Test(expected = HystrixRuntimeException.class)
public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand
.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3"));
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute();
}
@Test
public void givenSvcTimeoutOf5000AndExecTimeoutOf10000__whenExecuted_thenReturnSuccess()
public void givenSvcTimeoutOf5000AndExecTimeoutOf10000_whenRemoteSvcExecuted_thenReturnSuccess()
throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand
.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4"));
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
config.andCommandPropertiesDefaults(commandProperties);
@ -63,10 +51,13 @@ public class HystrixTimeoutTest {
equalTo("Success"));
}
@Test
@Test(expected = HystrixRuntimeException.class)
public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE()
throws InterruptedException {
exception.expect(HystrixRuntimeException.class);
HystrixCommand.Setter config = HystrixCommand
.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5"));
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
commandProperties.withExecutionTimeoutInMilliseconds(5_000);
config.andCommandPropertiesDefaults(commandProperties);
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(15_000)).execute();
@ -75,6 +66,11 @@ public class HystrixTimeoutTest {
@Test
public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess()
throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand
.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool"));
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
config.andCommandPropertiesDefaults(commandProperties);
config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
@ -85,4 +81,52 @@ public class HystrixTimeoutTest {
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success"));
}
@Test
public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess()
throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand
.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker"));
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
commandProperties.withExecutionTimeoutInMilliseconds(1000);
commandProperties.withCircuitBreakerSleepWindowInMilliseconds(4000);
commandProperties.withExecutionIsolationStrategy(
HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
commandProperties.withCircuitBreakerEnabled(true);
commandProperties.withCircuitBreakerRequestVolumeThreshold(1);
config.andCommandPropertiesDefaults(commandProperties);
config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withMaxQueueSize(1)
.withCoreSize(1)
.withQueueSizeRejectionThreshold(1));
assertThat(this.invokeRemoteService(config, 10_000), equalTo(null));
assertThat(this.invokeRemoteService(config, 10_000), equalTo(null));
assertThat(this.invokeRemoteService(config, 10_000), equalTo(null));
Thread.sleep(5000);
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success"));
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success"));
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success"));
}
public String invokeRemoteService(HystrixCommand.Setter config, int timeout)
throws InterruptedException {
String response = null;
try {
response = new RemoteServiceTestCommand(config,
new RemoteServiceTestSimulator(timeout)).execute();
} catch (HystrixRuntimeException ex) {
System.out.println("ex = " + ex);
}
return response;
}
}

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>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.2.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>mapstruct</finalName>

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

@ -2,41 +2,41 @@ package org.baeldung.dto;
public class EmployeeDTO {
private int employeeId;
private String employeeName;
private int divisionId;
private String divisionName;
private int employeeId;
private String employeeName;
private DivisionDTO division;
private String employeeStartDt;
public int getEmployeeId() {
return employeeId;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getDivisionId() {
return divisionId;
}
public DivisionDTO getDivision() {
return division;
}
public void setDivisionId(int divisionId) {
this.divisionId = divisionId;
}
public void setDivision(DivisionDTO division) {
this.division = division;
}
public String getDivisionName() {
return divisionName;
}
public String getEmployeeStartDt() {
return employeeStartDt;
}
public void setDivisionName(String divisionName) {
this.divisionName = divisionName;
}
public void setEmployeeStartDt(String employeeStartDt) {
this.employeeStartDt = employeeStartDt;
}
}

View File

@ -2,23 +2,23 @@ package org.baeldung.dto;
public class SimpleSource {
private String name;
private String description;
public String getName() {
return name;
}
private String name;
private String description;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -2,32 +2,32 @@ package org.baeldung.entity;
public class Division {
public Division() {
}
public Division() {
}
public Division(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Division(int id, String name) {
super();
this.id = id;
this.name = name;
}
private int id;
private String name;
private int id;
private String name;
public int getId() {
return id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,33 +1,44 @@
package org.baeldung.entity;
import java.util.Date;
public class Employee {
private int id;
private String name;
private Division division;
private int id;
private String name;
private Division division;
private Date startDt;
public int getId() {
return id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public Division getDivision() {
return division;
}
public Division getDivision() {
return division;
}
public void setDivision(Division division) {
this.division = division;
}
public void setDivision(Division division) {
this.division = division;
}
public Date getStartDt() {
return startDt;
}
public void setStartDt(Date startDt) {
this.startDt = startDt;
}
}

View File

@ -2,23 +2,23 @@ package org.baeldung.entity;
public class SimpleDestination {
private String name;
private String description;
public String getName() {
return name;
}
private String name;
private String description;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -1,6 +1,10 @@
package org.baeldung.mapper;
import java.util.List;
import org.baeldung.dto.DivisionDTO;
import org.baeldung.dto.EmployeeDTO;
import org.baeldung.entity.Division;
import org.baeldung.entity.Employee;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@ -9,19 +13,18 @@ import org.mapstruct.Mappings;
@Mapper
public interface EmployeeMapper {
@Mappings({
@Mapping(target="divisionId",source="entity.division.id"),
@Mapping(target="divisionName",source="entity.division.name"),
@Mapping(target="employeeId",source="entity.id"),
@Mapping(target="employeeName",source="entity.name")
})
EmployeeDTO employeeToEmployeeDTO(Employee entity);
@Mappings({
@Mapping(target="id",source="dto.employeeId"),
@Mapping(target="name",source="dto.employeeName"),
@Mapping(target="division",expression="java(new org.baeldung.entity.Division(dto.getDivisionId(),dto.getDivisionName()))")
})
Employee employeeDTOtoEmployee(EmployeeDTO dto);
@Mappings({ @Mapping(target = "employeeId", source = "entity.id"), @Mapping(target = "employeeName", source = "entity.name"), @Mapping(target = "employeeStartDt", source = "entity.startDt", dateFormat = "dd-MM-yyyy HH:mm:ss") })
EmployeeDTO employeeToEmployeeDTO(Employee entity);
@Mappings({ @Mapping(target = "id", source = "dto.employeeId"), @Mapping(target = "name", source = "dto.employeeName"), @Mapping(target = "startDt", source = "dto.employeeStartDt", dateFormat = "dd-MM-yyyy HH:mm:ss") })
Employee employeeDTOtoEmployee(EmployeeDTO dto);
DivisionDTO divisionToDivisionDTO(Division entity);
Division divisionDTOtoDivision(DivisionDTO dto);
List<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.mapstruct.Mapper;
@Mapper
@Mapper(componentModel = "spring")
public interface SimpleSourceDestinationMapper {
SimpleDestination sourceToDestination(SimpleSource source);
SimpleDestination sourceToDestination(SimpleSource source);
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;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.baeldung.dto.DivisionDTO;
import org.baeldung.dto.EmployeeDTO;
import org.baeldung.entity.Division;
import org.baeldung.entity.Employee;
@ -9,40 +16,108 @@ import org.junit.Test;
import org.mapstruct.factory.Mappers;
public class EmployeeMapperTest {
@Test
public void givenEmployeeDTOtoEmployee_whenMaps_thenCorrect(){
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
EmployeeDTO dto = new EmployeeDTO();
dto.setDivisionId(1);
dto.setDivisionName("IT Division");
dto.setEmployeeId(1);
dto.setEmployeeName("John");
Employee entity = mapper.employeeDTOtoEmployee(dto);
assertEquals(dto.getDivisionId(), entity.getDivision().getId());
assertEquals(dto.getDivisionName(), entity.getDivision().getName());
assertEquals(dto.getEmployeeId(),entity.getId());
assertEquals(dto.getEmployeeName(),entity.getName());
}
@Test
public void givenEmployeetoEmployeeDTO_whenMaps_thenCorrect(){
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
Employee entity = new Employee();
entity.setDivision(new Division(1,"IT Division"));
entity.setId(1);
entity.setName("John");
EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity);
assertEquals(dto.getDivisionId(), entity.getDivision().getId());
assertEquals(dto.getDivisionName(), entity.getDivision().getName());
assertEquals(dto.getEmployeeId(),entity.getId());
assertEquals(dto.getEmployeeName(),entity.getName());
}
EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class);
private static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss";
@Test
public void givenEmployeeDTOwithDiffNametoEmployee_whenMaps_thenCorrect() {
EmployeeDTO dto = new EmployeeDTO();
dto.setEmployeeId(1);
dto.setEmployeeName("John");
Employee entity = mapper.employeeDTOtoEmployee(dto);
assertEquals(dto.getEmployeeId(), entity.getId());
assertEquals(dto.getEmployeeName(), entity.getName());
}
@Test
public void givenEmployeewithDiffNametoEmployeeDTO_whenMaps_thenCorrect() {
Employee entity = new Employee();
entity.setId(1);
entity.setName("John");
EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity);
assertEquals(dto.getEmployeeId(), entity.getId());
assertEquals(dto.getEmployeeName(), entity.getName());
}
@Test
public void givenEmployeeDTOwithNestedMappingToEmployee_whenMaps_thenCorrect() {
EmployeeDTO dto = new EmployeeDTO();
dto.setDivision(new DivisionDTO(1, "Division1"));
Employee entity = mapper.employeeDTOtoEmployee(dto);
assertEquals(dto.getDivision().getId(), entity.getDivision().getId());
assertEquals(dto.getDivision().getName(), entity.getDivision().getName());
}
@Test
public void givenEmployeeWithNestedMappingToEmployeeDTO_whenMaps_thenCorrect() {
Employee entity = new Employee();
entity.setDivision(new Division(1, "Division1"));
EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity);
assertEquals(dto.getDivision().getId(), entity.getDivision().getId());
assertEquals(dto.getDivision().getName(), entity.getDivision().getName());
}
@Test
public void givenEmployeeListToEmployeeDTOList_whenMaps_thenCorrect() {
List<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,44 +1,44 @@
package org.baeldung.mapper;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import org.baeldung.dto.SimpleSource;
import org.baeldung.entity.SimpleDestination;
import org.junit.Test;
import org.mapstruct.factory.Mappers;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SimpleSourceDestinationMapperTest {
@Test
public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() {
SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers
.getMapper(SimpleSourceDestinationMapper.class);
SimpleSource simpleSource = new SimpleSource();
simpleSource.setName("SourceName");
simpleSource.setDescription("SourceDescription");
SimpleDestination destination =
simpleSourceDestinationMapper.sourceToDestination(simpleSource);
assertEquals(simpleSource.getName(), destination.getName());
assertEquals(simpleSource.getDescription(), destination.getDescription());
}
@Test
public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() {
SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers
.getMapper(SimpleSourceDestinationMapper.class);
SimpleDestination destination = new SimpleDestination();
destination.setName("DestinationName");
destination.setDescription("DestinationDescription");
SimpleSource source =
simpleSourceDestinationMapper.destinationToSource(destination);
assertEquals(destination.getName(), source.getName());
assertEquals(destination.getDescription(), source.getDescription());
}
@Autowired
SimpleSourceDestinationMapper simpleSourceDestinationMapper;
@Test
public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() {
SimpleSource simpleSource = new SimpleSource();
simpleSource.setName("SourceName");
simpleSource.setDescription("SourceDescription");
SimpleDestination destination = simpleSourceDestinationMapper.sourceToDestination(simpleSource);
assertEquals(simpleSource.getName(), destination.getName());
assertEquals(simpleSource.getDescription(), destination.getDescription());
}
@Test
public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() {
SimpleDestination destination = new SimpleDestination();
destination.setName("DestinationName");
destination.setDescription("DestinationDescription");
SimpleSource source = simpleSourceDestinationMapper.destinationToSource(destination);
assertEquals(destination.getName(), source.getName());
assertEquals(destination.getDescription(), source.getDescription());
}
}

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>
</execution>
</executions>
<configuration>
<verbose>true</verbose>
</configuration>
</plugin>
</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.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class CommitInfoController {
@ -17,7 +20,11 @@ public class CommitInfoController {
private String commitId;
@RequestMapping("/commitId")
public GitInfoDto getCommitId() {
return new GitInfoDto(commitMessage, branch, commitId);
public Map<String, String> getCommitId() {
Map<String, String> result = new HashMap<>();
result.put("Commit message",commitMessage);
result.put("Commit branch", branch);
result.put("Commit id", commitId);
return result;
}
}

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;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
@Entity
@Table (name = "USER_ORDER")
public class OrderDetail implements Serializable{
private static final long serialVersionUID = 1L;
private Long orderId;
private Date orderDate;
private String orderDesc;
private User user;
public OrderDetail(){
@Id
@GeneratedValue
@Column(name="ORDER_ID")
private Long orderId;
public OrderDetail(){
}
public OrderDetail(Date orderDate, String orderDesc) {
super();
this.orderDate = orderDate;
this.orderDesc = orderDesc;
super();
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getOrderDesc() {
return orderDesc;
}
public void setOrderDesc(String orderDesc) {
this.orderDesc = orderDesc;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public int hashCode() {
final int prime = 31;
@ -62,6 +46,7 @@ public class OrderDetail implements Serializable{
return true;
}
public Long getOrderId() {
return orderId;
}

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
//one with lazy loading enabled
//another lazy = false
SessionFactory sf = null;
SessionFactory sf;
if ("lazy".equals(fetchMethod)) {
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
} else {
@ -19,8 +19,7 @@ public class HibernateUtil {
}
// fetching.cfg.xml is used for this example
final Session session = sf.openSession();
return session;
return sf.openSession();
}
public static Session getHibernateSession() {

View File

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

View File

@ -11,7 +11,10 @@
<property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
<property name="hbm2ddl.auto">validate</property>
<mapping class="com.baeldung.hibernate.fetching.model.UserEager" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetailEager" />
</session-factory>
</hibernate-configuration>

View File

@ -11,7 +11,7 @@
<property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
</session-factory>
</hibernate-configuration>

View File

@ -1,17 +1,12 @@
CREATE TABLE `user` (
`user_id` int(10) NOT NULL AUTO_INCREMENT,
`USERNAME` varchar(100) DEFAULT NULL,
`FIRST_NAME` varchar(255) NOT NULL,
`LAST_NAME` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ;
CREATE TABLE `user_order` (
`ORDER_ID` int(10) NOT NULL AUTO_INCREMENT,
`ORDER_DATE` date DEFAULT NULL,
`USER_ID` int(10) NOT NULL DEFAULT '0',
`ORDER_DESC` varchar(1024) DEFAULT NULL,
PRIMARY KEY (`ORDER_ID`,`USER_ID`),
KEY `USER_ID` (`USER_ID`),
CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`)

View File

@ -1,21 +1,21 @@
package com.baeldung.hibernate.fetching;
import static org.junit.Assert.*;
import java.util.Set;
import com.baeldung.hibernate.fetching.model.OrderDetail;
import com.baeldung.hibernate.fetching.view.FetchingAppView;
import org.hibernate.Hibernate;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.fetching.model.OrderDetail;
import java.util.Set;
import com.baeldung.hibernate.fetching.view.FetchingAppView;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HibernateFetchingTest {
//this loads sample data in the database
@Before
@Before
public void addFecthingTestData(){
FetchingAppView fav = new FetchingAppView();
fav.createTestData();

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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
<mapping class="com.baeldung.hibernate.fetching.model.UserEager" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetailEager" />
</session-factory>
</hibernate-configuration>

View File

@ -11,7 +11,8 @@
<property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
</session-factory>
</hibernate-configuration>

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>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.hamcrest</groupId> -->
<!-- <artifactId>hamcrest-core</artifactId> -->
<!-- <scope>test</scope> -->
<!-- </dependency> -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>

View File

@ -16,29 +16,29 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() {
super();
}
public WebConfig() {
super();
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/graph.html");
registry.addViewController("/csrfHome.html");
registry.addViewController("/homepage.html");
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/graph.html");
registry.addViewController("/csrfHome.html");
registry.addViewController("/homepage.html");
}
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new LoggerInterceptor());
}
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new LoggerInterceptor());
}
}

View File

@ -14,20 +14,20 @@ import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
@RequestMapping(value = "/auth/")
public class BankController {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping(value = "/transfer", method = RequestMethod.GET)
@ResponseBody
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
logger.info("Transfer to {}", accountNo);
return amount;
}
@RequestMapping(value = "/transfer", method = RequestMethod.GET)
@ResponseBody
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
logger.info("Transfer to {}", accountNo);
return amount;
}
// write - just for test
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
logger.info("Transfer to {}", accountNo);
// write - just for test
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
logger.info("Transfer to {}", accountNo);
}
}
}

View File

@ -32,90 +32,90 @@ import com.google.common.base.Preconditions;
@RequestMapping(value = "/auth/foos")
public class FooController {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private IFooService service;
@Autowired
private IFooService service;
public FooController() {
super();
}
public FooController() {
super();
}
// API
// API
@RequestMapping(method = RequestMethod.GET, value = "/count")
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public long count() {
return 2l;
}
@RequestMapping(method = RequestMethod.GET, value = "/count")
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public long count() {
return 2l;
}
// read - one
// read - one
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return resourceById;
}
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return resourceById;
}
// read - all
// read - all
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<Foo> findAll() {
return service.findAll();
}
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<Foo> findAll() {
return service.findAll();
}
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
@ResponseBody
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);
if (page > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
@ResponseBody
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);
if (page > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
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)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
Preconditions.checkNotNull(resource);
final Foo foo = service.create(resource);
final Long idOfCreatedResource = foo.getId();
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
Preconditions.checkNotNull(resource);
final Foo foo = service.create(resource);
final Long idOfCreatedResource = foo.getId();
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
return foo;
}
return foo;
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
Preconditions.checkNotNull(resource);
RestPreconditions.checkFound(service.findOne(resource.getId()));
service.update(resource);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
Preconditions.checkNotNull(resource);
RestPreconditions.checkFound(service.findOne(resource.getId()));
service.update(resource);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") final Long id) {
service.deleteById(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") final Long id) {
service.deleteById(id);
}
@RequestMapping(method = RequestMethod.HEAD)
@ResponseStatus(HttpStatus.OK)
public void head(final HttpServletResponse resp) {
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
resp.setHeader("bar", "baz");
}
@RequestMapping(method = RequestMethod.HEAD)
@ResponseStatus(HttpStatus.OK)
public void head(final HttpServletResponse resp) {
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
resp.setHeader("bar", "baz");
}
}

View File

@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping(value = "/")
public class HomeController {
public String index() {
return "homepage";
}
public String index() {
return "homepage";
}
}

View File

@ -23,63 +23,63 @@ import org.springframework.web.util.UriTemplate;
@RequestMapping(value = "/auth/")
public class RootController {
@Autowired
private IMetricService metricService;
@Autowired
private IMetricService metricService;
@Autowired
private IActuatorMetricService actMetricService;
@Autowired
private IActuatorMetricService actMetricService;
public RootController() {
super();
}
public RootController() {
super();
}
// API
// API
// discover
// discover
@RequestMapping(value = "admin", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
final String rootUri = request.getRequestURL().toString();
@RequestMapping(value = "admin", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
final String rootUri = request.getRequestURL().toString();
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
response.addHeader("Link", linkToFoo);
}
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
response.addHeader("Link", linkToFoo);
}
@RequestMapping(value = "/metric", method = RequestMethod.GET)
@ResponseBody
public Map getMetric() {
return metricService.getFullMetric();
}
@RequestMapping(value = "/metric", method = RequestMethod.GET)
@ResponseBody
public Map getMetric() {
return metricService.getFullMetric();
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
@ResponseBody
public Map getStatusMetric() {
return metricService.getStatusMetric();
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
@ResponseBody
public Map getStatusMetric() {
return metricService.getStatusMetric();
}
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
@ResponseBody
public Object[][] drawMetric() {
final Object[][] result = metricService.getGraphData();
for (int i = 1; i < result[0].length; i++) {
result[0][i] = result[0][i].toString();
}
return result;
}
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
@ResponseBody
public Object[][] drawMetric() {
final Object[][] result = metricService.getGraphData();
for (int i = 1; i < result[0].length; i++) {
result[0][i] = result[0][i].toString();
}
return result;
}
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
@ResponseBody
public String sampleAdminPage() {
return "Hello";
}
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
@ResponseBody
public String sampleAdminPage() {
return "Hello";
}
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
@ResponseBody
public String sampleErrorPage() {
return "Error Occurred";
}
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
@ResponseBody
public String sampleErrorPage() {
return "Error Occurred";
}
}

View File

@ -40,94 +40,94 @@ import cz.jirutka.rsql.parser.ast.Node;
@RequestMapping(value = "/auth/")
public class UserController {
@Autowired
private IUserDAO service;
@Autowired
private IUserDAO service;
@Autowired
private UserRepository dao;
@Autowired
private UserRepository dao;
@Autowired
private MyUserRepository myUserRepository;
@Autowired
private MyUserRepository myUserRepository;
public UserController() {
super();
}
public UserController() {
super();
}
// API - READ
// API - READ
@RequestMapping(method = RequestMethod.GET, value = "/users")
@ResponseBody
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
if (search != null) {
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
}
}
return service.searchUser(params);
}
@RequestMapping(method = RequestMethod.GET, value = "/users")
@ResponseBody
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
if (search != null) {
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
}
}
return service.searchUser(params);
}
@RequestMapping(method = RequestMethod.GET, value = "/users/spec")
@ResponseBody
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
}
@RequestMapping(method = RequestMethod.GET, value = "/users/spec")
@ResponseBody
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
}
final Specification<User> spec = builder.build();
return dao.findAll(spec);
}
final Specification<User> spec = builder.build();
return dao.findAll(spec);
}
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
@ResponseBody
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
if (search != null) {
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
}
}
final BooleanExpression exp = builder.build();
return myUserRepository.findAll(exp);
}
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
@ResponseBody
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
if (search != null) {
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
}
}
final BooleanExpression exp = builder.build();
return myUserRepository.findAll(exp);
}
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
@ResponseBody
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
final Node rootNode = new RSQLParser().parse(search);
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
return dao.findAll(spec);
}
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
@ResponseBody
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
final Node rootNode = new RSQLParser().parse(search);
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
return dao.findAll(spec);
}
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
@ResponseBody
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
return myUserRepository.findAll(predicate);
}
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
@ResponseBody
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
return myUserRepository.findAll(predicate);
}
// API - WRITE
// API - WRITE
@RequestMapping(method = RequestMethod.POST, value = "/users")
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody final User resource) {
Preconditions.checkNotNull(resource);
dao.save(resource);
}
@RequestMapping(method = RequestMethod.POST, value = "/users")
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody final User resource) {
Preconditions.checkNotNull(resource);
dao.save(resource);
}
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
@ResponseStatus(HttpStatus.CREATED)
public void addMyUser(@RequestBody final MyUser resource) {
Preconditions.checkNotNull(resource);
myUserRepository.save(resource);
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
@ResponseStatus(HttpStatus.CREATED)
public void addMyUser(@RequestBody final MyUser resource) {
Preconditions.checkNotNull(resource);
myUserRepository.save(resource);
}
}
}

View File

@ -27,8 +27,7 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter {
* Executed before after handler is executed
**/
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception {
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
log.info("[postHandle][" + request + "]");
}
@ -36,8 +35,7 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter {
* Executed after complete request is finished
**/
@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
throws Exception {
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
if (ex != null)
ex.printStackTrace();
log.info("[afterCompletion][" + request + "][exception: " + ex + "]");

View File

@ -1,6 +1,5 @@
package org.baeldung.security;
import org.baeldung.security.csrf.CsrfDisabledIntegrationTest;
import org.baeldung.security.csrf.CsrfEnabledIntegrationTest;
import org.junit.runner.RunWith;

View File

@ -23,30 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@WebAppConfiguration
public class CsrfAbstractIntegrationTest {
@Autowired
private WebApplicationContext context;
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
@Autowired
private Filter springSecurityFilterChain;
protected MockMvc mvc;
protected MockMvc mvc;
//
//
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
}
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
}
protected RequestPostProcessor testUser() {
return user("user").password("userPass").roles("USER");
}
protected RequestPostProcessor testUser() {
return user("user").password("userPass").roles("USER");
}
protected RequestPostProcessor testAdmin() {
return user("admin").password("adminPass").roles("USER", "ADMIN");
}
protected RequestPostProcessor testAdmin() {
return user("admin").password("adminPass").roles("USER", "ADMIN");
}
protected String createFoo() throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
}
protected String createFoo() throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
}
}

View File

@ -14,33 +14,31 @@ import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
@Test
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
}
@Test
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
}
@Test
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
}
@Test
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
}
@Test
public void accessMainPageWithoutAuthorization() throws Exception {
mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
@Test
public void accessMainPageWithoutAuthorization() throws Exception {
mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
@Test
public void accessOtherPages() throws Exception {
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100"))
.andExpect(status().isUnauthorized()); // without authorization
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser()))
.andExpect(status().isOk()); // with authorization
}
@Test
public void accessOtherPages() throws Exception {
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100")).andExpect(status().isUnauthorized()); // without authorization
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser())).andExpect(status().isOk()); // with authorization
}
@Test
public void accessAdminPage() throws Exception {
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); //without authorization
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); //with authorization
}
@Test
public void accessAdminPage() throws Exception {
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); // without authorization
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); // with authorization
}
}

View File

@ -25,27 +25,27 @@ import org.springframework.web.context.WebApplicationContext;
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
public class LoggerInterceptorTest {
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
private MockMvc mockMvc;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
/**
* After execution of HTTP GET logs from interceptor will be displayed in
* the console
*
* @throws Exception
*/
@Test
public void testInterceptors() throws Exception {
mockMvc.perform(get("/graph.html")).andExpect(status().isOk());
}
/**
* After execution of HTTP GET logs from interceptor will be displayed in
* the console
*
* @throws Exception
*/
@Test
public void testInterceptors() throws Exception {
mockMvc.perform(get("/graph.html")).andExpect(status().isOk());
}
}

View File

@ -1,5 +1,7 @@
package com.baeldung.spring.security.x509;
import java.security.Principal;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
@ -7,8 +9,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.security.Principal;
@Controller
public class UserController {
@PreAuthorize("hasAuthority('ROLE_USER')")

View File

@ -2,21 +2,15 @@ package com.baeldung.spring.security.x509;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@SpringBootApplication
@EnableWebSecurity
public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(X509AuthenticationServer.class, args);
}
}

View File

@ -1,5 +1,7 @@
package com.baeldung.spring.security.x509;
import java.security.Principal;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
@ -7,8 +9,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.security.Principal;
@Controller
public class UserController {
@PreAuthorize("hasAuthority('ROLE_USER')")

View File

@ -23,9 +23,7 @@ public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService());
http.authorizeRequests().anyRequest().authenticated().and().x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService());
}
@Bean