From e479614eaabc25f243ebcb8754a29ca6c561e59a Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Fri, 12 Aug 2016 18:44:08 +0800 Subject: [PATCH 01/43] added persistence --- mapstruct/pom.xml | 49 +++++++++++++++++++ .../java/org/baeldung/dto/EmployeeDTO.java | 42 ++++++++++++++++ .../java/org/baeldung/dto/SimpleSource.java | 24 +++++++++ .../java/org/baeldung/entity/Division.java | 33 +++++++++++++ .../java/org/baeldung/entity/Employee.java | 33 +++++++++++++ .../baeldung/entity/SimpleDestination.java | 24 +++++++++ .../org/baeldung/mapper/EmployeeMapper.java | 27 ++++++++++ .../mapper/SimpleSourceDestinationMapper.java | 13 +++++ .../SimpleSourceDestinationSpringMapper.java | 13 +++++ .../baeldung/mapper/EmployeeMapperTest.java | 48 ++++++++++++++++++ .../SimpleSourceDestinationMapperTest.java | 44 +++++++++++++++++ spring-rest-angular-pagination/pom.xml | 9 ++++ .../org/baeldung/mock/MockStudentData.java | 46 ++++++++--------- .../baeldung/web/dao/StudentRepository.java | 10 ++++ .../baeldung/web/{vo => entity}/Student.java | 25 +++++++--- .../org/baeldung/web/main/Application.java | 4 +- .../baeldung/web/main/PersistenceConfig.java | 37 ++++++++++++++ .../rest/StudentDirectoryRestController.java | 5 +- .../org/baeldung/web/service/IOperations.java | 2 +- .../baeldung/web/service/StudentService.java | 2 +- .../web/service/StudentServiceImpl.java | 30 ++++-------- .../src/main/resources/application.properties | 4 +- .../src/main/resources/db/sql/data.sql | 9 ++++ 23 files changed, 472 insertions(+), 61 deletions(-) create mode 100644 mapstruct/pom.xml create mode 100644 mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java create mode 100644 mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java create mode 100644 mapstruct/src/main/java/org/baeldung/entity/Division.java create mode 100644 mapstruct/src/main/java/org/baeldung/entity/Employee.java create mode 100644 mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java create mode 100644 mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java create mode 100644 mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java create mode 100644 mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java create mode 100644 mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java create mode 100644 mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java create mode 100644 spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java rename spring-rest-angular-pagination/src/main/java/org/baeldung/web/{vo => entity}/Student.java (61%) create mode 100644 spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java create mode 100644 spring-rest-angular-pagination/src/main/resources/db/sql/data.sql diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml new file mode 100644 index 0000000000..8a28ae9511 --- /dev/null +++ b/mapstruct/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + mapstruct + mapstruct + com.baeldung + 1.0 + jar + + + 1.0.0.Final + + + + org.mapstruct + mapstruct-jdk8 + ${org.mapstruct.version} + + + junit + junit + 4.12 + test + + + + mapstruct + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + + diff --git a/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java b/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java new file mode 100644 index 0000000000..67b9ffc024 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java @@ -0,0 +1,42 @@ +package org.baeldung.dto; + +public class EmployeeDTO { + + private int employeeId; + private String employeeName; + private int divisionId; + private String divisionName; + + public int getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(int employeeId) { + this.employeeId = employeeId; + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public int getDivisionId() { + return divisionId; + } + + public void setDivisionId(int divisionId) { + this.divisionId = divisionId; + } + + public String getDivisionName() { + return divisionName; + } + + public void setDivisionName(String divisionName) { + this.divisionName = divisionName; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java b/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java new file mode 100644 index 0000000000..fc0c75dea3 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java @@ -0,0 +1,24 @@ +package org.baeldung.dto; + +public class SimpleSource { + + private String name; + private String description; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/entity/Division.java b/mapstruct/src/main/java/org/baeldung/entity/Division.java new file mode 100644 index 0000000000..04f1ab2c23 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/entity/Division.java @@ -0,0 +1,33 @@ +package org.baeldung.entity; + +public class Division { + + public Division() { + } + + public Division(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/entity/Employee.java b/mapstruct/src/main/java/org/baeldung/entity/Employee.java new file mode 100644 index 0000000000..55599a17f9 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/entity/Employee.java @@ -0,0 +1,33 @@ +package org.baeldung.entity; + +public class Employee { + + private int id; + private String name; + private Division division; + + 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; + } + + public Division getDivision() { + return division; + } + + public void setDivision(Division division) { + this.division = division; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java b/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java new file mode 100644 index 0000000000..901257c11b --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java @@ -0,0 +1,24 @@ +package org.baeldung.entity; + +public class SimpleDestination { + + private String name; + private String description; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java new file mode 100644 index 0000000000..28faffec45 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java @@ -0,0 +1,27 @@ +package org.baeldung.mapper; + +import org.baeldung.dto.EmployeeDTO; +import org.baeldung.entity.Employee; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +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); + +} diff --git a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java new file mode 100644 index 0000000000..f3210288d2 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java @@ -0,0 +1,13 @@ +package org.baeldung.mapper; + +import org.baeldung.dto.SimpleSource; +import org.baeldung.entity.SimpleDestination; +import org.mapstruct.Mapper; + +@Mapper +public interface SimpleSourceDestinationMapper { + + SimpleDestination sourceToDestination(SimpleSource source); + SimpleSource destinationToSource(SimpleDestination destination); + +} diff --git a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java new file mode 100644 index 0000000000..2077eabf51 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java @@ -0,0 +1,13 @@ +package org.baeldung.mapper; + +import org.baeldung.dto.SimpleSource; +import org.baeldung.entity.SimpleDestination; +import org.mapstruct.Mapper; + +@Mapper(componentModel="spring") +public interface SimpleSourceDestinationSpringMapper { + + SimpleDestination sourceToDestination(SimpleSource source); + SimpleSource destinationToSource(SimpleDestination destination); + +} diff --git a/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java b/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java new file mode 100644 index 0000000000..0433013f2e --- /dev/null +++ b/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java @@ -0,0 +1,48 @@ +package org.baeldung.mapper; + +import static org.junit.Assert.*; + +import org.baeldung.dto.EmployeeDTO; +import org.baeldung.entity.Division; +import org.baeldung.entity.Employee; +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()); + } + +} diff --git a/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java b/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java new file mode 100644 index 0000000000..a7e3b05dc6 --- /dev/null +++ b/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java @@ -0,0 +1,44 @@ +package org.baeldung.mapper; + +import static org.junit.Assert.*; + +import org.baeldung.dto.SimpleSource; +import org.baeldung.entity.SimpleDestination; +import org.junit.Test; +import org.mapstruct.factory.Mappers; + +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()); + } + +} diff --git a/spring-rest-angular-pagination/pom.xml b/spring-rest-angular-pagination/pom.xml index 7a0f3e7b31..db7da64b61 100644 --- a/spring-rest-angular-pagination/pom.xml +++ b/spring-rest-angular-pagination/pom.xml @@ -30,6 +30,15 @@ org.springframework.data spring-data-commons + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + org.springframework spring-test diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java index df70780a87..2c37317b75 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java @@ -3,34 +3,34 @@ package org.baeldung.mock; import java.util.ArrayList; import java.util.List; -import org.baeldung.web.vo.Student; +import org.baeldung.web.entity.Student; public class MockStudentData { private static List studentList = new ArrayList<>(); - static { - studentList.add(new Student("1", "Bryan", "Male", 20)); - studentList.add(new Student("2", "Ben", "Male", 22)); - studentList.add(new Student("3", "Lisa", "Female", 24)); - studentList.add(new Student("4", "Sarah", "Female", 26)); - studentList.add(new Student("5", "Jay", "Male", 20)); - studentList.add(new Student("6", "John", "Male", 22)); - studentList.add(new Student("7", "Jordan", "Male", 24)); - studentList.add(new Student("8", "Rob", "Male", 26)); - studentList.add(new Student("9", "Will", "Male", 20)); - studentList.add(new Student("10", "Shawn", "Male", 22)); - studentList.add(new Student("11", "Taylor", "Female", 24)); - studentList.add(new Student("12", "Venus", "Female", 26)); - studentList.add(new Student("13", "Vince", "Male", 20)); - studentList.add(new Student("14", "Carol", "Female", 22)); - studentList.add(new Student("15", "Joana", "Female", 24)); - studentList.add(new Student("16", "Dion", "Male", 26)); - studentList.add(new Student("17", "Evans", "Male", 20)); - studentList.add(new Student("18", "Bart", "Male", 22)); - studentList.add(new Student("19", "Jenny", "Female", 24)); - studentList.add(new Student("20", "Kristine", "Female", 26)); - } +// static { +// studentList.add(new Student("1", "Bryan", "Male", 20)); +// studentList.add(new Student("2", "Ben", "Male", 22)); +// studentList.add(new Student("3", "Lisa", "Female", 24)); +// studentList.add(new Student("4", "Sarah", "Female", 26)); +// studentList.add(new Student("5", "Jay", "Male", 20)); +// studentList.add(new Student("6", "John", "Male", 22)); +// studentList.add(new Student("7", "Jordan", "Male", 24)); +// studentList.add(new Student("8", "Rob", "Male", 26)); +// studentList.add(new Student("9", "Will", "Male", 20)); +// studentList.add(new Student("10", "Shawn", "Male", 22)); +// studentList.add(new Student("11", "Taylor", "Female", 24)); +// studentList.add(new Student("12", "Venus", "Female", 26)); +// studentList.add(new Student("13", "Vince", "Male", 20)); +// studentList.add(new Student("14", "Carol", "Female", 22)); +// studentList.add(new Student("15", "Joana", "Female", 24)); +// studentList.add(new Student("16", "Dion", "Male", 26)); +// studentList.add(new Student("17", "Evans", "Male", 20)); +// studentList.add(new Student("18", "Bart", "Male", 22)); +// studentList.add(new Student("19", "Jenny", "Female", 24)); +// studentList.add(new Student("20", "Kristine", "Female", 26)); +// } public static List getMockDataStudents(){ return studentList; diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java new file mode 100644 index 0000000000..0f468a48f1 --- /dev/null +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.web.dao; + +import org.baeldung.web.entity.Student; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface StudentRepository extends JpaRepository { + +} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/vo/Student.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java similarity index 61% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/vo/Student.java rename to spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java index 11c503815d..59a64b04e8 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/vo/Student.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java @@ -1,7 +1,12 @@ -package org.baeldung.web.vo; +package org.baeldung.web.entity; import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity public class Student implements Serializable { /** @@ -12,25 +17,29 @@ public class Student implements Serializable { public Student() { } - public Student(String studentId, String name, String gender, Integer age) { + public Student(long id, String name, String gender, Integer age) { super(); - this.studentId = studentId; + this.id = id; this.name = name; this.gender = gender; this.age = age; } - private String studentId; + @Id + private long id; + @Column(nullable = false) private String name; + @Column(nullable = false) private String gender; + @Column(nullable = false) private Integer age; - public String getStudentId() { - return studentId; + public long getId() { + return id; } - public void setStudentId(String studentId) { - this.studentId = studentId; + public void setId(long id) { + this.id = id; } public String getName() { diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java index b3b0dad98a..15e386a23d 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java @@ -4,13 +4,13 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Import; import org.springframework.web.filter.ShallowEtagHeaderFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication @EnableAutoConfiguration -@ComponentScan("org.baeldung") +@Import(PersistenceConfig.class) public class Application extends WebMvcConfigurerAdapter { diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java new file mode 100644 index 0000000000..2a50f19907 --- /dev/null +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java @@ -0,0 +1,37 @@ +package org.baeldung.web.main; + +import javax.sql.DataSource; + +import org.springframework.boot.orm.jpa.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +@EnableJpaRepositories("org.baeldung") +@ComponentScan(basePackages = { "org.baeldung.web" }) +@EntityScan("org.baeldung.web.entity") +@Configuration +public class PersistenceConfig { + + @Bean + public JdbcTemplate getJdbcTemplate() { + return new JdbcTemplate(dataSource()); + } + + @Bean + public DataSource dataSource() { + + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase db = builder + .setType(EmbeddedDatabaseType.HSQL) + .addScript("db/sql/data.sql") + .build(); + return db; + } + +} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java index b655d401a5..1aa9390aee 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java @@ -1,17 +1,14 @@ package org.baeldung.web.rest; +import org.baeldung.web.entity.Student; import org.baeldung.web.service.StudentService; -import org.baeldung.web.vo.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; -import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import static org.springframework.http.MediaType.APPLICATION_JSON; - @RestController public class StudentDirectoryRestController { diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java index 0b408106ce..c124c9e0a0 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java @@ -4,6 +4,6 @@ import org.springframework.data.domain.Page; public interface IOperations { - Page findPaginated(int page, int size); + public Page findPaginated(final int page, final int size); } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java index 5c4487254a..df40bb6b9e 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java @@ -1,6 +1,6 @@ package org.baeldung.web.service; -import org.baeldung.web.vo.Student; +import org.baeldung.web.entity.Student; public interface StudentService extends IOperations{ diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java index 3b6dda6fb1..fd9262cfc6 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java @@ -1,36 +1,24 @@ package org.baeldung.web.service; -import java.util.List; +import javax.transaction.Transactional; -import org.baeldung.mock.MockStudentData; -import org.baeldung.web.exception.MyResourceNotFoundException; -import org.baeldung.web.vo.Student; +import org.baeldung.web.dao.StudentRepository; +import org.baeldung.web.entity.Student; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @Service +@Transactional public class StudentServiceImpl implements StudentService { - private List mockDataStudent = MockStudentData.getMockDataStudents(); + @Autowired + private StudentRepository dao; @Override - public Page findPaginated(int page, int size){ - Page studentPage = getPage(page, size); - return studentPage; - } - - private Page getPage(int page, int size) { - page = page != 0?page - 1:page; - int from = Math.max(0, page * size); - int to = Math.min(mockDataStudent.size(), (page + 1) * size); - if(from > to){ - throw new MyResourceNotFoundException("page number is higher than total pages."); - } - return new PageImpl(mockDataStudent.subList(from, to), - new PageRequest(page,size), - mockDataStudent.size()); + public Page findPaginated(int page, int size) { + return dao.findAll(new PageRequest(page,size)); } } diff --git a/spring-rest-angular-pagination/src/main/resources/application.properties b/spring-rest-angular-pagination/src/main/resources/application.properties index e42588cee0..9b4f95a9dc 100644 --- a/spring-rest-angular-pagination/src/main/resources/application.properties +++ b/spring-rest-angular-pagination/src/main/resources/application.properties @@ -1 +1,3 @@ -server.contextPath=/ \ No newline at end of file +server.contextPath=/ +spring.h2.console.enabled=true +logging.level.org.hibernate.SQL=debug \ No newline at end of file diff --git a/spring-rest-angular-pagination/src/main/resources/db/sql/data.sql b/spring-rest-angular-pagination/src/main/resources/db/sql/data.sql new file mode 100644 index 0000000000..d9f6ac610a --- /dev/null +++ b/spring-rest-angular-pagination/src/main/resources/db/sql/data.sql @@ -0,0 +1,9 @@ +CREATE TABLE student ( + id INTEGER PRIMARY KEY, + name VARCHAR(30), + gender VARCHAR(10), + age INTEGER +); + +INSERT INTO student (id,name,gender,age) +VALUES (1,'Bryan', 'Male',20); \ No newline at end of file From f755fce0bb765b46fbadcab4b0fe79a698cccab6 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 13 Aug 2016 13:12:57 +0200 Subject: [PATCH 02/43] Initial classes --- .../baeldung/profiles/DatasourceConfig.java | 2 +- .../startup/InitializingBeanExampleBean.java | 12 +++++++++ .../LogicInConstructorExampleBean.java | 18 +++++++++++++ ...StartupApplicationListenerExampleBean.java | 4 +++ .../startup/PostConstructExampleBean.java | 15 +++++++++++ .../baeldung/startup/SpringStartupConfig.java | 10 ++++++++ .../baeldung/startup/SpringStartupTest.java | 25 +++++++++++++++++++ 7 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java create mode 100644 spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java create mode 100644 spring-all/src/main/java/org/baeldung/startup/OnStartupApplicationListenerExampleBean.java create mode 100644 spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java create mode 100644 spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java create mode 100644 spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java diff --git a/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java b/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java index 80cb060c7e..8fde925fd8 100644 --- a/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java +++ b/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java @@ -1,5 +1,5 @@ package org.baeldung.profiles; public interface DatasourceConfig { - public void setup(); + void setup(); } diff --git a/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java new file mode 100644 index 0000000000..431307b81a --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java @@ -0,0 +1,12 @@ +package org.baeldung.startup; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Scope; + +@Scope(value = "prototype") +public class InitializingBeanExampleBean implements InitializingBean { + + @Override + public void afterPropertiesSet() throws Exception { + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java new file mode 100644 index 0000000000..410eb3b061 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java @@ -0,0 +1,18 @@ +package org.baeldung.startup; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = "prototype") +public class LogicInConstructorExampleBean { + + @Autowired + private Environment environment; + + public LogicInConstructorExampleBean() { + environment.getActiveProfiles(); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/OnStartupApplicationListenerExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/OnStartupApplicationListenerExampleBean.java new file mode 100644 index 0000000000..259b468890 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/OnStartupApplicationListenerExampleBean.java @@ -0,0 +1,4 @@ +package org.baeldung.startup; + +public class OnStartupApplicationListenerExampleBean { +} diff --git a/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java new file mode 100644 index 0000000000..3f7cb5e7d2 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java @@ -0,0 +1,15 @@ +package org.baeldung.startup; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class PostConstructExampleBean { + + @Autowired + private Environment environment; + + public PostConstructExampleBean() { + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java b/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java new file mode 100644 index 0000000000..b7874af28c --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java @@ -0,0 +1,10 @@ +package org.baeldung.startup; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("org.baeldung.startup") +public class SpringStartupConfig { + +} \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java new file mode 100644 index 0000000000..2f6ce1b5ea --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java @@ -0,0 +1,25 @@ +package org.baeldung.startup; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringStartupTest { + + @Autowired + private ApplicationContext ctx; + + @Test(expected = BeanCreationException.class) + public void whenInstantiating_shouldThrowNPE() throws Exception { + ctx.getBean(LogicInConstructorExampleBean.class); + } + + +} \ No newline at end of file From cd2ee40c061b50c118f1a26c713df4b853e6ee62 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 13 Aug 2016 13:20:45 +0200 Subject: [PATCH 03/43] Use scope prototype --- .../java/org/baeldung/startup/InitializingBeanExampleBean.java | 2 ++ .../java/org/baeldung/startup/PostConstructExampleBean.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java index 431307b81a..c766238006 100644 --- a/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java @@ -2,7 +2,9 @@ package org.baeldung.startup; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +@Component @Scope(value = "prototype") public class InitializingBeanExampleBean implements InitializingBean { diff --git a/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java index 3f7cb5e7d2..785eab39c3 100644 --- a/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java @@ -1,10 +1,12 @@ package org.baeldung.startup; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component +@Scope(value = "prototype") public class PostConstructExampleBean { @Autowired From bec20baad046e69ff5d5a2b920c7e0b4b9120b85 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 13 Aug 2016 13:32:04 +0200 Subject: [PATCH 04/43] Add examples --- .../org/baeldung/async/AsyncComponent.java | 6 +++--- .../startup/InitializingBeanExampleBean.java | 9 +++++++++ .../startup/InvalidInitExampleBean.java | 18 ++++++++++++++++++ .../startup/LogicInConstructorExampleBean.java | 13 +++++++++---- .../startup/PostConstructExampleBean.java | 9 ++++++++- .../baeldung/startup/SpringStartupConfig.java | 1 - .../baeldung/startup/SpringStartupTest.java | 17 +++++++++++++++-- 7 files changed, 62 insertions(+), 11 deletions(-) create mode 100644 spring-all/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java diff --git a/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java b/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java index 2946ab0aa1..8503f75c8f 100644 --- a/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java +++ b/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java @@ -1,11 +1,11 @@ package org.baeldung.async; -import java.util.concurrent.Future; - import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; +import java.util.concurrent.Future; + @Component public class AsyncComponent { @@ -19,7 +19,7 @@ public class AsyncComponent { System.out.println("Execute method asynchronously " + Thread.currentThread().getName()); try { Thread.sleep(5000); - return new AsyncResult("hello world !!!!"); + return new AsyncResult<>("hello world !!!!"); } catch (final InterruptedException e) { } diff --git a/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java index c766238006..8d4f04e1ad 100644 --- a/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java @@ -1,14 +1,23 @@ package org.baeldung.startup; +import org.apache.log4j.Logger; import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @Scope(value = "prototype") public class InitializingBeanExampleBean implements InitializingBean { + private static final Logger LOG = Logger.getLogger(InitializingBeanExampleBean.class); + + @Autowired + private Environment environment; + @Override public void afterPropertiesSet() throws Exception { + LOG.info(environment); } } diff --git a/spring-all/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java new file mode 100644 index 0000000000..0b9c6f0c7d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java @@ -0,0 +1,18 @@ +package org.baeldung.startup; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Scope("prototype") +public class InvalidInitExampleBean { + + @Autowired + private Environment environment; + + public InvalidInitExampleBean() { + environment.getActiveProfiles(); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java index 410eb3b061..3cef105c3c 100644 --- a/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java @@ -1,5 +1,6 @@ package org.baeldung.startup; +import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; @@ -9,10 +10,14 @@ import org.springframework.stereotype.Component; @Scope(value = "prototype") public class LogicInConstructorExampleBean { - @Autowired - private Environment environment; + private static final Logger LOG = Logger.getLogger(LogicInConstructorExampleBean.class); - public LogicInConstructorExampleBean() { - environment.getActiveProfiles(); + private final Environment environment; + + @Autowired + public LogicInConstructorExampleBean(Environment environment) { + this.environment = environment; + + LOG.info(environment); } } diff --git a/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java index 785eab39c3..be21aef70c 100644 --- a/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java @@ -1,17 +1,24 @@ package org.baeldung.startup; +import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; + @Component @Scope(value = "prototype") public class PostConstructExampleBean { + private static final Logger LOG = Logger.getLogger(PostConstructExampleBean.class); + @Autowired private Environment environment; - public PostConstructExampleBean() { + @PostConstruct + public void init() { + LOG.info(environment); } } diff --git a/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java b/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java index b7874af28c..12854e1be5 100644 --- a/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java +++ b/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java @@ -6,5 +6,4 @@ import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("org.baeldung.startup") public class SpringStartupConfig { - } \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java index 2f6ce1b5ea..1e76fd8746 100644 --- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java @@ -17,9 +17,22 @@ public class SpringStartupTest { private ApplicationContext ctx; @Test(expected = BeanCreationException.class) - public void whenInstantiating_shouldThrowNPE() throws Exception { + public void whenInstantiating_shouldThrowBCE() throws Exception { + ctx.getBean(InvalidInitExampleBean.class); + } + + @Test + public void whenPostConstruct_shouldLogEnv() throws Exception { + ctx.getBean(PostConstructExampleBean.class); + } + + @Test + public void whenConstructorInjection_shouldLogEnv() throws Exception { ctx.getBean(LogicInConstructorExampleBean.class); } - + @Test + public void whenInitializingBean_shouldLogEnv() throws Exception { + ctx.getBean(InitializingBeanExampleBean.class); + } } \ No newline at end of file From 2153e6d1a5370ad4d8823ef805fa0cc6f59a628d Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 13 Aug 2016 13:38:24 +0200 Subject: [PATCH 05/43] Remove ApplicationListenerBean --- .../startup/OnStartupApplicationListenerExampleBean.java | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 spring-all/src/main/java/org/baeldung/startup/OnStartupApplicationListenerExampleBean.java diff --git a/spring-all/src/main/java/org/baeldung/startup/OnStartupApplicationListenerExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/OnStartupApplicationListenerExampleBean.java deleted file mode 100644 index 259b468890..0000000000 --- a/spring-all/src/main/java/org/baeldung/startup/OnStartupApplicationListenerExampleBean.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.baeldung.startup; - -public class OnStartupApplicationListenerExampleBean { -} From 28f1fe27e2359cb4b2f8dbf36f57eacfb25b98d0 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 13 Aug 2016 13:41:55 +0200 Subject: [PATCH 06/43] Modify logging --- .../org/baeldung/startup/InitializingBeanExampleBean.java | 4 +++- .../org/baeldung/startup/LogicInConstructorExampleBean.java | 4 +++- .../java/org/baeldung/startup/PostConstructExampleBean.java | 3 ++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java index 8d4f04e1ad..33b14864f3 100644 --- a/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java @@ -7,6 +7,8 @@ import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import java.util.Arrays; + @Component @Scope(value = "prototype") public class InitializingBeanExampleBean implements InitializingBean { @@ -18,6 +20,6 @@ public class InitializingBeanExampleBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { - LOG.info(environment); + LOG.info(Arrays.asList(environment.getDefaultProfiles())); } } diff --git a/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java index 3cef105c3c..2a7b3e26c7 100644 --- a/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java @@ -6,6 +6,8 @@ import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import java.util.Arrays; + @Component @Scope(value = "prototype") public class LogicInConstructorExampleBean { @@ -18,6 +20,6 @@ public class LogicInConstructorExampleBean { public LogicInConstructorExampleBean(Environment environment) { this.environment = environment; - LOG.info(environment); + LOG.info(Arrays.asList(environment.getDefaultProfiles())); } } diff --git a/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java index be21aef70c..4cabaad4df 100644 --- a/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java @@ -7,6 +7,7 @@ import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; +import java.util.Arrays; @Component @Scope(value = "prototype") @@ -19,6 +20,6 @@ public class PostConstructExampleBean { @PostConstruct public void init() { - LOG.info(environment); + LOG.info(Arrays.asList(environment.getDefaultProfiles())); } } From e31c07a29c3c7aafe7b8d88da86ea6c3784544cd Mon Sep 17 00:00:00 2001 From: chernykhalexander Date: Sat, 13 Aug 2016 18:33:45 +0300 Subject: [PATCH 07/43] Changed method name in Spring Aspect. --- .../main/java/com/baeldung/spring/aspect/SpringTestAspect.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java index 8c2ff2600b..5d7b064d71 100644 --- a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java +++ b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java @@ -16,7 +16,7 @@ public class SpringTestAspect { private List accumulator; @Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))") - public Object advice(ProceedingJoinPoint jp) throws Throwable { + public Object auditMethod(ProceedingJoinPoint jp) throws Throwable { String methodName = jp.getSignature().getName(); accumulator.add("Call to "+methodName); Object obj = jp.proceed(); From eb1230b865ea6d2a039beb927f68c09df8e7df80 Mon Sep 17 00:00:00 2001 From: chernykhalexander Date: Sat, 13 Aug 2016 18:50:10 +0300 Subject: [PATCH 08/43] Fixed formatting --- .../main/java/com/baeldung/interceptor/Audited.java | 10 ++++++---- .../baeldung/interceptor/AuditedInterceptor.java | 5 +++-- .../java/com/baeldung/service/SuperService.java | 2 +- .../baeldung/spring/aspect/SpringTestAspect.java | 11 ++++------- .../baeldung/spring/configuration/AppConfig.java | 13 +++++++------ .../baeldung/spring/service/SpringSuperService.java | 2 +- 6 files changed, 22 insertions(+), 21 deletions(-) diff --git a/cdi/src/main/java/com/baeldung/interceptor/Audited.java b/cdi/src/main/java/com/baeldung/interceptor/Audited.java index 4065450b09..3df4bef95e 100644 --- a/cdi/src/main/java/com/baeldung/interceptor/Audited.java +++ b/cdi/src/main/java/com/baeldung/interceptor/Audited.java @@ -1,12 +1,14 @@ package com.baeldung.interceptor; -import javax.interceptor.InterceptorBinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.interceptor.InterceptorBinding; + @InterceptorBinding -@Target( {ElementType.METHOD, ElementType.TYPE } ) -@Retention(RetentionPolicy.RUNTIME ) -public @interface Audited {} +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Audited { +} diff --git a/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java index 46ab9b33c8..c62d9a4127 100644 --- a/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java +++ b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java @@ -3,12 +3,13 @@ package com.baeldung.interceptor; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; -import java.lang.reflect.Method; -@Audited @Interceptor +@Audited +@Interceptor public class AuditedInterceptor { public static boolean calledBefore = false; public static boolean calledAfter = false; + @AroundInvoke public Object auditMethod(InvocationContext ctx) throws Exception { calledBefore = true; diff --git a/cdi/src/main/java/com/baeldung/service/SuperService.java b/cdi/src/main/java/com/baeldung/service/SuperService.java index e1e57a4e0d..e15f049342 100644 --- a/cdi/src/main/java/com/baeldung/service/SuperService.java +++ b/cdi/src/main/java/com/baeldung/service/SuperService.java @@ -5,6 +5,6 @@ import com.baeldung.interceptor.Audited; public class SuperService { @Audited public String deliverService(String uid) { - return uid; + return uid; } } diff --git a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java index 5d7b064d71..e48039706d 100644 --- a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java +++ b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java @@ -1,15 +1,12 @@ package com.baeldung.spring.aspect; -import org.aspectj.lang.JoinPoint; +import java.util.List; + import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; import org.springframework.beans.factory.annotation.Autowired; -import javax.inject.Inject; -import java.util.List; - @Aspect public class SpringTestAspect { @Autowired @@ -18,9 +15,9 @@ public class SpringTestAspect { @Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))") public Object auditMethod(ProceedingJoinPoint jp) throws Throwable { String methodName = jp.getSignature().getName(); - accumulator.add("Call to "+methodName); + accumulator.add("Call to " + methodName); Object obj = jp.proceed(); - accumulator.add("Method called successfully: "+methodName); + accumulator.add("Method called successfully: " + methodName); return obj; } } diff --git a/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java index 6cfc8f8743..b30c4a1326 100644 --- a/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java +++ b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java @@ -1,13 +1,14 @@ package com.baeldung.spring.configuration; -import com.baeldung.spring.aspect.SpringTestAspect; -import com.baeldung.spring.service.SpringSuperService; +import java.util.ArrayList; +import java.util.List; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; -import java.util.ArrayList; -import java.util.List; +import com.baeldung.spring.aspect.SpringTestAspect; +import com.baeldung.spring.service.SpringSuperService; @Configuration @EnableAspectJAutoProxy @@ -18,12 +19,12 @@ public class AppConfig { } @Bean - public SpringTestAspect springTestAspect(){ + public SpringTestAspect springTestAspect() { return new SpringTestAspect(); } @Bean - public List getAccumulator(){ + public List getAccumulator() { return new ArrayList(); } } diff --git a/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java index 72dbd1c006..082eb2e0f8 100644 --- a/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java +++ b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java @@ -1,7 +1,7 @@ package com.baeldung.spring.service; public class SpringSuperService { - public String getInfoFromService(String code){ + public String getInfoFromService(String code) { return code; } } From 2ea8328576e19da3662ae2b132bda5d51510888c Mon Sep 17 00:00:00 2001 From: chernykhalexander Date: Sat, 13 Aug 2016 18:58:09 +0300 Subject: [PATCH 09/43] Fixed formatting --- .../com/baeldung/test/TestInterceptor.java | 16 ++++--------- .../baeldung/test/TestSpringInterceptor.java | 24 ++++++++----------- 2 files changed, 15 insertions(+), 25 deletions(-) diff --git a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java index d1b851c94f..406296529c 100644 --- a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java @@ -1,8 +1,5 @@ package com.baeldung.test; -import com.baeldung.interceptor.Audited; -import com.baeldung.interceptor.AuditedInterceptor; -import com.baeldung.service.SuperService; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.After; @@ -10,24 +7,21 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import javax.enterprise.inject.spi.BeanManager; -import javax.enterprise.inject.spi.InterceptionType; -import javax.enterprise.inject.spi.Interceptor; -import javax.enterprise.util.AnnotationLiteral; - -import static javafx.beans.binding.Bindings.select; +import com.baeldung.interceptor.AuditedInterceptor; +import com.baeldung.service.SuperService; public class TestInterceptor { Weld weld; WeldContainer container; + @Before - public void init(){ + public void init() { weld = new Weld(); container = weld.initialize(); } @After - public void shutdown(){ + public void shutdown() { weld.shutdown(); } diff --git a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java index b5aedd4b76..1f3a8d83e3 100644 --- a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java @@ -1,25 +1,21 @@ package com.baeldung.test; -import com.baeldung.spring.configuration.AppConfig; -import com.baeldung.spring.service.SpringSuperService; +import static org.hamcrest.CoreMatchers.is; + +import java.util.List; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import org.springframework.test.context.transaction.TransactionalTestExecutionListener; -import javax.inject.Inject; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; +import com.baeldung.spring.configuration.AppConfig; +import com.baeldung.spring.service.SpringSuperService; @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {AppConfig.class}) +@ContextConfiguration(classes = { AppConfig.class }) public class TestSpringInterceptor { @Autowired SpringSuperService springSuperService; @@ -28,11 +24,11 @@ public class TestSpringInterceptor { private List accumulator; @Test - public void givenService_whenServiceAndAspectExecuted_thenOk(){ + public void givenService_whenServiceAndAspectExecuted_thenOk() { String code = "123456"; String result = springSuperService.getInfoFromService(code); Assert.assertThat(accumulator.size(), is(2)); - Assert.assertThat(accumulator.get(0),is("Call to getInfoFromService")); - Assert.assertThat(accumulator.get(1),is("Method called successfully: getInfoFromService")); + Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService")); + Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService")); } } From 24e033a24bf1e18ea07bcd80a8a36c8dcfff416b Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 14 Aug 2016 08:13:04 +0200 Subject: [PATCH 10/43] Add ApplicationListener example --- spring-all/pom.xml | 7 +++++++ .../StartupApplicationListenerExample.java | 16 ++++++++++++++++ .../org/baeldung/startup/SpringStartupTest.java | 6 ++++++ 3 files changed, 29 insertions(+) create mode 100644 spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 25a45d9bae..c70d9d75fc 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -130,6 +130,13 @@ test + + org.assertj + assertj-core + 3.5.1 + test + + org.hamcrest hamcrest-core diff --git a/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java b/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java new file mode 100644 index 0000000000..1c784e0c74 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java @@ -0,0 +1,16 @@ +package org.baeldung.startup; + +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +@Component +public class StartupApplicationListenerExample implements ApplicationListener { + + public static int counter; + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + counter++; + } +} diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java index 1e76fd8746..523a27c2c4 100644 --- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java @@ -1,5 +1,6 @@ package org.baeldung.startup; +import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanCreationException; @@ -35,4 +36,9 @@ public class SpringStartupTest { public void whenInitializingBean_shouldLogEnv() throws Exception { ctx.getBean(InitializingBeanExampleBean.class); } + + @Test + public void whenApplicationListener_shouldRunOnce() throws Exception { + Assertions.assertThat(StartupApplicationListenerExample.counter).isEqualTo(1); + } } \ No newline at end of file From b759bf7c5946a5682a50ed85c65f506cf88e9069 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 14 Aug 2016 08:18:10 +0200 Subject: [PATCH 11/43] Add logging to ApplicationListener example --- .../baeldung/startup/StartupApplicationListenerExample.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java b/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java index 1c784e0c74..32a63f0c1a 100644 --- a/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java +++ b/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java @@ -1,5 +1,6 @@ package org.baeldung.startup; +import org.apache.log4j.Logger; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @@ -7,10 +8,13 @@ import org.springframework.stereotype.Component; @Component public class StartupApplicationListenerExample implements ApplicationListener { + private static final Logger LOG = Logger.getLogger(StartupApplicationListenerExample.class); + public static int counter; @Override public void onApplicationEvent(ContextRefreshedEvent event) { + LOG.info("Increment counter"); counter++; } } From d27db567c16d4f35c230369d678b956ac1c6cdb1 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 14 Aug 2016 08:58:25 +0200 Subject: [PATCH 12/43] Add init-method example --- .../startup/InitMethodExampleBean.java | 24 +++++++++++++++++++ .../src/main/resources/startupConfig.xml | 10 ++++++++ .../startup/SpringStartupXMLConfigTest.java | 21 ++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java create mode 100644 spring-all/src/main/resources/startupConfig.xml create mode 100644 spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java diff --git a/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java new file mode 100644 index 0000000000..cbbe5665e6 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java @@ -0,0 +1,24 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.util.Arrays; + +@Component +@Scope(value = "prototype") +public class InitMethodExampleBean { + + private static final Logger LOG = Logger.getLogger(InitMethodExampleBean.class); + + @Autowired + private Environment environment; + + public void init() { + LOG.info(Arrays.asList(environment.getDefaultProfiles())); + } +} + diff --git a/spring-all/src/main/resources/startupConfig.xml b/spring-all/src/main/resources/startupConfig.xml new file mode 100644 index 0000000000..440fa68e22 --- /dev/null +++ b/spring-all/src/main/resources/startupConfig.xml @@ -0,0 +1,10 @@ + + + + + \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java new file mode 100644 index 0000000000..630f21fb14 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java @@ -0,0 +1,21 @@ +package org.baeldung.startup; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:startupConfig.xml") +public class SpringStartupXMLConfigTest { + + @Autowired + private ApplicationContext ctx; + + @Test + public void whenPostConstruct_shouldLogEnv() throws Exception { + ctx.getBean(InitMethodExampleBean.class); + } +} From 1d511d4336f76a1cc8e239cd67586b06b63d977a Mon Sep 17 00:00:00 2001 From: pared Date: Sun, 14 Aug 2016 15:54:46 +0200 Subject: [PATCH 13/43] Injecting CommitId Into a Spring Bean (#599) * initial * working * added injection test --- .gitmodules | 3 ++ spring-boot/pom.xml | 19 ++++++++++- .../com/baeldung/git/CommitIdApplication.java | 14 ++++++++ .../baeldung/git/CommitInfoController.java | 22 +++++++++++++ .../java/com/baeldung/git/GitInfoDto.java | 25 +++++++++++++++ .../java/com/baeldung/git/CommitIdTest.java | 32 +++++++++++++++++++ testgitrepo | 1 + 7 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 .gitmodules create mode 100644 spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java create mode 100644 spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java create mode 100644 spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java create mode 100644 spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java create mode 160000 testgitrepo diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000000..9c5cdb8f2d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "testgitrepo"] + path = testgitrepo + url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/ diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 2c5304dbf3..66197feacd 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -112,7 +112,24 @@ maven-war-plugin - + + pl.project13.maven + git-commit-id-plugin + 2.2.1 + + + get-the-git-infos + + revision + + + + + true + + + + diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java new file mode 100644 index 0000000000..1f774dbead --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.git; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@PropertySource("classpath:/git.properties") +@SpringBootApplication(scanBasePackages = { "com.baeldung.git"}) +public class CommitIdApplication { + public static void main(String[] args) { + SpringApplication.run(CommitIdApplication.class, args); + } +} + diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java new file mode 100644 index 0000000000..7829339cd6 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java @@ -0,0 +1,22 @@ +package com.baeldung.git; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CommitInfoController { + @Value("${git.commit.message.short}") + private String commitMessage; + + @Value("${git.branch}") + private String branch; + + @Value("${git.commit.id}") + private String commitId; + + @RequestMapping("/commitId") + public GitInfoDto getCommitId() { + return new GitInfoDto(commitMessage, branch, commitId); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java b/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java new file mode 100644 index 0000000000..b8b58f55e8 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java @@ -0,0 +1,25 @@ +package com.baeldung.git; + +public class GitInfoDto { + private String commitMessage; + private String branch; + private String commitId; + + public GitInfoDto(String commitMessage, String branch, String commitId) { + this.commitMessage = commitMessage; + this.branch = branch; + this.commitId = commitId; + } + + public String getCommitMessage() { + return commitMessage; + } + + public String getBranch() { + return branch; + } + + public String getCommitId() { + return commitId; + } +} diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java new file mode 100644 index 0000000000..833cfc1c2a --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -0,0 +1,32 @@ +package com.baeldung.git; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = CommitIdApplication.class) +public class CommitIdTest { + + @Value("${git.commit.message.short}") + private String commitMessage; + + @Value("${git.branch}") + private String branch; + + @Value("${git.commit.id}") + private String commitId; + + @Test + public void shouldInjectGitInfoProperties() throws Exception { + assertThat(commitMessage).isNotNull(); + assertThat(commitMessage).isNotEqualTo("${git.commit.message.short}"); + assertThat(branch).isNotNull(); + assertThat(branch).isNotEqualTo("${git.branch}"); + assertThat(commitId).isNotNull(); + assertThat(commitId).isNotEqualTo("${git.commit.id}"); + } +} \ No newline at end of file diff --git a/testgitrepo b/testgitrepo new file mode 160000 index 0000000000..b3e635b96d --- /dev/null +++ b/testgitrepo @@ -0,0 +1 @@ +Subproject commit b3e635b96d114e25ca1da696acfd881b5fac28a7 From 91d12fe986fe93ce9bd17dff3c55d84a63d075c4 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 14 Aug 2016 16:01:57 +0200 Subject: [PATCH 14/43] Refactor git commit id examples --- .../com/baeldung/git/CommitInfoController.java | 1 + .../java/com/baeldung/git/CommitIdTest.java | 17 +++++++++++------ testgitrepo | 1 - 3 files changed, 12 insertions(+), 7 deletions(-) delete mode 160000 testgitrepo diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java index 7829339cd6..226ba44dd5 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java @@ -6,6 +6,7 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class CommitInfoController { + @Value("${git.commit.message.short}") private String commitMessage; diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java index 833cfc1c2a..a51c668f41 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -22,11 +22,16 @@ public class CommitIdTest { @Test public void shouldInjectGitInfoProperties() throws Exception { - assertThat(commitMessage).isNotNull(); - assertThat(commitMessage).isNotEqualTo("${git.commit.message.short}"); - assertThat(branch).isNotNull(); - assertThat(branch).isNotEqualTo("${git.branch}"); - assertThat(commitId).isNotNull(); - assertThat(commitId).isNotEqualTo("${git.commit.id}"); + assertThat(commitMessage) + .isNotNull() + .isNotEqualTo("${git.commit.message.short}"); + + assertThat(branch) + .isNotNull() + .isNotEqualTo("${git.branch}"); + + assertThat(commitId) + .isNotNull() + .isNotEqualTo("${git.commit.id}"); } } \ No newline at end of file diff --git a/testgitrepo b/testgitrepo deleted file mode 160000 index b3e635b96d..0000000000 --- a/testgitrepo +++ /dev/null @@ -1 +0,0 @@ -Subproject commit b3e635b96d114e25ca1da696acfd881b5fac28a7 From e4bc7713f5bbce8f5ff2b9f62f5f16761f06cd8d Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 07:42:58 +0800 Subject: [PATCH 15/43] Added Embedded Database for persistence --- .../org/baeldung/mock/MockStudentData.java | 39 ------------------ .../baeldung/web/main/PersistenceConfig.java | 3 +- .../rest/StudentDirectoryRestController.java | 10 +++-- .../src/main/resources/application.properties | 3 +- .../src/main/resources/db/sql/data.sql | 40 ++++++++++++++++++- .../src/main/webapp/view/app.js | 3 +- .../web/service/StudentServiceTest.java | 23 ++++++----- 7 files changed, 63 insertions(+), 58 deletions(-) delete mode 100644 spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java deleted file mode 100644 index 2c37317b75..0000000000 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.mock; - -import java.util.ArrayList; -import java.util.List; - -import org.baeldung.web.entity.Student; - -public class MockStudentData { - - private static List studentList = new ArrayList<>(); - -// static { -// studentList.add(new Student("1", "Bryan", "Male", 20)); -// studentList.add(new Student("2", "Ben", "Male", 22)); -// studentList.add(new Student("3", "Lisa", "Female", 24)); -// studentList.add(new Student("4", "Sarah", "Female", 26)); -// studentList.add(new Student("5", "Jay", "Male", 20)); -// studentList.add(new Student("6", "John", "Male", 22)); -// studentList.add(new Student("7", "Jordan", "Male", 24)); -// studentList.add(new Student("8", "Rob", "Male", 26)); -// studentList.add(new Student("9", "Will", "Male", 20)); -// studentList.add(new Student("10", "Shawn", "Male", 22)); -// studentList.add(new Student("11", "Taylor", "Female", 24)); -// studentList.add(new Student("12", "Venus", "Female", 26)); -// studentList.add(new Student("13", "Vince", "Male", 20)); -// studentList.add(new Student("14", "Carol", "Female", 22)); -// studentList.add(new Student("15", "Joana", "Female", 24)); -// studentList.add(new Student("16", "Dion", "Male", 26)); -// studentList.add(new Student("17", "Evans", "Male", 20)); -// studentList.add(new Student("18", "Bart", "Male", 22)); -// studentList.add(new Student("19", "Jenny", "Female", 24)); -// studentList.add(new Student("20", "Kristine", "Female", 26)); -// } - - public static List getMockDataStudents(){ - return studentList; - } - -} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java index 2a50f19907..c20664473b 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java @@ -12,7 +12,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -@EnableJpaRepositories("org.baeldung") +@EnableJpaRepositories("org.baeldung.web.dao") @ComponentScan(basePackages = { "org.baeldung.web" }) @EntityScan("org.baeldung.web.entity") @Configuration @@ -25,7 +25,6 @@ public class PersistenceConfig { @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); EmbeddedDatabase db = builder .setType(EmbeddedDatabaseType.HSQL) diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java index 1aa9390aee..97a9d901c2 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java @@ -1,6 +1,7 @@ package org.baeldung.web.rest; import org.baeldung.web.entity.Student; +import org.baeldung.web.exception.MyResourceNotFoundException; import org.baeldung.web.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; @@ -15,11 +16,14 @@ public class StudentDirectoryRestController { @Autowired private StudentService service; - @RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET, produces = "application/json") - public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size){ + @RequestMapping(value = "/student/get", params = { "page", + "size" }, method = RequestMethod.GET, produces = "application/json") + public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size) { Page resultPage = service.findPaginated(page, size); - + if (page > resultPage.getTotalPages()) { + throw new MyResourceNotFoundException(); + } return resultPage; } diff --git a/spring-rest-angular-pagination/src/main/resources/application.properties b/spring-rest-angular-pagination/src/main/resources/application.properties index 9b4f95a9dc..cfabe45a42 100644 --- a/spring-rest-angular-pagination/src/main/resources/application.properties +++ b/spring-rest-angular-pagination/src/main/resources/application.properties @@ -1,3 +1,4 @@ server.contextPath=/ spring.h2.console.enabled=true -logging.level.org.hibernate.SQL=debug \ No newline at end of file +logging.level.org.hibernate.SQL=trace +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-rest-angular-pagination/src/main/resources/db/sql/data.sql b/spring-rest-angular-pagination/src/main/resources/db/sql/data.sql index d9f6ac610a..418381a681 100644 --- a/spring-rest-angular-pagination/src/main/resources/db/sql/data.sql +++ b/spring-rest-angular-pagination/src/main/resources/db/sql/data.sql @@ -6,4 +6,42 @@ CREATE TABLE student ( ); INSERT INTO student (id,name,gender,age) -VALUES (1,'Bryan', 'Male',20); \ No newline at end of file +VALUES (1,'Bryan', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (2, 'Ben', 'Male', 22); +INSERT INTO student (id,name,gender,age) +VALUES (3,'Lisa', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (4,'Sarah', 'Female',20); +INSERT INTO student (id,name,gender,age) +VALUES (5,'Jay', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (6,'John', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (7,'Jordan', 'Male',24); +INSERT INTO student (id,name,gender,age) +VALUES (8,'Rob', 'Male',26); +INSERT INTO student (id,name,gender,age) +VALUES (9,'Will', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (10,'Shawn', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (11,'Taylor', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (12,'Venus', 'Female',26); +INSERT INTO student (id,name,gender,age) +VALUES (13,'Vince', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (14,'Carol', 'Female',22); +INSERT INTO student (id,name,gender,age) +VALUES (15,'Joana', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (16,'Dion', 'Male',26); +INSERT INTO student (id,name,gender,age) +VALUES (17,'Evans', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (18,'Bart', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (19,'Jenny', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (20,'Kristine', 'Female',26); \ No newline at end of file diff --git a/spring-rest-angular-pagination/src/main/webapp/view/app.js b/spring-rest-angular-pagination/src/main/webapp/view/app.js index 715b667cc9..a41026d2c3 100644 --- a/spring-rest-angular-pagination/src/main/webapp/view/app.js +++ b/spring-rest-angular-pagination/src/main/webapp/view/app.js @@ -19,7 +19,7 @@ app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,Stude enableColumnMenus:false, useExternalPagination: true, columnDefs: [ - { name: 'studentId' }, + { name: 'id' }, { name: 'name' }, { name: 'gender' }, { name: 'age' } @@ -42,6 +42,7 @@ app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,Stude app.service('StudentService',['$http', function ($http) { function getStudents(pageNumber,size) { + pageNumber = pageNumber > 0?pageNumber - 1:0; return $http({ method: 'GET', url: 'student/get?page='+pageNumber+'&size='+size diff --git a/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java index 19fe77a1fd..a9417ad5b8 100644 --- a/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java +++ b/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java @@ -9,9 +9,10 @@ import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import static io.restassured.RestAssured.given; -import static org.hamcrest.core.IsCollectionContaining.hasItems; -import static org.hamcrest.core.IsEqual.equalTo; +import static io.restassured.RestAssured.*; +import static org.hamcrest.core.IsCollectionContaining.*; +import static org.hamcrest.core.Is.*; +import static org.hamcrest.core.IsEqual.*; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @@ -23,28 +24,28 @@ public class StudentServiceTest { @Test public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { - given().params("page", "1", "size", "2").get(ENDPOINT) + given().params("page", "0", "size", "2").get(ENDPOINT) .then() .assertThat().body("content.name", hasItems("Bryan", "Ben")); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectTwoItems() { - given().params("page", "1", "size", "2").get(ENDPOINT) + given().params("page", "0", "size", "2").get(ENDPOINT) .then() .assertThat().body("size", equalTo(2)); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectNumberOfElementsTwo() { - given().params("page", "1", "size", "2").get(ENDPOINT) + given().params("page", "0", "size", "2").get(ENDPOINT) .then() .assertThat().body("numberOfElements", equalTo(2)); } @Test public void givenRequestForStudents_whenResourcesAreRetrievedPaged_thenExpect200() { - given().params("page", "1", "size", "2").get(ENDPOINT) + given().params("page", "0", "size", "2").get(ENDPOINT) .then() .statusCode(200); } @@ -64,15 +65,15 @@ public class StudentServiceTest { } @Test - public void givenRequestForStudents_whenPageIsFive_expectFiveItems() { - given().params("page", "1", "size", "5").get(ENDPOINT) + public void givenRequestForStudents_whenPageSizeIsFive_expectFiveItems() { + given().params("page", "0", "size", "5").get(ENDPOINT) .then() - .body("content.studentId.max()", equalTo("5")); + .body("content.size()", is(5)); } @Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { - given().params("page", "1", "size", "2").get(ENDPOINT) + given().params("page", "0", "size", "2").get(ENDPOINT) .then() .assertThat().body("first", equalTo(true)); } From bc60a8fba1529e103b97d38ec2de70eaf2154e57 Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 08:01:23 +0800 Subject: [PATCH 16/43] clean up service impl --- .../main/java/org/baeldung/web/service/StudentServiceImpl.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java index fd9262cfc6..65b3487c1b 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java @@ -1,7 +1,5 @@ package org.baeldung.web.service; -import javax.transaction.Transactional; - import org.baeldung.web.dao.StudentRepository; import org.baeldung.web.entity.Student; import org.springframework.beans.factory.annotation.Autowired; @@ -10,7 +8,6 @@ import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @Service -@Transactional public class StudentServiceImpl implements StudentService { @Autowired From ac7407e4b3c2f059ffafc546c474be89c1eef28d Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 08:12:08 +0800 Subject: [PATCH 17/43] cleanup code --- .../src/main/java/org/baeldung/web/dao/StudentRepository.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java index 0f468a48f1..b1aafb583a 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java @@ -2,9 +2,7 @@ package org.baeldung.web.dao; import org.baeldung.web.entity.Student; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; -@Repository public interface StudentRepository extends JpaRepository { } From 71637a986f24e10f9207628d3043cd2996b9f712 Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 08:13:39 +0800 Subject: [PATCH 18/43] code cleanup --- .../src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-rest-angular-pagination/src/main/resources/application.properties b/spring-rest-angular-pagination/src/main/resources/application.properties index cfabe45a42..e24db89c8f 100644 --- a/spring-rest-angular-pagination/src/main/resources/application.properties +++ b/spring-rest-angular-pagination/src/main/resources/application.properties @@ -1,4 +1,4 @@ server.contextPath=/ spring.h2.console.enabled=true -logging.level.org.hibernate.SQL=trace +logging.level.org.hibernate.SQL=info spring.jpa.hibernate.ddl-auto=none \ No newline at end of file From ee0ddb2a59c8718c852f8ae6b49eac5121cc1f07 Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 08:44:13 +0800 Subject: [PATCH 19/43] code cleanup --- spring-rest-angular-pagination/pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/spring-rest-angular-pagination/pom.xml b/spring-rest-angular-pagination/pom.xml index db7da64b61..8b8a37cedf 100644 --- a/spring-rest-angular-pagination/pom.xml +++ b/spring-rest-angular-pagination/pom.xml @@ -13,9 +13,6 @@ spring-boot-starter-parent 1.3.3.RELEASE - - 1.12.2.RELEASE - org.springframework.boot From 4fff6716e57380727ea13a1a9015ab682fde4894 Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 13:38:45 +0800 Subject: [PATCH 20/43] remove protocol on javascript imports --- spring-rest-angular-pagination/src/main/webapp/index.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-rest-angular-pagination/src/main/webapp/index.html b/spring-rest-angular-pagination/src/main/webapp/index.html index 56a1273588..a37c1b77fe 100644 --- a/spring-rest-angular-pagination/src/main/webapp/index.html +++ b/spring-rest-angular-pagination/src/main/webapp/index.html @@ -1,9 +1,9 @@ - - - + + + From a9d714c389f81f9d504503858b8706cce044fe8a Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 13:44:56 +0800 Subject: [PATCH 21/43] code format --- .../java/org/baeldung/web/entity/Student.java | 90 +++++++++---------- .../MyResourceNotFoundException.java | 9 +- .../org/baeldung/web/main/Application.java | 3 +- .../baeldung/web/main/PersistenceConfig.java | 29 +++--- .../rest/StudentDirectoryRestController.java | 21 +++-- .../org/baeldung/web/service/IOperations.java | 2 +- .../baeldung/web/service/StudentService.java | 2 +- .../web/service/StudentServiceImpl.java | 14 +-- .../src/main/webapp/WEB-INF/web.xml | 2 +- .../web/service/StudentServiceTest.java | 32 ++----- 10 files changed, 91 insertions(+), 113 deletions(-) diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java index 59a64b04e8..0a0b60d87d 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java @@ -9,61 +9,61 @@ import javax.persistence.Id; @Entity public class Student implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - public Student() { - } + public Student() { + } - public Student(long id, String name, String gender, Integer age) { - super(); - this.id = id; - this.name = name; - this.gender = gender; - this.age = age; - } + public Student(long id, String name, String gender, Integer age) { + super(); + this.id = id; + this.name = name; + this.gender = gender; + this.age = age; + } - @Id - private long id; - @Column(nullable = false) - private String name; - @Column(nullable = false) - private String gender; - @Column(nullable = false) - private Integer age; + @Id + private long id; + @Column(nullable = false) + private String name; + @Column(nullable = false) + private String gender; + @Column(nullable = false) + private Integer age; - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long 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 String getGender() { - return gender; - } + public String getGender() { + return gender; + } - public void setGender(String gender) { - this.gender = gender; - } + public void setGender(String gender) { + this.gender = gender; + } - public Integer getAge() { - return age; - } + public Integer getAge() { + return age; + } - public void setAge(Integer age) { - this.age = age; - } + public void setAge(Integer age) { + this.age = age; + } } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java index 3105d1cb11..740caec59e 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java @@ -3,11 +3,11 @@ package org.baeldung.web.exception; public class MyResourceNotFoundException extends RuntimeException { /** - * - */ - private static final long serialVersionUID = 4088649120307193208L; + * + */ + private static final long serialVersionUID = 4088649120307193208L; - public MyResourceNotFoundException() { + public MyResourceNotFoundException() { super(); } @@ -23,5 +23,4 @@ public class MyResourceNotFoundException extends RuntimeException { super(cause); } - } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java index 15e386a23d..d6fe719311 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java @@ -13,7 +13,6 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Import(PersistenceConfig.class) public class Application extends WebMvcConfigurerAdapter { - public static void main(String[] args) { SpringApplication.run(Application.class, args); } @@ -22,5 +21,5 @@ public class Application extends WebMvcConfigurerAdapter { public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { return new ShallowEtagHeaderFilter(); } - + } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java index c20664473b..df1240f270 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java @@ -14,23 +14,20 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @EnableJpaRepositories("org.baeldung.web.dao") @ComponentScan(basePackages = { "org.baeldung.web" }) -@EntityScan("org.baeldung.web.entity") +@EntityScan("org.baeldung.web.entity") @Configuration public class PersistenceConfig { - - @Bean - public JdbcTemplate getJdbcTemplate() { - return new JdbcTemplate(dataSource()); - } - @Bean - public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder - .setType(EmbeddedDatabaseType.HSQL) - .addScript("db/sql/data.sql") - .build(); - return db; - } - + @Bean + public JdbcTemplate getJdbcTemplate() { + return new JdbcTemplate(dataSource()); + } + + @Bean + public DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL).addScript("db/sql/data.sql").build(); + return db; + } + } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java index 97a9d901c2..dc295a3d97 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java @@ -13,18 +13,17 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class StudentDirectoryRestController { - @Autowired - private StudentService service; + @Autowired + private StudentService service; - @RequestMapping(value = "/student/get", params = { "page", - "size" }, method = RequestMethod.GET, produces = "application/json") - public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size) { + @RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET, produces = "application/json") + public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size) { - Page resultPage = service.findPaginated(page, size); - if (page > resultPage.getTotalPages()) { - throw new MyResourceNotFoundException(); - } - return resultPage; - } + Page resultPage = service.findPaginated(page, size); + if (page > resultPage.getTotalPages()) { + throw new MyResourceNotFoundException(); + } + return resultPage; + } } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java index c124c9e0a0..2176c0bb70 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java @@ -4,6 +4,6 @@ import org.springframework.data.domain.Page; public interface IOperations { - public Page findPaginated(final int page, final int size); + public Page findPaginated(final int page, final int size); } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java index df40bb6b9e..1b194f76e2 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java @@ -2,6 +2,6 @@ package org.baeldung.web.service; import org.baeldung.web.entity.Student; -public interface StudentService extends IOperations{ +public interface StudentService extends IOperations { } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java index 65b3487c1b..c7bcdc5bd5 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java +++ b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java @@ -10,12 +10,12 @@ import org.springframework.stereotype.Service; @Service public class StudentServiceImpl implements StudentService { - @Autowired - private StudentRepository dao; - - @Override - public Page findPaginated(int page, int size) { - return dao.findAll(new PageRequest(page,size)); - } + @Autowired + private StudentRepository dao; + + @Override + public Page findPaginated(int page, int size) { + return dao.findAll(new PageRequest(page, size)); + } } diff --git a/spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml b/spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml index ff65bd6b96..6adf31503f 100644 --- a/spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml @@ -3,7 +3,7 @@ xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> - + index.html diff --git a/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java index a9417ad5b8..1199f15ab3 100644 --- a/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java +++ b/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java @@ -24,58 +24,42 @@ public class StudentServiceTest { @Test public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { - given().params("page", "0", "size", "2").get(ENDPOINT) - .then() - .assertThat().body("content.name", hasItems("Bryan", "Ben")); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("content.name", hasItems("Bryan", "Ben")); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectTwoItems() { - given().params("page", "0", "size", "2").get(ENDPOINT) - .then() - .assertThat().body("size", equalTo(2)); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("size", equalTo(2)); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectNumberOfElementsTwo() { - given().params("page", "0", "size", "2").get(ENDPOINT) - .then() - .assertThat().body("numberOfElements", equalTo(2)); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("numberOfElements", equalTo(2)); } @Test public void givenRequestForStudents_whenResourcesAreRetrievedPaged_thenExpect200() { - given().params("page", "0", "size", "2").get(ENDPOINT) - .then() - .statusCode(200); + given().params("page", "0", "size", "2").get(ENDPOINT).then().statusCode(200); } @Test public void givenRequestForStudents_whenPageOfResourcesAreRetrievedOutOfBounds_thenExpect500() { - given().params("page", "1000", "size", "2").get(ENDPOINT) - .then() - .statusCode(500); + given().params("page", "1000", "size", "2").get(ENDPOINT).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageNotValid_thenExpect500() { - given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(ENDPOINT) - .then() - .statusCode(500); + given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(ENDPOINT).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageSizeIsFive_expectFiveItems() { - given().params("page", "0", "size", "5").get(ENDPOINT) - .then() - .body("content.size()", is(5)); + given().params("page", "0", "size", "5").get(ENDPOINT).then().body("content.size()", is(5)); } @Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { - given().params("page", "0", "size", "2").get(ENDPOINT) - .then() - .assertThat().body("first", equalTo(true)); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("first", equalTo(true)); } } From 06236434b32f259845cef504003611710849c320 Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 13:51:15 +0800 Subject: [PATCH 22/43] - module name is renamed to "spring-rest-angular" - code formatted using formatter provided --- .../src/main/webapp/index.html | 14 --- .../bin}/pom.xml | 4 +- .../src/main/resources/application.properties | 0 .../bin}/src/main/resources/db/sql/data.sql | 0 .../bin}/src/main/webapp/WEB-INF/web.xml | 0 .../bin/src/main/webapp/index.html | 17 ++++ .../bin}/src/main/webapp/view/app.js | 0 spring-rest-angular/pom.xml | 95 +++++++++++++++++++ .../baeldung/web/dao/StudentRepository.java | 0 .../java/org/baeldung/web/entity/Student.java | 0 .../MyResourceNotFoundException.java | 0 .../org/baeldung/web/main/Application.java | 0 .../baeldung/web/main/PersistenceConfig.java | 0 .../rest/StudentDirectoryRestController.java | 0 .../org/baeldung/web/service/IOperations.java | 0 .../baeldung/web/service/StudentService.java | 0 .../web/service/StudentServiceImpl.java | 0 .../src/main/resources/application.properties | 4 + .../src/main/resources/db/sql/data.sql | 47 +++++++++ .../src/main/webapp/WEB-INF/web.xml | 11 +++ .../src/main/webapp/index.html | 17 ++++ .../src/main/webapp/view/app.js | 56 +++++++++++ .../web/service/StudentServiceTest.java | 0 23 files changed, 249 insertions(+), 16 deletions(-) delete mode 100644 spring-rest-angular-pagination/src/main/webapp/index.html rename {spring-rest-angular-pagination => spring-rest-angular/bin}/pom.xml (96%) rename {spring-rest-angular-pagination => spring-rest-angular/bin}/src/main/resources/application.properties (100%) rename {spring-rest-angular-pagination => spring-rest-angular/bin}/src/main/resources/db/sql/data.sql (100%) rename {spring-rest-angular-pagination => spring-rest-angular/bin}/src/main/webapp/WEB-INF/web.xml (100%) create mode 100644 spring-rest-angular/bin/src/main/webapp/index.html rename {spring-rest-angular-pagination => spring-rest-angular/bin}/src/main/webapp/view/app.js (100%) create mode 100644 spring-rest-angular/pom.xml rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/dao/StudentRepository.java (100%) rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/entity/Student.java (100%) rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java (100%) rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/main/Application.java (100%) rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/main/PersistenceConfig.java (100%) rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java (100%) rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/service/IOperations.java (100%) rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/service/StudentService.java (100%) rename {spring-rest-angular-pagination => spring-rest-angular}/src/main/java/org/baeldung/web/service/StudentServiceImpl.java (100%) create mode 100644 spring-rest-angular/src/main/resources/application.properties create mode 100644 spring-rest-angular/src/main/resources/db/sql/data.sql create mode 100644 spring-rest-angular/src/main/webapp/WEB-INF/web.xml create mode 100644 spring-rest-angular/src/main/webapp/index.html create mode 100644 spring-rest-angular/src/main/webapp/view/app.js rename {spring-rest-angular-pagination => spring-rest-angular}/src/test/java/org/baeldung/web/service/StudentServiceTest.java (100%) diff --git a/spring-rest-angular-pagination/src/main/webapp/index.html b/spring-rest-angular-pagination/src/main/webapp/index.html deleted file mode 100644 index a37c1b77fe..0000000000 --- a/spring-rest-angular-pagination/src/main/webapp/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - -
-
-
- - \ No newline at end of file diff --git a/spring-rest-angular-pagination/pom.xml b/spring-rest-angular/bin/pom.xml similarity index 96% rename from spring-rest-angular-pagination/pom.xml rename to spring-rest-angular/bin/pom.xml index 8b8a37cedf..331c9a644c 100644 --- a/spring-rest-angular-pagination/pom.xml +++ b/spring-rest-angular/bin/pom.xml @@ -3,8 +3,8 @@ 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"> 4.0.0 - angular-spring-rest-sample - angular-spring-rest-sample + spring-rest-angular + spring-rest-angular com.baeldung 1.0 war diff --git a/spring-rest-angular-pagination/src/main/resources/application.properties b/spring-rest-angular/bin/src/main/resources/application.properties similarity index 100% rename from spring-rest-angular-pagination/src/main/resources/application.properties rename to spring-rest-angular/bin/src/main/resources/application.properties diff --git a/spring-rest-angular-pagination/src/main/resources/db/sql/data.sql b/spring-rest-angular/bin/src/main/resources/db/sql/data.sql similarity index 100% rename from spring-rest-angular-pagination/src/main/resources/db/sql/data.sql rename to spring-rest-angular/bin/src/main/resources/db/sql/data.sql diff --git a/spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml b/spring-rest-angular/bin/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml rename to spring-rest-angular/bin/src/main/webapp/WEB-INF/web.xml diff --git a/spring-rest-angular/bin/src/main/webapp/index.html b/spring-rest-angular/bin/src/main/webapp/index.html new file mode 100644 index 0000000000..49e0d6393d --- /dev/null +++ b/spring-rest-angular/bin/src/main/webapp/index.html @@ -0,0 +1,17 @@ + + + + + + + + + +
+
+
+ + \ No newline at end of file diff --git a/spring-rest-angular-pagination/src/main/webapp/view/app.js b/spring-rest-angular/bin/src/main/webapp/view/app.js similarity index 100% rename from spring-rest-angular-pagination/src/main/webapp/view/app.js rename to spring-rest-angular/bin/src/main/webapp/view/app.js diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml new file mode 100644 index 0000000000..331c9a644c --- /dev/null +++ b/spring-rest-angular/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + spring-rest-angular + spring-rest-angular + com.baeldung + 1.0 + war + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-commons + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + + + org.springframework + spring-test + test + + + org.apache.commons + commons-lang3 + 3.3 + + + com.google.guava + guava + 19.0 + + + junit + junit + test + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + spring-mock-mvc + 3.0.0 + test + + + + angular-spring-rest-sample + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + + + diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java b/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/dao/StudentRepository.java rename to spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java b/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/entity/Student.java rename to spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java rename to spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java rename to spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/PersistenceConfig.java rename to spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java rename to spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java rename to spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java rename to spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java similarity index 100% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java rename to spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java diff --git a/spring-rest-angular/src/main/resources/application.properties b/spring-rest-angular/src/main/resources/application.properties new file mode 100644 index 0000000000..e24db89c8f --- /dev/null +++ b/spring-rest-angular/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.contextPath=/ +spring.h2.console.enabled=true +logging.level.org.hibernate.SQL=info +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-rest-angular/src/main/resources/db/sql/data.sql b/spring-rest-angular/src/main/resources/db/sql/data.sql new file mode 100644 index 0000000000..418381a681 --- /dev/null +++ b/spring-rest-angular/src/main/resources/db/sql/data.sql @@ -0,0 +1,47 @@ +CREATE TABLE student ( + id INTEGER PRIMARY KEY, + name VARCHAR(30), + gender VARCHAR(10), + age INTEGER +); + +INSERT INTO student (id,name,gender,age) +VALUES (1,'Bryan', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (2, 'Ben', 'Male', 22); +INSERT INTO student (id,name,gender,age) +VALUES (3,'Lisa', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (4,'Sarah', 'Female',20); +INSERT INTO student (id,name,gender,age) +VALUES (5,'Jay', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (6,'John', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (7,'Jordan', 'Male',24); +INSERT INTO student (id,name,gender,age) +VALUES (8,'Rob', 'Male',26); +INSERT INTO student (id,name,gender,age) +VALUES (9,'Will', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (10,'Shawn', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (11,'Taylor', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (12,'Venus', 'Female',26); +INSERT INTO student (id,name,gender,age) +VALUES (13,'Vince', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (14,'Carol', 'Female',22); +INSERT INTO student (id,name,gender,age) +VALUES (15,'Joana', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (16,'Dion', 'Male',26); +INSERT INTO student (id,name,gender,age) +VALUES (17,'Evans', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (18,'Bart', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (19,'Jenny', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (20,'Kristine', 'Female',26); \ No newline at end of file diff --git a/spring-rest-angular/src/main/webapp/WEB-INF/web.xml b/spring-rest-angular/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..6adf31503f --- /dev/null +++ b/spring-rest-angular/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + + + index.html + + + \ No newline at end of file diff --git a/spring-rest-angular/src/main/webapp/index.html b/spring-rest-angular/src/main/webapp/index.html new file mode 100644 index 0000000000..49e0d6393d --- /dev/null +++ b/spring-rest-angular/src/main/webapp/index.html @@ -0,0 +1,17 @@ + + + + + + + + + +
+
+
+ + \ No newline at end of file diff --git a/spring-rest-angular/src/main/webapp/view/app.js b/spring-rest-angular/src/main/webapp/view/app.js new file mode 100644 index 0000000000..a41026d2c3 --- /dev/null +++ b/spring-rest-angular/src/main/webapp/view/app.js @@ -0,0 +1,56 @@ +var app = angular.module('app', ['ui.grid','ui.grid.pagination']); + +app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,StudentService) { + var paginationOptions = { + pageNumber: 1, + pageSize: 5, + sort: null + }; + + StudentService.getStudents(paginationOptions.pageNumber, + paginationOptions.pageSize).success(function(data){ + $scope.gridOptions.data = data.content; + $scope.gridOptions.totalItems = data.totalElements; + }); + + $scope.gridOptions = { + paginationPageSizes: [5, 10, 20], + paginationPageSize: paginationOptions.pageSize, + enableColumnMenus:false, + useExternalPagination: true, + columnDefs: [ + { name: 'id' }, + { name: 'name' }, + { name: 'gender' }, + { name: 'age' } + ], + onRegisterApi: function(gridApi) { + $scope.gridApi = gridApi; + gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) { + paginationOptions.pageNumber = newPage; + paginationOptions.pageSize = pageSize; + StudentService.getStudents(newPage,pageSize).success(function(data){ + $scope.gridOptions.data = data.content; + $scope.gridOptions.totalItems = data.totalElements; + }); + }); + } + }; + +}]); + +app.service('StudentService',['$http', function ($http) { + + function getStudents(pageNumber,size) { + pageNumber = pageNumber > 0?pageNumber - 1:0; + return $http({ + method: 'GET', + url: 'student/get?page='+pageNumber+'&size='+size + }); + } + + return { + getStudents:getStudents + }; + +}]); \ No newline at end of file diff --git a/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java similarity index 100% rename from spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java rename to spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java From 5663f044c6ce52dae4dbcd3e3f811d190b8fb887 Mon Sep 17 00:00:00 2001 From: jesus-dayo Date: Mon, 15 Aug 2016 13:59:21 +0800 Subject: [PATCH 23/43] remove bin folder --- spring-rest-angular/bin/pom.xml | 95 ------------------- .../src/main/resources/application.properties | 4 - .../bin/src/main/resources/db/sql/data.sql | 47 --------- .../bin/src/main/webapp/WEB-INF/web.xml | 11 --- .../bin/src/main/webapp/index.html | 17 ---- .../bin/src/main/webapp/view/app.js | 56 ----------- 6 files changed, 230 deletions(-) delete mode 100644 spring-rest-angular/bin/pom.xml delete mode 100644 spring-rest-angular/bin/src/main/resources/application.properties delete mode 100644 spring-rest-angular/bin/src/main/resources/db/sql/data.sql delete mode 100644 spring-rest-angular/bin/src/main/webapp/WEB-INF/web.xml delete mode 100644 spring-rest-angular/bin/src/main/webapp/index.html delete mode 100644 spring-rest-angular/bin/src/main/webapp/view/app.js diff --git a/spring-rest-angular/bin/pom.xml b/spring-rest-angular/bin/pom.xml deleted file mode 100644 index 331c9a644c..0000000000 --- a/spring-rest-angular/bin/pom.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - 4.0.0 - spring-rest-angular - spring-rest-angular - com.baeldung - 1.0 - war - - org.springframework.boot - spring-boot-starter-parent - 1.3.3.RELEASE - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.data - spring-data-commons - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hsqldb - hsqldb - runtime - - - org.springframework - spring-test - test - - - org.apache.commons - commons-lang3 - 3.3 - - - com.google.guava - guava - 19.0 - - - junit - junit - test - - - io.rest-assured - rest-assured - 3.0.0 - test - - - io.rest-assured - spring-mock-mvc - 3.0.0 - test - - - - angular-spring-rest-sample - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-war-plugin - - false - - - - - - diff --git a/spring-rest-angular/bin/src/main/resources/application.properties b/spring-rest-angular/bin/src/main/resources/application.properties deleted file mode 100644 index e24db89c8f..0000000000 --- a/spring-rest-angular/bin/src/main/resources/application.properties +++ /dev/null @@ -1,4 +0,0 @@ -server.contextPath=/ -spring.h2.console.enabled=true -logging.level.org.hibernate.SQL=info -spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-rest-angular/bin/src/main/resources/db/sql/data.sql b/spring-rest-angular/bin/src/main/resources/db/sql/data.sql deleted file mode 100644 index 418381a681..0000000000 --- a/spring-rest-angular/bin/src/main/resources/db/sql/data.sql +++ /dev/null @@ -1,47 +0,0 @@ -CREATE TABLE student ( - id INTEGER PRIMARY KEY, - name VARCHAR(30), - gender VARCHAR(10), - age INTEGER -); - -INSERT INTO student (id,name,gender,age) -VALUES (1,'Bryan', 'Male',20); -INSERT INTO student (id,name,gender,age) -VALUES (2, 'Ben', 'Male', 22); -INSERT INTO student (id,name,gender,age) -VALUES (3,'Lisa', 'Female',24); -INSERT INTO student (id,name,gender,age) -VALUES (4,'Sarah', 'Female',20); -INSERT INTO student (id,name,gender,age) -VALUES (5,'Jay', 'Male',20); -INSERT INTO student (id,name,gender,age) -VALUES (6,'John', 'Male',22); -INSERT INTO student (id,name,gender,age) -VALUES (7,'Jordan', 'Male',24); -INSERT INTO student (id,name,gender,age) -VALUES (8,'Rob', 'Male',26); -INSERT INTO student (id,name,gender,age) -VALUES (9,'Will', 'Male',20); -INSERT INTO student (id,name,gender,age) -VALUES (10,'Shawn', 'Male',22); -INSERT INTO student (id,name,gender,age) -VALUES (11,'Taylor', 'Female',24); -INSERT INTO student (id,name,gender,age) -VALUES (12,'Venus', 'Female',26); -INSERT INTO student (id,name,gender,age) -VALUES (13,'Vince', 'Male',20); -INSERT INTO student (id,name,gender,age) -VALUES (14,'Carol', 'Female',22); -INSERT INTO student (id,name,gender,age) -VALUES (15,'Joana', 'Female',24); -INSERT INTO student (id,name,gender,age) -VALUES (16,'Dion', 'Male',26); -INSERT INTO student (id,name,gender,age) -VALUES (17,'Evans', 'Male',20); -INSERT INTO student (id,name,gender,age) -VALUES (18,'Bart', 'Male',22); -INSERT INTO student (id,name,gender,age) -VALUES (19,'Jenny', 'Female',24); -INSERT INTO student (id,name,gender,age) -VALUES (20,'Kristine', 'Female',26); \ No newline at end of file diff --git a/spring-rest-angular/bin/src/main/webapp/WEB-INF/web.xml b/spring-rest-angular/bin/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 6adf31503f..0000000000 --- a/spring-rest-angular/bin/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - index.html - - - \ No newline at end of file diff --git a/spring-rest-angular/bin/src/main/webapp/index.html b/spring-rest-angular/bin/src/main/webapp/index.html deleted file mode 100644 index 49e0d6393d..0000000000 --- a/spring-rest-angular/bin/src/main/webapp/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - -
-
-
- - \ No newline at end of file diff --git a/spring-rest-angular/bin/src/main/webapp/view/app.js b/spring-rest-angular/bin/src/main/webapp/view/app.js deleted file mode 100644 index a41026d2c3..0000000000 --- a/spring-rest-angular/bin/src/main/webapp/view/app.js +++ /dev/null @@ -1,56 +0,0 @@ -var app = angular.module('app', ['ui.grid','ui.grid.pagination']); - -app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,StudentService) { - var paginationOptions = { - pageNumber: 1, - pageSize: 5, - sort: null - }; - - StudentService.getStudents(paginationOptions.pageNumber, - paginationOptions.pageSize).success(function(data){ - $scope.gridOptions.data = data.content; - $scope.gridOptions.totalItems = data.totalElements; - }); - - $scope.gridOptions = { - paginationPageSizes: [5, 10, 20], - paginationPageSize: paginationOptions.pageSize, - enableColumnMenus:false, - useExternalPagination: true, - columnDefs: [ - { name: 'id' }, - { name: 'name' }, - { name: 'gender' }, - { name: 'age' } - ], - onRegisterApi: function(gridApi) { - $scope.gridApi = gridApi; - gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) { - paginationOptions.pageNumber = newPage; - paginationOptions.pageSize = pageSize; - StudentService.getStudents(newPage,pageSize).success(function(data){ - $scope.gridOptions.data = data.content; - $scope.gridOptions.totalItems = data.totalElements; - }); - }); - } - }; - -}]); - -app.service('StudentService',['$http', function ($http) { - - function getStudents(pageNumber,size) { - pageNumber = pageNumber > 0?pageNumber - 1:0; - return $http({ - method: 'GET', - url: 'student/get?page='+pageNumber+'&size='+size - }); - } - - return { - getStudents:getStudents - }; - -}]); \ No newline at end of file From d7551dd761c8d0493d615d67c6046eab318152e5 Mon Sep 17 00:00:00 2001 From: pared Date: Mon, 15 Aug 2016 11:16:28 +0200 Subject: [PATCH 24/43] Commit id plugin (#606) * initial * working * added injection test * [COMMIT-ID-PLUGIN] Add default value for testcheck * pivovarit review refactor * pivovarit review refactor --- .../java/com/baeldung/git/CommitIdTest.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java index a51c668f41..b06b511bb4 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -7,31 +7,32 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) @ContextConfiguration(classes = CommitIdApplication.class) public class CommitIdTest { - @Value("${git.commit.message.short}") + private static final String UNKNOWN_STATUS = "UNKNOWN"; + + @Value("${git.commit.message.short:#{'UNKNOWN'}}") private String commitMessage; - @Value("${git.branch}") + @Value("${git.branch:#{'UNKNOWN'}") private String branch; - @Value("${git.commit.id}") + @Value("${git.commit.id:#{'UNKNOWN'}") private String commitId; @Test public void shouldInjectGitInfoProperties() throws Exception { + assertThat(commitMessage) - .isNotNull() - .isNotEqualTo("${git.commit.message.short}"); + .isNotEqualTo(UNKNOWN_STATUS); assertThat(branch) - .isNotNull() - .isNotEqualTo("${git.branch}"); + .isNotEqualTo(UNKNOWN_STATUS); assertThat(commitId) - .isNotNull() - .isNotEqualTo("${git.commit.id}"); + .isNotEqualTo(UNKNOWN_STATUS); } } \ No newline at end of file From ad9986874f7ee832548f22f26e3c72ac553a5728 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 15 Aug 2016 11:33:21 +0200 Subject: [PATCH 25/43] Refactor CommitId examples --- .../com/baeldung/git/CommitIdApplication.java | 2 +- .../src/main/resources/application.properties | 4 +++- .../java/com/baeldung/git/CommitIdTest.java | 18 ++++++++++++------ 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java index 1f774dbead..b535c8bd4a 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -4,7 +4,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.PropertySource; -@PropertySource("classpath:/git.properties") +@PropertySource(value = "classpath:/git.properties", ignoreResourceNotFound = true) @SpringBootApplication(scanBasePackages = { "com.baeldung.git"}) public class CommitIdApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 78bcf4cc05..d30045d1dc 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -26,4 +26,6 @@ info.app.version=1.0.0 ## Spring Security Configurations security.user.name=admin1 security.user.password=secret1 -management.security.role=SUPERUSER \ No newline at end of file +management.security.role=SUPERUSER + +logging.level.org.springframework=INFO \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java index b06b511bb4..cddc0d60bc 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -2,6 +2,8 @@ package com.baeldung.git; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @@ -12,27 +14,31 @@ import static org.assertj.core.api.Assertions.assertThat; @ContextConfiguration(classes = CommitIdApplication.class) public class CommitIdTest { - private static final String UNKNOWN_STATUS = "UNKNOWN"; + private static final Logger LOG = LoggerFactory.getLogger(CommitIdTest.class); @Value("${git.commit.message.short:#{'UNKNOWN'}}") private String commitMessage; - @Value("${git.branch:#{'UNKNOWN'}") + @Value("${git.branch:#{'UNKNOWN'}}") private String branch; - @Value("${git.commit.id:#{'UNKNOWN'}") + @Value("${git.commit.id:#{'UNKNOWN'}}") private String commitId; @Test public void shouldInjectGitInfoProperties() throws Exception { + LOG.info(commitId); + LOG.info(commitMessage); + LOG.info(branch); + assertThat(commitMessage) - .isNotEqualTo(UNKNOWN_STATUS); + .isNotEqualTo("UNKNOWN"); assertThat(branch) - .isNotEqualTo(UNKNOWN_STATUS); + .isNotEqualTo("UNKNOWN"); assertThat(commitId) - .isNotEqualTo(UNKNOWN_STATUS); + .isNotEqualTo("UNKNOWN"); } } \ No newline at end of file From c2e999f09fb104b9ce575f9bd59c2f91398fbbfa Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 15 Aug 2016 11:47:01 +0200 Subject: [PATCH 26/43] Fix GitCommitId example --- .../com/baeldung/git/CommitIdApplication.java | 16 ++++++++++++++-- .../test/java/com/baeldung/git/CommitIdTest.java | 8 ++++---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java index b535c8bd4a..95abbf894c 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -2,13 +2,25 @@ package com.baeldung.git; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.core.io.ClassPathResource; -@PropertySource(value = "classpath:/git.properties", ignoreResourceNotFound = true) @SpringBootApplication(scanBasePackages = { "com.baeldung.git"}) public class CommitIdApplication { public static void main(String[] args) { SpringApplication.run(CommitIdApplication.class, args); } + + @Bean + public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { + PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer(); + c.setLocation(new ClassPathResource("git.properties")); + c.setIgnoreResourceNotFound(true); + c.setIgnoreUnresolvablePlaceholders(true); + return c; + } } + + diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java index cddc0d60bc..e16791881e 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -16,17 +16,17 @@ public class CommitIdTest { private static final Logger LOG = LoggerFactory.getLogger(CommitIdTest.class); - @Value("${git.commit.message.short:#{'UNKNOWN'}}") + @Value("${git.commit.message.short:UNKNOWN}") private String commitMessage; - @Value("${git.branch:#{'UNKNOWN'}}") + @Value("${git.branch:UNKNOWN}") private String branch; - @Value("${git.commit.id:#{'UNKNOWN'}}") + @Value("${git.commit.id:UNKNOWN}") private String commitId; @Test - public void shouldInjectGitInfoProperties() throws Exception { + public void whenInjecting_shouldDisplay() throws Exception { LOG.info(commitId); LOG.info(commitMessage); From 59cbbd68d252a3a039480aacfe3b58eb7c901a97 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 15 Aug 2016 11:51:49 +0200 Subject: [PATCH 27/43] Remove redundant module entry --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index d797240169..5a327770a4 100644 --- a/pom.xml +++ b/pom.xml @@ -82,7 +82,6 @@ spring-quartz spring-spel spring-rest - spring-rest-angular-pagination spring-rest-docs spring-cloud-config From 35f53b91758adfad23be7a779206c2b1231b2cb9 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 15 Aug 2016 12:07:24 +0200 Subject: [PATCH 28/43] Add spring-rest-angular module --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 5a327770a4..3f4489fc4c 100644 --- a/pom.xml +++ b/pom.xml @@ -82,6 +82,7 @@ spring-quartz spring-spel spring-rest + spring-rest-angular spring-rest-docs spring-cloud-config From 9549b15e49091091c88b90d77205776d1a4cd830 Mon Sep 17 00:00:00 2001 From: pared Date: Mon, 15 Aug 2016 16:56:36 +0200 Subject: [PATCH 29/43] Added logback.xml to spring-boot, log level: INFO (#609) * initial * working * added injection test * [COMMIT-ID-PLUGIN] Add default value for testcheck * pivovarit review refactor * pivovarit review refactor * add logback, log level: INFO --- spring-boot/src/main/resources/logback.xml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 spring-boot/src/main/resources/logback.xml diff --git a/spring-boot/src/main/resources/logback.xml b/spring-boot/src/main/resources/logback.xml new file mode 100644 index 0000000000..78913ee76f --- /dev/null +++ b/spring-boot/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + \ No newline at end of file From 208fcaa9152a520ce76c4cc020b0b9c1d9564f16 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 15 Aug 2016 17:44:19 +0200 Subject: [PATCH 30/43] Add AllStrategies combined example --- .../startup/AllStrategiesExampleBean.java | 33 +++++++++++++++++++ .../startup/InitMethodExampleBean.java | 4 --- .../src/main/resources/startupConfig.xml | 6 ++++ .../startup/SpringStartupXMLConfigTest.java | 5 +++ 4 files changed, 44 insertions(+), 4 deletions(-) create mode 100644 spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java diff --git a/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java new file mode 100644 index 0000000000..d4334437f7 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java @@ -0,0 +1,33 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +@Scope(value = "prototype") +public class AllStrategiesExampleBean implements InitializingBean { + + private static final Logger LOG = Logger.getLogger(AllStrategiesExampleBean.class); + + public AllStrategiesExampleBean() { + LOG.info("Constructor"); + } + + @Override + public void afterPropertiesSet() throws Exception { + LOG.info("InitializingBean"); + } + + @PostConstruct + public void postConstruct() { + LOG.info("PostConstruct"); + } + + public void init() { + LOG.info("init-method"); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java index cbbe5665e6..ea0a85d261 100644 --- a/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java @@ -2,14 +2,10 @@ package org.baeldung.startup; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; import java.util.Arrays; -@Component -@Scope(value = "prototype") public class InitMethodExampleBean { private static final Logger LOG = Logger.getLogger(InitMethodExampleBean.class); diff --git a/spring-all/src/main/resources/startupConfig.xml b/spring-all/src/main/resources/startupConfig.xml index 440fa68e22..8226665a90 100644 --- a/spring-all/src/main/resources/startupConfig.xml +++ b/spring-all/src/main/resources/startupConfig.xml @@ -5,6 +5,12 @@ + + + \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java index 630f21fb14..19a35bb92b 100644 --- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java @@ -18,4 +18,9 @@ public class SpringStartupXMLConfigTest { public void whenPostConstruct_shouldLogEnv() throws Exception { ctx.getBean(InitMethodExampleBean.class); } + + @Test + public void whenAllStrategies_shouldLogOrder() throws Exception { + ctx.getBean(AllStrategiesExampleBean.class); + } } From c17d48fdb2e41b428e1f10be1e2603fd9a3c3f00 Mon Sep 17 00:00:00 2001 From: maibin Date: Mon, 15 Aug 2016 09:58:06 -0700 Subject: [PATCH 31/43] LoggerInterceptor plus tests (#610) * Expression-Based Access Control PermitAll, hasRole, hasAnyRole etc. I modified classes regards to Security * Added test cases for Spring Security Expressions * Handler Interceptor - logging example * Test for logger interceptor * Removed conflicted part --- .../interceptor/LoggerInterceptorTest.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java new file mode 100644 index 0000000000..8aa9162edc --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java @@ -0,0 +1,51 @@ +package org.baeldung.web.interceptor; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityWithoutCsrfConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +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.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@Transactional +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +public class LoggerInterceptorTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @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()); + } + +} From 3949ff343cf3831af24cf0d8cce2ae833493a472 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 15 Aug 2016 18:58:47 +0200 Subject: [PATCH 32/43] Remove annotations --- .../java/org/baeldung/startup/AllStrategiesExampleBean.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java index d4334437f7..64af2d520c 100644 --- a/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java @@ -2,13 +2,9 @@ package org.baeldung.startup; import org.apache.log4j.Logger; import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; -@Component -@Scope(value = "prototype") public class AllStrategiesExampleBean implements InitializingBean { private static final Logger LOG = Logger.getLogger(AllStrategiesExampleBean.class); From 2f331cecf808b7232818d91101d50faddaf25fa0 Mon Sep 17 00:00:00 2001 From: Alex Theedom Date: Mon, 15 Aug 2016 18:47:23 +0100 Subject: [PATCH 33/43] Minor changes after review --- .../java/org/baeldung/startup/AllStrategiesExampleBean.java | 4 ++++ .../java/org/baeldung/startup/InitMethodExampleBean.java | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java index 64af2d520c..d4334437f7 100644 --- a/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java @@ -2,9 +2,13 @@ package org.baeldung.startup; import org.apache.log4j.Logger; import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; +@Component +@Scope(value = "prototype") public class AllStrategiesExampleBean implements InitializingBean { private static final Logger LOG = Logger.getLogger(AllStrategiesExampleBean.class); diff --git a/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java index ea0a85d261..cea6b026d6 100644 --- a/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java +++ b/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java @@ -2,10 +2,14 @@ package org.baeldung.startup; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; import java.util.Arrays; +@Component +@Scope(value = "prototype") public class InitMethodExampleBean { private static final Logger LOG = Logger.getLogger(InitMethodExampleBean.class); @@ -17,4 +21,3 @@ public class InitMethodExampleBean { LOG.info(Arrays.asList(environment.getDefaultProfiles())); } } - From 5195a4310eb959cca6643dafeeed4e779f83f556 Mon Sep 17 00:00:00 2001 From: Sergey Petunin Date: Tue, 16 Aug 2016 03:16:19 +0600 Subject: [PATCH 34/43] Added test for the Guide to CompletableFuture (#611) --- .../CompletableFutureTest.java | 196 ++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java new file mode 100644 index 0000000000..47700f60c7 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java @@ -0,0 +1,196 @@ +package com.baeldung.completablefuture; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class CompletableFutureTest { + + @Test + public void whenRunningCompletableFutureAsyncronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { + + Future completableFuture = calculateAsync(); + + String result = completableFuture.get(); + assertEquals("Hello", result); + + } + + public Future calculateAsync() throws InterruptedException { + CompletableFuture completableFuture = new CompletableFuture<>(); + + Executors.newCachedThreadPool().submit(() -> { + Thread.sleep(500); + completableFuture.complete("Hello"); + return null; + }); + + return completableFuture; + } + + @Test + public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException { + + Future completableFuture = CompletableFuture.completedFuture("Hello"); + + String result = completableFuture.get(); + assertEquals("Hello", result); + + } + + @Test + public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException { + + CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello"); + + assertEquals("Hello", future.get()); + + } + + @Test + public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); + + future.get(); + + } + + @Test + public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); + + future.get(); + + } + + @Test + public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenApply(s -> s + " World"); + + assertEquals("Hello World", future.get()); + + } + + @Test + public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + + assertEquals("Hello World", completableFuture.get()); + + } + + @Test + public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCombine(CompletableFuture.supplyAsync(() -> " World"), + (s1, s2) -> s1 + s2); + + assertEquals("Hello World", completableFuture.get()); + + } + + @Test + public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { + + CompletableFuture.supplyAsync(() -> "Hello") + .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), + (s1, s2) -> System.out.println(s1 + s2)); + + } + + @Test + public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException { + + CompletableFuture future1 = CompletableFuture.supplyAsync(() -> "Hello"); + CompletableFuture future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); + CompletableFuture future3 = CompletableFuture.supplyAsync(() -> "World"); + + CompletableFuture combinedFuture = CompletableFuture.allOf(future1, future2, future3); + + // ... + + combinedFuture.get(); + + assertTrue(future1.isDone()); + assertTrue(future2.isDone()); + assertTrue(future3.isDone()); + + String combined = Stream.of(future1, future2, future3) + .map(CompletableFuture::join) + .collect(Collectors.joining(" ")); + + assertEquals("Hello Beautiful World", combined); + + } + + @Test + public void whenFutureThrows_thenHandleMethodRecievesException() throws ExecutionException, InterruptedException { + + String name = null; + + // ... + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { + if (name == null) { + throw new RuntimeException("Computation error!"); + } + return "Hello, " + name; + }).handle((s, t) -> { + if (s != null) { + return s; + } else { + return "Hello, Stranger!"; + } + }); + + assertEquals("Hello, Stranger!", completableFuture.get()); + + } + + @Test(expected = ExecutionException.class) + public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = new CompletableFuture<>(); + + // ... + + completableFuture.completeExceptionally(new RuntimeException("Calculation failed!")); + + // ... + + completableFuture.get(); + + } + + @Test + public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenApplyAsync(s -> s + " World"); + + assertEquals("Hello World", future.get()); + + } + +} From 0bb096672323c5e1bb15db2a2b7b3781d14ff4e8 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 15 Aug 2016 23:20:39 +0200 Subject: [PATCH 35/43] Refactor CompletableFutureTest --- .../completablefuture/CompletableFutureTest.java | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java index 47700f60c7..806bca5461 100644 --- a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java +++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java @@ -1,5 +1,7 @@ package com.baeldung.completablefuture; +import org.junit.Test; + import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; @@ -7,15 +9,13 @@ import java.util.concurrent.Future; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.junit.Test; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class CompletableFutureTest { @Test - public void whenRunningCompletableFutureAsyncronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { + public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { Future completableFuture = calculateAsync(); @@ -144,7 +144,7 @@ public class CompletableFutureTest { } @Test - public void whenFutureThrows_thenHandleMethodRecievesException() throws ExecutionException, InterruptedException { + public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException { String name = null; @@ -155,13 +155,7 @@ public class CompletableFutureTest { throw new RuntimeException("Computation error!"); } return "Hello, " + name; - }).handle((s, t) -> { - if (s != null) { - return s; - } else { - return "Hello, Stranger!"; - } - }); + }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); assertEquals("Hello, Stranger!", completableFuture.get()); From 6aadd2d8ffba78f46d571b8199c6106fdd662228 Mon Sep 17 00:00:00 2001 From: Alex Theedom Date: Mon, 15 Aug 2016 22:48:27 +0100 Subject: [PATCH 36/43] Minor changes after review --- hystrix/pom.xml | 40 ++++++++++------- .../com/baeldung/hystrix/HystrixAspect.java | 44 ++++++++++--------- .../src/main/resources/application.properties | 2 +- .../baeldung/hystrix/HystrixTimeoutTest.java | 14 +++--- .../SpringAndHystrixIntegrationTest.java | 32 ++++++++++++++ 5 files changed, 87 insertions(+), 45 deletions(-) create mode 100644 hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java diff --git a/hystrix/pom.xml b/hystrix/pom.xml index ef443ebd15..7867bbb955 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -12,9 +12,9 @@ org.springframework.boot spring-boot-starter-parent 1.4.0.RELEASE - + @@ -33,60 +33,68 @@ 2.6 2.19.1 2.7 - + 1.3.16 + 1.4.3 + 1.4.0.RELEASE - + + org.springframework.boot + spring-boot-starter-tomcat + provided + org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-aop - com.netflix.hystrix hystrix-core ${hystrix-core.version} - com.netflix.hystrix hystrix-metrics-event-stream - 1.3.16 + ${hystrix-metrics-event-stream.version} - - - - + ${hystrix-dashboard.version} +
com.netflix.rxjava rxjava-core ${rxjava-core.version} - org.hamcrest hamcrest-all ${hamcrest-all.version} test - junit junit ${junit.version} test - + + org.springframework + spring-test + test + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot-starter-test.version} + test +
diff --git a/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java b/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java index c2e4af8edb..3a650c2f4f 100644 --- a/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java @@ -17,6 +17,28 @@ public class HystrixAspect { private HystrixCommandProperties.Setter commandProperties; private HystrixThreadPoolProperties.Setter threadPoolProperties; + @Value("${remoteservice.command.execution.timeout}") + private int executionTimeout; + + @Value("${remoteservice.command.sleepwindow}") + private int sleepWindow; + + @Value("${remoteservice.command.threadpool.maxsize}") + private int maxThreadCount; + + @Value("${remoteservice.command.threadpool.coresize}") + private int coreThreadCount; + + @Value("${remoteservice.command.task.queue.size}") + private int queueCount; + + @Value("${remoteservice.command.group.key}") + private String groupKey; + + @Value("${remoteservice.command.key}") + private String key; + + @Around("@annotation(com.baeldung.hystrix.HystrixCircuitBreaker)") public Object circuitBreakerAround(final ProceedingJoinPoint aJoinPoint) { return new RemoteServiceCommand(config, aJoinPoint).execute(); @@ -31,7 +53,7 @@ public class HystrixAspect { this.commandProperties.withExecutionTimeoutInMilliseconds(executionTimeout); this.commandProperties.withCircuitBreakerSleepWindowInMilliseconds(sleepWindow); - this.threadPoolProperties= HystrixThreadPoolProperties.Setter(); + this.threadPoolProperties = HystrixThreadPoolProperties.Setter(); this.threadPoolProperties.withMaxQueueSize(maxThreadCount).withCoreSize(coreThreadCount).withMaxQueueSize(queueCount); this.config.andCommandPropertiesDefaults(commandProperties); @@ -58,24 +80,4 @@ public class HystrixAspect { } } - @Value("${remoteservice.command.execution.timeout}") - private int executionTimeout; - - @Value("${remoteservice.command.sleepwindow}") - private int sleepWindow; - - @Value("${remoteservice.command.threadpool.maxsize}") - private int maxThreadCount; - - @Value("${remoteservice.command.threadpool.coresize}") - private int coreThreadCount; - - @Value("${remoteservice.command.task.queue.size}") - private int queueCount; - - @Value("${remoteservice.command.group.key}") - private String groupKey; - - @Value("${remoteservice.command.key}") - private String key; } diff --git a/hystrix/src/main/resources/application.properties b/hystrix/src/main/resources/application.properties index abde975550..50c241d03f 100644 --- a/hystrix/src/main/resources/application.properties +++ b/hystrix/src/main/resources/application.properties @@ -5,4 +5,4 @@ remoteservice.command.threadpool.coresize=5 remoteservice.command.threadpool.maxsize=10 remoteservice.command.task.queue.size=5 remoteservice.command.sleepwindow=5000 -remoteservice.timeout=5000 \ No newline at end of file +remoteservice.timeout=15000 \ No newline at end of file diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java index 34eb334b32..d65931d9f7 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -16,7 +16,7 @@ import static org.hamcrest.Matchers.equalTo; public class HystrixTimeoutTest { private HystrixCommand.Setter config; - private HystrixCommandProperties.Setter commandProperties ; + private HystrixCommandProperties.Setter commandProperties; @Rule @@ -26,12 +26,12 @@ public class HystrixTimeoutTest { public void setup() { commandProperties = HystrixCommandProperties.Setter(); config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); } @Test - public void givenInputBob_andDefaultSettings_thenReturnHelloBob(){ + public void givenInputBob_andDefaultSettings_thenReturnHelloBob() { assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!")); } @@ -107,12 +107,12 @@ public class HystrixTimeoutTest { equalTo("Success")); } - public String invokeRemoteService(long timeout) throws InterruptedException{ + public String invokeRemoteService(long timeout) throws InterruptedException { String response = null; - try{ + try { response = new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(timeout)).execute(); - }catch(HystrixRuntimeException ex){ + } catch (HystrixRuntimeException ex) { System.out.println("ex = " + ex); } return response; diff --git a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java new file mode 100644 index 0000000000..8f443fc5a4 --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.exception.HystrixRuntimeException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppConfig.class) +public class SpringAndHystrixIntegrationTest { + + @Autowired + private HystrixController hystrixController; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Test + public void givenTimeOutOf15000_whenExistingClientCalled_thenExpectHystrixRuntimeException() throws InterruptedException { + exception.expect(HystrixRuntimeException.class); + assertThat(hystrixController.index(), equalTo("Success")); + } + + +} From cfeaa4e6f30637bf5bbccc9ff414670acf140bcb Mon Sep 17 00:00:00 2001 From: sbalachandran Date: Mon, 15 Aug 2016 22:26:28 -0400 Subject: [PATCH 37/43] Fixed unit test naming convention. --- .../baeldung/hystrix/HystrixTimeoutTest.java | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java index c9ddd98367..b66ed4507f 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -32,32 +32,40 @@ public class HystrixTimeoutTest { } @Test - public void givenInputBob_andDefaultSettings_thenReturnHelloBob(){ + public void givenInputBobAndDefaultSettings_whenExecuted_thenReturnHelloBob(){ assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!")); } @Test - public void givenServiceTimeoutEqualTo100_andDefaultSettings_thenReturnSuccess() throws InterruptedException { - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), equalTo("Success")); + public void givenSvcTimeoutOf100AndDefaultSettings_whenExecuted_thenReturnSuccess() + throws InterruptedException { + + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), + equalTo("Success")); } @Test - public void givenServiceTimeoutEqualTo10000_andDefaultSettings_thenExpectHRE() throws InterruptedException { + public void givenSvcTimeoutOf10000AndDefaultSettings__whenExecuted_thenExpectHRE() throws InterruptedException { exception.expect(HystrixRuntimeException.class); new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute(); } @Test - public void givenServiceTimeoutEqualTo5000_andExecutionTimeoutEqualTo10000_thenReturnSuccess() + public void givenSvcTimeoutOf5000AndExecTimeoutOf10000__whenExecuted_thenReturnSuccess() throws InterruptedException { commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), equalTo("Success")); } @Test - public void givenServiceTimeoutEqualTo15000_andExecutionTimeoutEqualTo5000_thenExpectHRE() + public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE() throws InterruptedException { exception.expect(HystrixRuntimeException.class); commandProperties.withExecutionTimeoutInMilliseconds(5_000); @@ -66,7 +74,7 @@ public class HystrixTimeoutTest { } @Test - public void givenServiceTimeoutEqual_andExecutionTimeout_andThreadPool_thenReturnSuccess() + public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess() throws InterruptedException { commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); @@ -74,12 +82,14 @@ public class HystrixTimeoutTest { .withMaxQueueSize(10) .withCoreSize(3) .withQueueSizeRejectionThreshold(10)); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), equalTo("Success")); } @Test - public void givenCircuitBreakerSetup_thenReturnSuccess() throws InterruptedException { + public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess() + throws InterruptedException { commandProperties.withExecutionTimeoutInMilliseconds(1000); From fa3581339cc74d021874d5272967fa2099c53b61 Mon Sep 17 00:00:00 2001 From: Alex Theedom Date: Tue, 16 Aug 2016 07:56:54 +0100 Subject: [PATCH 38/43] Minor changes after review --- .../hystrix/HystrixTimeShortCircuitTest.java | 74 +++++++++++++++++++ .../baeldung/hystrix/HystrixTimeoutTest.java | 49 +----------- 2 files changed, 77 insertions(+), 46 deletions(-) create mode 100644 hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java new file mode 100644 index 0000000000..a5303e6c0d --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import com.netflix.hystrix.HystrixThreadPoolProperties; +import com.netflix.hystrix.exception.HystrixRuntimeException; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.junit.runners.MethodSorters; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +@FixMethodOrder(MethodSorters.JVM) +public class HystrixTimeShortCircuitTest { + + private HystrixCommand.Setter config; + private HystrixCommandProperties.Setter commandProperties; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Before + public void setup() { + commandProperties = HystrixCommandProperties.Setter(); + config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + } + + @Test + public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess() + throws InterruptedException { + + commandProperties.withExecutionTimeoutInMilliseconds(1000); + + commandProperties.withCircuitBreakerSleepWindowInMilliseconds(4000); + commandProperties.withExecutionIsolationStrategy( + HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); + commandProperties.withCircuitBreakerEnabled(true); + commandProperties.withCircuitBreakerRequestVolumeThreshold(1); + + config.andCommandPropertiesDefaults(commandProperties); + + config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() + .withMaxQueueSize(1) + .withCoreSize(1) + .withQueueSizeRejectionThreshold(1)); + + assertThat(this.invokeRemoteService(10000), equalTo(null)); + assertThat(this.invokeRemoteService(10000), equalTo(null)); + Thread.sleep(5000); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + } + + String invokeRemoteService(long timeout) throws InterruptedException { + String response = null; + try { + response = new RemoteServiceTestCommand(config, + new RemoteServiceTestSimulator(timeout)).execute(); + } catch (HystrixRuntimeException ex) { + System.out.println("ex = " + ex); + } + return response; + } + +} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java index e85f3d7199..878d7808a0 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -5,14 +5,14 @@ import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.exception.HystrixRuntimeException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +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 HystrixTimeoutTest { private HystrixCommand.Setter config; @@ -85,47 +85,4 @@ public class HystrixTimeoutTest { assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), equalTo("Success")); } - - @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")); - } - - public 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; - } - } From e4f2bed4fd3b435b9e56894b86f6f4b145725e7d Mon Sep 17 00:00:00 2001 From: Alex Theedom Date: Tue, 16 Aug 2016 08:10:45 +0100 Subject: [PATCH 39/43] Minor changes after review --- .../java/com/baeldung/hystrix/HystrixController.java | 11 ++++++++--- .../com/baeldung/hystrix/SpringExistingClient.java | 5 ++++- .../hystrix/SpringAndHystrixIntegrationTest.java | 8 ++++++-- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java b/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java index a8ca0adef2..69d9e30ff8 100644 --- a/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java @@ -10,8 +10,13 @@ public class HystrixController { @Autowired private SpringExistingClient client; - @RequestMapping("/") - public String index() throws InterruptedException{ - return client.invokeRemoteService(); + @RequestMapping("/withHystrix") + public String withHystrix() throws InterruptedException{ + return client.invokeRemoteServiceWithHystrix(); + } + + @RequestMapping("/withOutHystrix") + public String withOutHystrix() throws InterruptedException{ + return client.invokeRemoteServiceWithOutHystrix(); } } diff --git a/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java b/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java index fab8e611d4..525c7b4785 100644 --- a/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java @@ -10,8 +10,11 @@ public class SpringExistingClient { private int remoteServiceDelay; @HystrixCircuitBreaker - public String invokeRemoteService() throws InterruptedException{ + public String invokeRemoteServiceWithHystrix() throws InterruptedException{ return new RemoteServiceTestSimulator(remoteServiceDelay).execute(); } + public String invokeRemoteServiceWithOutHystrix() throws InterruptedException{ + return new RemoteServiceTestSimulator(remoteServiceDelay).execute(); + } } diff --git a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java index 8f443fc5a4..004314b0ed 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java @@ -23,10 +23,14 @@ public class SpringAndHystrixIntegrationTest { public final ExpectedException exception = ExpectedException.none(); @Test - public void givenTimeOutOf15000_whenExistingClientCalled_thenExpectHystrixRuntimeException() throws InterruptedException { + public void givenTimeOutOf15000_whenClientCalledWithHystrix_thenExpectHystrixRuntimeException() throws InterruptedException { exception.expect(HystrixRuntimeException.class); - assertThat(hystrixController.index(), equalTo("Success")); + hystrixController.withHystrix(); } + @Test + public void givenTimeOutOf15000_whenClientCalledWithOutHystrix_thenExpectSuccess() throws InterruptedException { + assertThat(hystrixController.withOutHystrix(), equalTo("Success")); + } } From fe16518c17d7a51abe0940e240d439727b9cde88 Mon Sep 17 00:00:00 2001 From: Sergey Petunin Date: Tue, 16 Aug 2016 13:42:14 +0600 Subject: [PATCH 40/43] Added cancellation example for CompletableFuture (#614) --- .../CompletableFutureTest.java | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java index 806bca5461..e713115cab 100644 --- a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java +++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java @@ -1,14 +1,11 @@ package com.baeldung.completablefuture; -import org.junit.Test; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; +import java.util.concurrent.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -46,6 +43,28 @@ public class CompletableFutureTest { } + + public Future calculateAsyncWithCancellation() throws InterruptedException { + CompletableFuture completableFuture = new CompletableFuture<>(); + + Executors.newCachedThreadPool().submit(() -> { + Thread.sleep(500); + completableFuture.cancel(false); + return null; + }); + + return completableFuture; + } + + + @Test(expected = CancellationException.class) + public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException { + + Future future = calculateAsyncWithCancellation(); + future.get(); + + } + @Test public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException { From 6c062ca19e3336643bc821fe5f3c0c3a0f4e607c Mon Sep 17 00:00:00 2001 From: PRITAM BANERJEE Date: Tue, 16 Aug 2016 22:19:34 -0700 Subject: [PATCH 41/43] Hibernate Fetching Update (#607) * BAEL-212 Contains: 1. Hibernate Criteria Query Classes 2. Hibernate Criteria Query Test * Updating the config file and the HibernateUtil class * Hibernate Criteria Queries Example * Hibernate Fetching : Eager Loading vs Lazy Loading * Hibernate Criteria Query files * Hibernate Eager Loading and Lazy Loading Changes * Latest Changes on Fetching * Fetching Changes * Latest Changes * Latest Changes * Undoing the changes --- .../CompletableFutureTest.java | 2 +- .../hibernate/fetching/model/OrderDetail.java | 141 +++++++-------- .../hibernate/fetching/model/User.java | 11 +- .../fetching/util/HibernateUtil.java | 31 ++-- .../fetching/view/FetchingAppView.java | 169 +++++++++--------- .../fetching/HibernateFetchingTest.java | 29 ++- 6 files changed, 198 insertions(+), 185 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java index e713115cab..5363a73afa 100644 --- a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java +++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java @@ -206,4 +206,4 @@ public class CompletableFutureTest { } -} +} \ No newline at end of file diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index 91388b107b..80cb915e52 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -3,80 +3,71 @@ package com.baeldung.hibernate.fetching.model; import java.io.Serializable; import java.sql.Date; -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() { - - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - this.orderDate = orderDate; - this.orderDesc = orderDesc; - } - - public Date getOrderDate() { - return orderDate; - } - - public void setOrderDate(Date orderDate) { - this.orderDate = orderDate; - } - - public String getOrderDesc() { - return orderDesc; - } - - public void setOrderDesc(String orderDesc) { - this.orderDesc = orderDesc; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } +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(){ + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + this.orderDate = orderDate; + this.orderDesc = orderDesc; + } + + public Date getOrderDate() { + return orderDate; + } + public void setOrderDate(Date orderDate) { + this.orderDate = orderDate; + } + public String getOrderDesc() { + return orderDesc; + } + public void setOrderDesc(String orderDesc) { + this.orderDesc = orderDesc; + } + public User getUser() { + return user; + } + public void setUser(User user) { + this.user = user; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + public Long getOrderId() { + return orderId; + } + public void setOrderId(Long orderId) { + this.orderId = orderId; + } } + + diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java index 158855f93e..fa995319fd 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java @@ -17,12 +17,11 @@ public class User implements Serializable { } 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; - + super(); + this.userId = userId; + this.userName = userName; + this.firstName = firstName; + this.lastName = lastName; } @Override diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index 65ecea2fa4..27af8c9b8b 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -1,24 +1,27 @@ package com.baeldung.hibernate.fetching.util; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - //two config files are there - //one with lazy loading enabled - //another lazy = false - - final String configFileName = "lazy".equals(fetchMethod) ? - "fetchingLazy.cfg.xml" : - "fetching.cfg.xml"; - - return new Configuration() - .configure(configFileName) - .buildSessionFactory().openSession(); - } + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + //two config files are there + //one with lazy loading enabled + //another lazy = false + SessionFactory sf = null; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + final Session session = sf.openSession(); + return session; + } public static Session getHibernateSession() { return new Configuration() diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java index 90fd302968..c55f65cdbf 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -18,93 +18,94 @@ import com.baeldung.hibernate.fetching.model.User; public class FetchingAppView { - public FetchingAppView() { + public FetchingAppView(){ + + } + + //lazily loaded + public Set lazyLoaded(){ + final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); + List users = sessionLazy.createQuery("From User").list(); + User userLazyLoaded = new User(); + userLazyLoaded = users.get(3); + //since data is lazyloaded so data won't be initialized + Set orderDetailSet = userLazyLoaded.getOrderDetail(); + return (orderDetailSet); + } + + //eagerly loaded + public Set eagerLoaded(){ + final Session sessionEager = HibernateUtil.getHibernateSession(); + //data should be loaded in the following line + //also note the queries generated + List users =sessionEager.createQuery("From User").list(); + User userEagerLoaded = new User(); + userEagerLoaded = users.get(3); + Set orderDetailSet = userEagerLoaded.getOrderDetail(); + return orderDetailSet; + } + + + //creates test data + //call this method to create the data in the database + public void createTestData() { - } + 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); - public boolean lazyLoaded() { - final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); - List users = sessionLazy.createQuery("From User").list(); - User userLazyLoaded = users.get(3); - //since data is lazyloaded so data won't be initialized - Set orderDetailSet = userLazyLoaded.getOrderDetail(); + 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(); - return (Hibernate.isInitialized(orderDetailSet)); - } + 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); - public boolean eagerLoaded() { - final Session sessionEager = HibernateUtil.getHibernateSession(); - //data should be loaded in the following line - //also note the queries generated - List users = sessionEager.createQuery("From User").list(); - User userEagerLoaded = users.get(3); - Set orderDetailSet = userEagerLoaded.getOrderDetail(); + tx.commit(); + session.close(); - return (Hibernate.isInitialized(orderDetailSet)); - } - - - //creates test data - //call this method to create the data in the database - public void createTestData() { - - final Session session = HibernateUtil.getHibernateSession(); - Transaction 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(); - - 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); - - // session.saveOrUpdate(user1); - tx.commit(); - session.close(); - } + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java index 94ee8a3c79..fb3d0f92fc 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -1,24 +1,43 @@ package com.baeldung.hibernate.fetching; import static org.junit.Assert.*; +import java.util.Set; +import org.hibernate.Hibernate; +import org.junit.Before; import org.junit.Test; +import com.baeldung.hibernate.fetching.model.OrderDetail; + import com.baeldung.hibernate.fetching.view.FetchingAppView; public class HibernateFetchingTest { + + //this loads sample data in the database + @Before + public void addFecthingTestData(){ + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } + + //testLazyFetching() tests the lazy loading + //Since it lazily loaded so orderDetalSetLazy won't + //be initialized @Test public void testLazyFetching() { FetchingAppView fav = new FetchingAppView(); - fav.createTestData(); - assertFalse(fav.lazyLoaded()); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); } - + + //testEagerFetching() tests the eager loading + //Since it eagerly loaded so orderDetalSetLazy would + //be initialized @Test public void testEagerFetching() { FetchingAppView fav = new FetchingAppView(); - assertTrue(fav.eagerLoaded()); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); } - } From 82afbe6aef71058699433d60c1b4695ccd735606 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 17 Aug 2016 10:41:23 +0300 Subject: [PATCH 42/43] maven cleanup --- cdi/pom.xml | 54 +++++++++---------- .../com/baeldung/test/TestInterceptor.java | 2 + pom.xml | 1 + 3 files changed, 30 insertions(+), 27 deletions(-) diff --git a/cdi/pom.xml b/cdi/pom.xml index 2a9d32188b..b771857938 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -1,52 +1,52 @@ - + 4.0.0 com.baeldung cdi 1.0-SNAPSHOT - - 4.3.1.RELEASE - + - - - junit - junit - 4.12 - - org.springframework spring-core ${spring.version} - org.springframework spring-context ${spring.version} - + + + org.aspectj + aspectjweaver + 1.8.9 + + + org.jboss.weld.se + weld-se-core + 2.3.5.Final + + + + junit + junit + 4.12 + test + org.springframework spring-test ${spring.version} test - - - org.aspectj - aspectjweaver - 1.8.9 - - - - org.jboss.weld.se - weld-se-core - 2.3.5.Final - + + + + 4.3.1.RELEASE + + \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java index 406296529c..3529a796d2 100644 --- a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java @@ -30,7 +30,9 @@ public class TestInterceptor { SuperService superService = container.select(SuperService.class).get(); String code = "123456"; superService.deliverService(code); + Assert.assertTrue(AuditedInterceptor.calledBefore); Assert.assertTrue(AuditedInterceptor.calledAfter); } + } diff --git a/pom.xml b/pom.xml index 3f4489fc4c..8b2d0b3ff1 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,7 @@ apache-cxf apache-fop autovalue-tutorial + cdi core-java core-java-8 couchbase-sdk-intro From f811eacebb34aa97f725394f51adaa6c8bc770de Mon Sep 17 00:00:00 2001 From: Slavisa Baeldung Date: Wed, 17 Aug 2016 16:45:14 +0200 Subject: [PATCH 43/43] BAEL-219 - adding docker files --- spring-cloud-config/docker/Dockerfile | 4 ++ spring-cloud-config/docker/Dockerfile.client | 6 +++ spring-cloud-config/docker/Dockerfile.server | 9 ++++ .../docker/config-client-entrypoint.sh | 8 ++++ .../docker/docker-compose.scale.yml | 41 ++++++++++++++++++ spring-cloud-config/docker/docker-compose.yml | 43 +++++++++++++++++++ 6 files changed, 111 insertions(+) create mode 100644 spring-cloud-config/docker/Dockerfile create mode 100644 spring-cloud-config/docker/Dockerfile.client create mode 100644 spring-cloud-config/docker/Dockerfile.server create mode 100644 spring-cloud-config/docker/config-client-entrypoint.sh create mode 100644 spring-cloud-config/docker/docker-compose.scale.yml create mode 100644 spring-cloud-config/docker/docker-compose.yml diff --git a/spring-cloud-config/docker/Dockerfile b/spring-cloud-config/docker/Dockerfile new file mode 100644 index 0000000000..bdb37abf80 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile @@ -0,0 +1,4 @@ +FROM alpine:edge +MAINTAINER baeldung.com +RUN apk add --no-cache openjdk8 +COPY files/UnlimitedJCEPolicyJDK8/* /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/ diff --git a/spring-cloud-config/docker/Dockerfile.client b/spring-cloud-config/docker/Dockerfile.client new file mode 100644 index 0000000000..5fbc0b98c0 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile.client @@ -0,0 +1,6 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +RUN apk --no-cache add netcat-openbsd +COPY files/config-client.jar /opt/spring-cloud/lib/ +COPY files/config-client-entrypoint.sh /opt/spring-cloud/bin/ +RUN chmod 755 /opt/spring-cloud/bin/config-client-entrypoint.sh diff --git a/spring-cloud-config/docker/Dockerfile.server b/spring-cloud-config/docker/Dockerfile.server new file mode 100644 index 0000000000..4f7bd751e8 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile.server @@ -0,0 +1,9 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +COPY files/config-server.jar /opt/spring-cloud/lib/ +ENV SPRING_APPLICATION_JSON='{"spring": {"cloud": {"config": {"server": \ + {"git": {"uri": "/var/lib/spring-cloud/config-repo", "clone-on-start": true}}}}}}' +ENTRYPOINT ["/usr/bin/java"] +CMD ["-jar", "/opt/spring-cloud/lib/config-server.jar"] +VOLUME /var/lib/spring-cloud/config-repo +EXPOSE 8888 diff --git a/spring-cloud-config/docker/config-client-entrypoint.sh b/spring-cloud-config/docker/config-client-entrypoint.sh new file mode 100644 index 0000000000..12352119fa --- /dev/null +++ b/spring-cloud-config/docker/config-client-entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +while ! nc -z config-server 8888 ; do + echo "Waiting for upcoming Config Server" + sleep 2 +done + +java -jar /opt/spring-cloud/lib/config-client.jar diff --git a/spring-cloud-config/docker/docker-compose.scale.yml b/spring-cloud-config/docker/docker-compose.scale.yml new file mode 100644 index 0000000000..f74153bea3 --- /dev/null +++ b/spring-cloud-config/docker/docker-compose.scale.yml @@ -0,0 +1,41 @@ +version: '2' +services: + config-server: + build: + context: . + dockerfile: Dockerfile.server + image: config-server:latest + expose: + - 8888 + networks: + - spring-cloud-network + volumes: + - spring-cloud-config-repo:/var/lib/spring-cloud/config-repo + logging: + driver: json-file + config-client: + build: + context: . + dockerfile: Dockerfile.client + image: config-client:latest + entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh + environment: + SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}' + expose: + - 8080 + ports: + - 8080 + networks: + - spring-cloud-network + links: + - config-server:config-server + depends_on: + - config-server + logging: + driver: json-file +networks: + spring-cloud-network: + driver: bridge +volumes: + spring-cloud-config-repo: + external: true diff --git a/spring-cloud-config/docker/docker-compose.yml b/spring-cloud-config/docker/docker-compose.yml new file mode 100644 index 0000000000..74c71b651c --- /dev/null +++ b/spring-cloud-config/docker/docker-compose.yml @@ -0,0 +1,43 @@ +version: '2' +services: + config-server: + container_name: config-server + build: + context: . + dockerfile: Dockerfile.server + image: config-server:latest + expose: + - 8888 + networks: + - spring-cloud-network + volumes: + - spring-cloud-config-repo:/var/lib/spring-cloud/config-repo + logging: + driver: json-file + config-client: + container_name: config-client + build: + context: . + dockerfile: Dockerfile.client + image: config-client:latest + entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh + environment: + SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}' + expose: + - 8080 + ports: + - 8080:8080 + networks: + - spring-cloud-network + links: + - config-server:config-server + depends_on: + - config-server + logging: + driver: json-file +networks: + spring-cloud-network: + driver: bridge +volumes: + spring-cloud-config-repo: + external: true