diff --git a/spring-mvc-velocity/src/main/webapp/WEB-INF/views/index.vm b/spring-mvc-velocity/src/main/webapp/WEB-INF/views/index.vm
index d1ae0b02cb..8883a50658 100644
--- a/spring-mvc-velocity/src/main/webapp/WEB-INF/views/index.vm
+++ b/spring-mvc-velocity/src/main/webapp/WEB-INF/views/index.vm
@@ -1,19 +1,4 @@
Index
-
Tutorials list
-
-
- Tutorial Id
- Tutorial Title
- Tutorial Description
- Tutorial Author
-
-#foreach($tut in $tutorials)
-
- $tut.tutId
- $tut.title
- $tut.description
- $tut.author
-
-#end
-
\ No newline at end of file
+
Welcome page
+This is just the welcome page
\ No newline at end of file
diff --git a/spring-mvc-velocity/src/main/webapp/WEB-INF/views/list.vm b/spring-mvc-velocity/src/main/webapp/WEB-INF/views/list.vm
new file mode 100644
index 0000000000..9e06a09e4f
--- /dev/null
+++ b/spring-mvc-velocity/src/main/webapp/WEB-INF/views/list.vm
@@ -0,0 +1,19 @@
+
Index
+
+
Tutorials list
+
+
+ Tutorial Id
+ Tutorial Title
+ Tutorial Description
+ Tutorial Author
+
+#foreach($tut in $tutorials)
+
+ $tut.tutId
+ $tut.title
+ $tut.description
+ $tut.author
+
+#end
+
\ No newline at end of file
diff --git a/spring-mvc-velocity/src/main/webapp/WEB-INF/web.xml b/spring-mvc-velocity/src/main/webapp/WEB-INF/web_old.xml
similarity index 100%
rename from spring-mvc-velocity/src/main/webapp/WEB-INF/web.xml
rename to spring-mvc-velocity/src/main/webapp/WEB-INF/web_old.xml
diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java
index 36453eef92..a9fb242755 100644
--- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java
+++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java
@@ -1,12 +1,19 @@
package com.baeldung.mvc.velocity.test;
-import com.baeldung.mvc.velocity.domain.Tutorial;
-import com.baeldung.mvc.velocity.service.ITutorialsService;
-import com.baeldung.mvc.velocity.service.TutorialsService;
+import static org.hamcrest.Matchers.allOf;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.is;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -15,72 +22,40 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
-import java.util.Arrays;
-
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.hasItem;
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.hasSize;
-import static org.hamcrest.Matchers.is;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
+import com.baeldung.mvc.velocity.spring.config.WebConfig;
+import com.baeldung.mvc.velocity.test.config.TestConfig;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = {"classpath:mvc-servlet.xml"})
+// @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"})
+@ContextConfiguration(classes = { TestConfig.class, WebConfig.class })
@WebAppConfiguration
public class DataContentControllerTest {
-
private MockMvc mockMvc;
- @Autowired
- private ITutorialsService tutServiceMock;
-
@Autowired
private WebApplicationContext webApplicationContext;
-
+
@Before
public void setUp() {
- tutServiceMock = Mockito.mock(TutorialsService.class);
- Mockito.reset(tutServiceMock);
+
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
-
- @Test
- public void testModel() throws Exception{
- Mockito.when(tutServiceMock.listTutorials()).thenReturn(Arrays.asList(
- new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
- new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")
- ));
-
- mockMvc.perform(get("/"))
- .andExpect(status().isOk())
- .andExpect(view().name("index"))
- .andExpect(content().string(containsString("GuavaAuthor")))
- .andExpect(content().string(containsString("Introduction to Guava")))
- .andExpect(content().string(containsString("AndroidAuthor")))
- .andExpect(content().string(containsString("Introduction to Android")))
- .andExpect(model().attribute("tutorials", hasSize(2)))
- .andExpect(model().attribute("tutorials", hasSize(2)))
- .andExpect(model().attribute("tutorials", hasItem(
- allOf(
- hasProperty("tutId", is(1)),
- hasProperty("author", is("GuavaAuthor")),
- hasProperty("title", is("Guava"))
- )
- )))
- .andExpect(model().attribute("tutorials", hasItem(
- allOf(
- hasProperty("tutId", is(2)),
- hasProperty("author", is("AndroidAuthor")),
- hasProperty("title", is("Android"))
- )
- )));
- }
+ @Test
+ public void whenCallingList_ThenModelAndContentOK() throws Exception {
+
+ mockMvc.perform(get("/list")).andExpect(status().isOk()).andExpect(view().name("list")).andExpect(model().attribute("tutorials", hasSize(2)))
+ .andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(1)), hasProperty("author", is("GuavaAuthor")), hasProperty("title", is("Guava"))))))
+ .andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)), hasProperty("author", is("AndroidAuthor")), hasProperty("title", is("Android"))))));
+
+ mockMvc.perform(get("/list")).andExpect(xpath("//table").exists());
+ mockMvc.perform(get("/list")).andExpect(xpath("//td[@id='tutId_1']").exists());
+ }
+
+ @Test
+ public void whenCallingIndex_thenViewOK() throws Exception{
+ mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0));
+ }
}
diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java
deleted file mode 100644
index e007cf3f94..0000000000
--- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package com.baeldung.mvc.velocity.test;
-
-
-import com.baeldung.mvc.velocity.controller.MainController;
-import com.baeldung.mvc.velocity.domain.Tutorial;
-import com.baeldung.mvc.velocity.service.TutorialsService;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.web.WebAppConfiguration;
-import org.springframework.ui.ExtendedModelMap;
-import org.springframework.ui.Model;
-
-import java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@WebAppConfiguration
-@ContextConfiguration(locations = {"classpath:mvc-servlet.xml"})
-public class NavigationControllerTest {
-
- private MainController mainController = new MainController(Mockito.mock(TutorialsService.class));
-
- private final Model model = new ExtendedModelMap();
-
-
- @Test
- public void shouldGoToTutorialListView() {
- Mockito.when(mainController.getTutService().listTutorials())
- .thenReturn(createTutorialList());
-
- final String view = mainController.listTutorialsPage(model);
- final List
tutorialListAttribute = (List) model.asMap().get("tutorials");
-
- assertEquals("index", view);
- assertNotNull(tutorialListAttribute);
- }
-
- @Test
- public void testContent() throws Exception{
-
- List tutorials = Arrays.asList(
- new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
- new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")
- );
- Mockito.when(mainController.getTutService().listTutorials()).thenReturn(tutorials);
-
- String view = mainController.listTutorialsPage(model);
-
- verify(mainController.getTutService(), times(1)).listTutorials();
- verifyNoMoreInteractions(mainController.getTutService());
-
- assertEquals("index", view);
- assertEquals(tutorials, model.asMap().get("tutorials"));
- }
-
- private static List createTutorialList() {
- return Arrays.asList(new Tutorial(1, "TestAuthor", "Test Title", "Test Description"));
- }
-}
diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java
new file mode 100644
index 0000000000..8b84bcdd23
--- /dev/null
+++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java
@@ -0,0 +1,32 @@
+package com.baeldung.mvc.velocity.test.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.ViewResolver;
+import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
+import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
+
+@Configuration
+public class TestConfig {
+
+
+ @Bean
+ public ViewResolver viewResolver() {
+ final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
+ bean.setCache(true);
+ bean.setPrefix("/WEB-INF/views/");
+ bean.setLayoutUrl("/WEB-INF/layouts/layout.vm");
+ bean.setSuffix(".vm");
+ return bean;
+ }
+
+ @Bean
+ public VelocityConfigurer velocityConfig() {
+ VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
+ velocityConfigurer.setResourceLoaderPath("/");
+ return velocityConfigurer;
+ }
+
+
+
+}
diff --git a/spring-rest-angular-pagination/StudentDirectory/pom.xml b/spring-rest-angular-pagination/StudentDirectory/pom.xml
new file mode 100644
index 0000000000..8dab851ef2
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/pom.xml
@@ -0,0 +1,86 @@
+
+
+ 4.0.0
+ angular-spring-rest-sample
+ angular-spring-rest-sample
+ com.baeldung
+ 1.0
+ war
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 1.3.3.RELEASE
+
+
+ 1.12.2.RELEASE
+
+
+
+ org.springframework.boot
+ spring-boot-starter-tomcat
+ provided
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.data
+ spring-data-commons
+
+
+ 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/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java
new file mode 100644
index 0000000000..df70780a87
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java
@@ -0,0 +1,39 @@
+package org.baeldung.mock;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.baeldung.web.vo.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/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java
new file mode 100644
index 0000000000..3105d1cb11
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java
@@ -0,0 +1,27 @@
+package org.baeldung.web.exception;
+
+public class MyResourceNotFoundException extends RuntimeException {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 4088649120307193208L;
+
+ public MyResourceNotFoundException() {
+ super();
+ }
+
+ public MyResourceNotFoundException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+ public MyResourceNotFoundException(final String message) {
+ super(message);
+ }
+
+ public MyResourceNotFoundException(final Throwable cause) {
+ super(cause);
+ }
+
+
+}
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java
new file mode 100644
index 0000000000..b3b0dad98a
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java
@@ -0,0 +1,26 @@
+package org.baeldung.web.main;
+
+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.web.filter.ShallowEtagHeaderFilter;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
+
+@SpringBootApplication
+@EnableAutoConfiguration
+@ComponentScan("org.baeldung")
+public class Application extends WebMvcConfigurerAdapter {
+
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+
+ @Bean
+ public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
+ return new ShallowEtagHeaderFilter();
+ }
+
+}
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java
new file mode 100644
index 0000000000..5ff24ec0f2
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java
@@ -0,0 +1,26 @@
+package org.baeldung.web.rest;
+
+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.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;
+
+@RestController
+public class StudentDirectoryRestController {
+
+ @Autowired
+ private StudentService service;
+
+ @RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET)
+ public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size){
+
+ Page resultPage = service.findPaginated(page, size);
+
+ return resultPage;
+ }
+
+}
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java
new file mode 100644
index 0000000000..0b408106ce
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java
@@ -0,0 +1,9 @@
+package org.baeldung.web.service;
+
+import org.springframework.data.domain.Page;
+
+public interface IOperations {
+
+ Page findPaginated(int page, int size);
+
+}
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java
new file mode 100644
index 0000000000..5c4487254a
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java
@@ -0,0 +1,7 @@
+package org.baeldung.web.service;
+
+import org.baeldung.web.vo.Student;
+
+public interface StudentService extends IOperations{
+
+}
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java
new file mode 100644
index 0000000000..3b6dda6fb1
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java
@@ -0,0 +1,36 @@
+package org.baeldung.web.service;
+
+import java.util.List;
+
+import org.baeldung.mock.MockStudentData;
+import org.baeldung.web.exception.MyResourceNotFoundException;
+import org.baeldung.web.vo.Student;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageImpl;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.stereotype.Service;
+
+@Service
+public class StudentServiceImpl implements StudentService {
+
+ private List mockDataStudent = MockStudentData.getMockDataStudents();
+
+ @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());
+ }
+
+}
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java
new file mode 100644
index 0000000000..11c503815d
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java
@@ -0,0 +1,60 @@
+package org.baeldung.web.vo;
+
+import java.io.Serializable;
+
+public class Student implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ public Student() {
+ }
+
+ public Student(String studentId, String name, String gender, Integer age) {
+ super();
+ this.studentId = studentId;
+ this.name = name;
+ this.gender = gender;
+ this.age = age;
+ }
+
+ private String studentId;
+ private String name;
+ private String gender;
+ private Integer age;
+
+ public String getStudentId() {
+ return studentId;
+ }
+
+ public void setStudentId(String studentId) {
+ this.studentId = studentId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getGender() {
+ return gender;
+ }
+
+ public void setGender(String gender) {
+ this.gender = gender;
+ }
+
+ public Integer getAge() {
+ return age;
+ }
+
+ public void setAge(Integer age) {
+ this.age = age;
+ }
+
+}
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties b/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties
new file mode 100644
index 0000000000..a9bf6ca218
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties
@@ -0,0 +1 @@
+server.contextPath=/StudentDirectory
\ No newline at end of file
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/WEB-INF/web.xml b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..ff65bd6b96
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/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-pagination/StudentDirectory/src/main/webapp/index.html b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/index.html
new file mode 100644
index 0000000000..56a1273588
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/index.html
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js
new file mode 100644
index 0000000000..522c49c8cb
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js
@@ -0,0 +1,54 @@
+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,
+ columnDefs: [
+ { name: 'studentId' },
+ { 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) {
+ 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/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular-pagination/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java
new file mode 100644
index 0000000000..3e476bf0d0
--- /dev/null
+++ b/spring-rest-angular-pagination/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java
@@ -0,0 +1,49 @@
+package org.baeldung.web.service;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.baeldung.web.main.Application;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.IntegrationTest;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.web.WebAppConfiguration;
+
+import io.restassured.RestAssured;
+import io.restassured.response.Response;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringApplicationConfiguration(classes = Application.class)
+@WebAppConfiguration
+@IntegrationTest("server.port:8080")
+public class StudentServiceTest{
+
+ private String getURL() {
+ return "/StudentDirectory/student/get";
+ }
+
+ @Test
+ public void whenResourcesAreRetrievedPaged_then200IsReceived(){
+ Response response = RestAssured.given().get(getURL()+ "?page=0&size=2").andReturn();
+
+ assertTrue(response.getStatusCode() == 200 );
+ }
+
+ @Test
+ public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived(){
+ String url = getURL()+ "?page=" + RandomStringUtils.randomNumeric(5) + "&size=2";
+ Response response = RestAssured.given().get(url);
+
+ assertTrue(response.getStatusCode() == 500 );
+ }
+
+ @Test
+ public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources(){
+ Response response = RestAssured.given().get(getURL() + "?page=1&size=2" );
+ assertFalse(response.getBody().jsonPath().getList("content").isEmpty() );
+ }
+
+}
diff --git a/spring-rest-docs/src/main/java/com/example/CRUDController.java b/spring-rest-docs/src/main/java/com/example/CRUDController.java
index 818b29d3a6..ff8c91d6cd 100644
--- a/spring-rest-docs/src/main/java/com/example/CRUDController.java
+++ b/spring-rest-docs/src/main/java/com/example/CRUDController.java
@@ -17,39 +17,39 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/crud")
public class CRUDController {
-
- @RequestMapping(method=RequestMethod.GET)
- @ResponseStatus(HttpStatus.OK)
- public List read(@RequestBody CrudInput crudInput) {
- List returnList=new ArrayList();
- returnList.add(crudInput);
- return returnList;
- }
-
- @ResponseStatus(HttpStatus.CREATED)
- @RequestMapping(method=RequestMethod.POST)
- public HttpHeaders save(@RequestBody CrudInput crudInput) {
- HttpHeaders httpHeaders = new HttpHeaders();
- httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getTitle()).toUri());
- return httpHeaders;
- }
-
- @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
- @ResponseStatus(HttpStatus.OK)
- HttpHeaders delete(@RequestBody CrudInput crudInput) {
- HttpHeaders httpHeaders = new HttpHeaders();
- return httpHeaders;
- }
-
- @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
- @ResponseStatus(HttpStatus.ACCEPTED)
- void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
-
- }
-
- @RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
- @ResponseStatus(HttpStatus.NO_CONTENT)
- void patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
-
- }
+
+ @RequestMapping(method = RequestMethod.GET)
+ @ResponseStatus(HttpStatus.OK)
+ public List read(@RequestBody CrudInput crudInput) {
+ List returnList = new ArrayList();
+ returnList.add(crudInput);
+ return returnList;
+ }
+
+ @ResponseStatus(HttpStatus.CREATED)
+ @RequestMapping(method = RequestMethod.POST)
+ public HttpHeaders save(@RequestBody CrudInput crudInput) {
+ HttpHeaders httpHeaders = new HttpHeaders();
+ httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getTitle()).toUri());
+ return httpHeaders;
+ }
+
+ @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
+ @ResponseStatus(HttpStatus.OK)
+ HttpHeaders delete(@RequestBody CrudInput crudInput) {
+ HttpHeaders httpHeaders = new HttpHeaders();
+ return httpHeaders;
+ }
+
+ @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
+ @ResponseStatus(HttpStatus.ACCEPTED)
+ void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
+
+ }
+
+ @RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ void patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
+
+ }
}
diff --git a/spring-rest-docs/src/main/java/com/example/CrudInput.java b/spring-rest-docs/src/main/java/com/example/CrudInput.java
index 3d91b7d45a..36ad67eb21 100644
--- a/spring-rest-docs/src/main/java/com/example/CrudInput.java
+++ b/spring-rest-docs/src/main/java/com/example/CrudInput.java
@@ -10,33 +10,32 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CrudInput {
-
- //@NotBlank
- private final String title;
- private final String body;
+ // @NotBlank
+ private final String title;
- private final List tagUris;
+ private final String body;
- @JsonCreator
- public CrudInput(@JsonProperty("title") String title,
- @JsonProperty("body") String body, @JsonProperty("tags") List tagUris) {
- this.title = title;
- this.body = body;
- this.tagUris = tagUris == null ? Collections.emptyList() : tagUris;
- }
+ private final List tagUris;
- public String getTitle() {
- return title;
- }
+ @JsonCreator
+ public CrudInput(@JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List tagUris) {
+ this.title = title;
+ this.body = body;
+ this.tagUris = tagUris == null ? Collections. emptyList() : tagUris;
+ }
- public String getBody() {
- return body;
- }
+ public String getTitle() {
+ return title;
+ }
- @JsonProperty("tags")
- public List getTagUris() {
- return this.tagUris;
- }
+ public String getBody() {
+ return body;
+ }
+
+ @JsonProperty("tags")
+ public List getTagUris() {
+ return this.tagUris;
+ }
}
\ No newline at end of file
diff --git a/spring-rest-docs/src/main/java/com/example/IndexController.java b/spring-rest-docs/src/main/java/com/example/IndexController.java
index a6b4537c43..6b896da416 100644
--- a/spring-rest-docs/src/main/java/com/example/IndexController.java
+++ b/spring-rest-docs/src/main/java/com/example/IndexController.java
@@ -1,6 +1,5 @@
package com.example;
-
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import org.springframework.hateoas.ResourceSupport;
@@ -12,11 +11,11 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/")
public class IndexController {
- @RequestMapping(method=RequestMethod.GET)
- public ResourceSupport index() {
- ResourceSupport index = new ResourceSupport();
- index.add(linkTo(CRUDController.class).withRel("crud"));
- return index;
- }
+ @RequestMapping(method = RequestMethod.GET)
+ public ResourceSupport index() {
+ ResourceSupport index = new ResourceSupport();
+ index.add(linkTo(CRUDController.class).withRel("crud"));
+ return index;
+ }
}
\ No newline at end of file
diff --git a/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java b/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java
index dd20ef324e..da09f9accc 100644
--- a/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java
+++ b/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java
@@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringRestDocsApplication {
- public static void main(String[] args) {
- SpringApplication.run(SpringRestDocsApplication.class, args);
- }
+ public static void main(String[] args) {
+ SpringApplication.run(SpringRestDocsApplication.class, args);
+ }
}
diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java
index 195b9dc514..5b753aff0c 100644
--- a/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java
+++ b/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java
@@ -56,55 +56,35 @@ public class ApiDocumentation {
@Before
public void setUp() {
this.document = document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()));
- this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
- .apply(documentationConfiguration(this.restDocumentation))
- .alwaysDo(this.document)
- .build();
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(documentationConfiguration(this.restDocumentation)).alwaysDo(this.document).build();
}
-
@Test
public void headersExample() throws Exception {
- this.document.snippets(responseHeaders(headerWithName("Content-Type")
- .description("The Content-Type of the payload, e.g. `application/hal+json`")));
- this.mockMvc.perform(get("/"))
- .andExpect(status().isOk());
+ this.document.snippets(responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`")));
+ this.mockMvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void indexExample() throws Exception {
- this.document.snippets(
- links(linkWithRel("crud").description("The <>")),
- responseFields(fieldWithPath("_links").description("<> to other resources"))
- );
- this.mockMvc.perform(get("/"))
- .andExpect(status().isOk());
+ this.document.snippets(links(linkWithRel("crud").description("The <>")), responseFields(fieldWithPath("_links").description("<> to other resources")));
+ this.mockMvc.perform(get("/")).andExpect(status().isOk());
}
-
@Test
public void crudGetExample() throws Exception {
Map tag = new HashMap<>();
tag.put("name", "GET");
- String tagLocation = this.mockMvc.perform(get("/crud")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(tag)))
- .andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getHeader("Location");
+ String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isOk()).andReturn().getResponse().getHeader("Location");
Map crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
- this.mockMvc.perform(get("/crud")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(crud)))
- .andExpect(status().isOk());
+ this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isOk());
}
@Test
@@ -112,13 +92,7 @@ public class ApiDocumentation {
Map tag = new HashMap<>();
tag.put("name", "CREATE");
- String tagLocation = this.mockMvc.perform(post("/crud")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(tag)))
- .andExpect(status().isCreated())
- .andReturn()
- .getResponse()
- .getHeader("Location");
+ String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isCreated()).andReturn().getResponse().getHeader("Location");
Map crud = new HashMap<>();
crud.put("title", "Sample Model");
@@ -126,13 +100,9 @@ public class ApiDocumentation {
crud.put("tags", singletonList(tagLocation));
ConstrainedFields fields = new ConstrainedFields(CrudInput.class);
- this.document.snippets(requestFields(
- fields.withPath("title").description("The title of the note"),
- fields.withPath("body").description("The body of the note"),
- fields.withPath("tags").description("An array of tag resource URIs")));
+ this.document.snippets(requestFields(fields.withPath("title").description("The title of the note"), fields.withPath("body").description("The body of the note"), fields.withPath("tags").description("An array of tag resource URIs")));
this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isCreated());
-
}
@Test
@@ -141,23 +111,14 @@ public class ApiDocumentation {
Map tag = new HashMap<>();
tag.put("name", "DELETE");
- String tagLocation = this.mockMvc.perform(delete("/crud/10")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(tag)))
- .andExpect(status().isOk())
- .andReturn()
- .getResponse()
- .getHeader("Location");
+ String tagLocation = this.mockMvc.perform(delete("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isOk()).andReturn().getResponse().getHeader("Location");
Map crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
- this.mockMvc.perform(delete("/crud/10")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(crud)))
- .andExpect(status().isOk());
+ this.mockMvc.perform(delete("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isOk());
}
@Test
@@ -166,51 +127,31 @@ public class ApiDocumentation {
Map tag = new HashMap<>();
tag.put("name", "PATCH");
- String tagLocation = this.mockMvc.perform(patch("/crud/10")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(tag)))
- .andExpect(status().isNoContent())
- .andReturn()
- .getResponse()
- .getHeader("Location");
+ String tagLocation = this.mockMvc.perform(patch("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isNoContent()).andReturn().getResponse().getHeader("Location");
Map crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
- this.mockMvc.perform(patch("/crud/10")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(crud)))
- .andExpect(status().isNoContent());
+ this.mockMvc.perform(patch("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isNoContent());
}
-
@Test
public void crudPutExample() throws Exception {
Map tag = new HashMap<>();
tag.put("name", "PUT");
- String tagLocation = this.mockMvc.perform(put("/crud/10")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(tag)))
- .andExpect(status().isAccepted())
- .andReturn()
- .getResponse()
- .getHeader("Location");
+ String tagLocation = this.mockMvc.perform(put("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isAccepted()).andReturn().getResponse().getHeader("Location");
Map crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
- this.mockMvc.perform(put("/crud/10")
- .contentType(MediaTypes.HAL_JSON)
- .content(this.objectMapper.writeValueAsString(crud)))
- .andExpect(status().isAccepted());
+ this.mockMvc.perform(put("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isAccepted());
}
-
@Test
public void contextLoads() {
}
@@ -224,11 +165,8 @@ public class ApiDocumentation {
}
private FieldDescriptor withPath(String path) {
- return fieldWithPath(path)
- .attributes(key("constraints")
- .value(collectionToDelimitedString(this.constraintDescriptions.descriptionsForProperty(path), ". ")));
+ return fieldWithPath(path).attributes(key("constraints").value(collectionToDelimitedString(this.constraintDescriptions.descriptionsForProperty(path), ". ")));
}
}
-
}
diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java
index 7f3c4db1f9..7aea9d303c 100644
--- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java
+++ b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java
@@ -46,113 +46,105 @@ public class GettingStartedDocumentation {
private MockMvc mockMvc;
-
@Before
public void setUp() {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
- .apply(documentationConfiguration(this.restDocumentation))
- .alwaysDo(document("{method-name}/{step}/",
- preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
- .build();
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(documentationConfiguration(this.restDocumentation)).alwaysDo(document("{method-name}/{step}/", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()))).build();
}
@Test
public void index() throws Exception {
- this.mockMvc.perform(get("/").accept(MediaTypes.HAL_JSON))
- .andExpect(status().isOk())
- .andExpect(jsonPath("_links.crud", is(notNullValue())))
- .andExpect(jsonPath("_links.crud", is(notNullValue())));
+ this.mockMvc.perform(get("/").accept(MediaTypes.HAL_JSON)).andExpect(status().isOk()).andExpect(jsonPath("_links.crud", is(notNullValue()))).andExpect(jsonPath("_links.crud", is(notNullValue())));
}
-// String createNote() throws Exception {
-// Map note = new HashMap();
-// note.put("title", "Note creation with cURL");
-// note.put("body", "An example of how to create a note using curl");
-// String noteLocation = this.mockMvc.perform(post("/crud")
-// .contentType(MediaTypes.HAL_JSON)
-// .content(objectMapper.writeValueAsString(note)))
-// .andExpect(status().isCreated())
-// .andExpect(header().string("Location", notNullValue()))
-// .andReturn()
-// .getResponse()
-// .getHeader("Location");
-// return noteLocation;
-// }
-//
-// MvcResult getNote(String noteLocation) throws Exception {
-// return this.mockMvc.perform(get(noteLocation))
-// .andExpect(status().isOk())
-// .andExpect(jsonPath("title", is(notNullValue())))
-// .andExpect(jsonPath("body", is(notNullValue())))
-// .andExpect(jsonPath("_links.crud", is(notNullValue())))
-// .andReturn();
-// }
-//
-//
-// String createTag() throws Exception, JsonProcessingException {
-// Map tag = new HashMap();
-// tag.put("name", "getting-started");
-// String tagLocation = this.mockMvc.perform(post("/crud")
-// .contentType(MediaTypes.HAL_JSON)
-// .content(objectMapper.writeValueAsString(tag)))
-// .andExpect(status().isCreated())
-// .andExpect(header().string("Location", notNullValue()))
-// .andReturn()
-// .getResponse()
-// .getHeader("Location");
-// return tagLocation;
-// }
-//
-// void getTag(String tagLocation) throws Exception {
-// this.mockMvc.perform(get(tagLocation)).andExpect(status().isOk())
-// .andExpect(jsonPath("name", is(notNullValue())))
-// .andExpect(jsonPath("_links.tagged-notes", is(notNullValue())));
-// }
-//
-// String createTaggedNote(String tag) throws Exception {
-// Map note = new HashMap();
-// note.put("title", "Tagged note creation with cURL");
-// note.put("body", "An example of how to create a tagged note using cURL");
-// note.put("tags", Arrays.asList(tag));
-//
-// String noteLocation = this.mockMvc.perform(post("/notes")
-// .contentType(MediaTypes.HAL_JSON)
-// .content(objectMapper.writeValueAsString(note)))
-// .andExpect(status().isCreated())
-// .andExpect(header().string("Location", notNullValue()))
-// .andReturn()
-// .getResponse()
-// .getHeader("Location");
-// return noteLocation;
-// }
-//
-// void getTags(String noteTagsLocation) throws Exception {
-// this.mockMvc.perform(get(noteTagsLocation))
-// .andExpect(status().isOk())
-// .andExpect(jsonPath("_embedded.tags", hasSize(1)));
-// }
-//
-// void tagExistingNote(String noteLocation, String tagLocation) throws Exception {
-// Map update = new HashMap();
-// update.put("tags", Arrays.asList(tagLocation));
-// this.mockMvc.perform(patch(noteLocation)
-// .contentType(MediaTypes.HAL_JSON)
-// .content(objectMapper.writeValueAsString(update)))
-// .andExpect(status().isNoContent());
-// }
-//
-// MvcResult getTaggedExistingNote(String noteLocation) throws Exception {
-// return this.mockMvc.perform(get(noteLocation)).andExpect(status().isOk()).andReturn();
-// }
-//
-// void getTagsForExistingNote(String noteTagsLocation) throws Exception {
-// this.mockMvc.perform(get(noteTagsLocation))
-// .andExpect(status().isOk()).andExpect(jsonPath("_embedded.tags", hasSize(1)));
-// }
-//
-// private String getLink(MvcResult result, String rel)
-// throws UnsupportedEncodingException {
-// return JsonPath.parse(result.getResponse().getContentAsString()).read("_links." + rel + ".href");
-// }
+ // String createNote() throws Exception {
+ // Map note = new HashMap();
+ // note.put("title", "Note creation with cURL");
+ // note.put("body", "An example of how to create a note using curl");
+ // String noteLocation = this.mockMvc.perform(post("/crud")
+ // .contentType(MediaTypes.HAL_JSON)
+ // .content(objectMapper.writeValueAsString(note)))
+ // .andExpect(status().isCreated())
+ // .andExpect(header().string("Location", notNullValue()))
+ // .andReturn()
+ // .getResponse()
+ // .getHeader("Location");
+ // return noteLocation;
+ // }
+ //
+ // MvcResult getNote(String noteLocation) throws Exception {
+ // return this.mockMvc.perform(get(noteLocation))
+ // .andExpect(status().isOk())
+ // .andExpect(jsonPath("title", is(notNullValue())))
+ // .andExpect(jsonPath("body", is(notNullValue())))
+ // .andExpect(jsonPath("_links.crud", is(notNullValue())))
+ // .andReturn();
+ // }
+ //
+ //
+ // String createTag() throws Exception, JsonProcessingException {
+ // Map tag = new HashMap();
+ // tag.put("name", "getting-started");
+ // String tagLocation = this.mockMvc.perform(post("/crud")
+ // .contentType(MediaTypes.HAL_JSON)
+ // .content(objectMapper.writeValueAsString(tag)))
+ // .andExpect(status().isCreated())
+ // .andExpect(header().string("Location", notNullValue()))
+ // .andReturn()
+ // .getResponse()
+ // .getHeader("Location");
+ // return tagLocation;
+ // }
+ //
+ // void getTag(String tagLocation) throws Exception {
+ // this.mockMvc.perform(get(tagLocation)).andExpect(status().isOk())
+ // .andExpect(jsonPath("name", is(notNullValue())))
+ // .andExpect(jsonPath("_links.tagged-notes", is(notNullValue())));
+ // }
+ //
+ // String createTaggedNote(String tag) throws Exception {
+ // Map note = new HashMap();
+ // note.put("title", "Tagged note creation with cURL");
+ // note.put("body", "An example of how to create a tagged note using cURL");
+ // note.put("tags", Arrays.asList(tag));
+ //
+ // String noteLocation = this.mockMvc.perform(post("/notes")
+ // .contentType(MediaTypes.HAL_JSON)
+ // .content(objectMapper.writeValueAsString(note)))
+ // .andExpect(status().isCreated())
+ // .andExpect(header().string("Location", notNullValue()))
+ // .andReturn()
+ // .getResponse()
+ // .getHeader("Location");
+ // return noteLocation;
+ // }
+ //
+ // void getTags(String noteTagsLocation) throws Exception {
+ // this.mockMvc.perform(get(noteTagsLocation))
+ // .andExpect(status().isOk())
+ // .andExpect(jsonPath("_embedded.tags", hasSize(1)));
+ // }
+ //
+ // void tagExistingNote(String noteLocation, String tagLocation) throws Exception {
+ // Map update = new HashMap();
+ // update.put("tags", Arrays.asList(tagLocation));
+ // this.mockMvc.perform(patch(noteLocation)
+ // .contentType(MediaTypes.HAL_JSON)
+ // .content(objectMapper.writeValueAsString(update)))
+ // .andExpect(status().isNoContent());
+ // }
+ //
+ // MvcResult getTaggedExistingNote(String noteLocation) throws Exception {
+ // return this.mockMvc.perform(get(noteLocation)).andExpect(status().isOk()).andReturn();
+ // }
+ //
+ // void getTagsForExistingNote(String noteTagsLocation) throws Exception {
+ // this.mockMvc.perform(get(noteTagsLocation))
+ // .andExpect(status().isOk()).andExpect(jsonPath("_embedded.tags", hasSize(1)));
+ // }
+ //
+ // private String getLink(MvcResult result, String rel)
+ // throws UnsupportedEncodingException {
+ // return JsonPath.parse(result.getResponse().getContentAsString()).read("_links." + rel + ".href");
+ // }
}
diff --git a/spring-scurity-custom-permission/README.MD b/spring-scurity-custom-permission/README.MD
deleted file mode 100644
index 8fb14fa522..0000000000
--- a/spring-scurity-custom-permission/README.MD
+++ /dev/null
@@ -1,2 +0,0 @@
-###The Course
-The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
diff --git a/spring-security-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch
deleted file mode 100644
index 627021fb96..0000000000
--- a/spring-security-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
diff --git a/spring-security-basic-auth/.settings/.jsdtscope b/spring-security-basic-auth/.settings/.jsdtscope
deleted file mode 100644
index 7b3f0c8b9f..0000000000
--- a/spring-security-basic-auth/.settings/.jsdtscope
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/spring-security-basic-auth/.settings/org.eclipse.jdt.core.prefs b/spring-security-basic-auth/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index fb671a82a6..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,95 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.8
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=error
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=error
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.8
diff --git a/spring-security-basic-auth/.settings/org.eclipse.jdt.ui.prefs b/spring-security-basic-auth/.settings/org.eclipse.jdt.ui.prefs
deleted file mode 100644
index 471e9b0d81..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.jdt.ui.prefs
+++ /dev/null
@@ -1,55 +0,0 @@
-#Sat Jan 21 23:04:06 EET 2012
-eclipse.preferences.version=1
-editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
-sp_cleanup.add_default_serial_version_id=true
-sp_cleanup.add_generated_serial_version_id=false
-sp_cleanup.add_missing_annotations=true
-sp_cleanup.add_missing_deprecated_annotations=true
-sp_cleanup.add_missing_methods=false
-sp_cleanup.add_missing_nls_tags=false
-sp_cleanup.add_missing_override_annotations=true
-sp_cleanup.add_missing_override_annotations_interface_methods=true
-sp_cleanup.add_serial_version_id=false
-sp_cleanup.always_use_blocks=true
-sp_cleanup.always_use_parentheses_in_expressions=true
-sp_cleanup.always_use_this_for_non_static_field_access=false
-sp_cleanup.always_use_this_for_non_static_method_access=false
-sp_cleanup.convert_to_enhanced_for_loop=true
-sp_cleanup.correct_indentation=true
-sp_cleanup.format_source_code=true
-sp_cleanup.format_source_code_changes_only=true
-sp_cleanup.make_local_variable_final=true
-sp_cleanup.make_parameters_final=true
-sp_cleanup.make_private_fields_final=false
-sp_cleanup.make_type_abstract_if_missing_method=false
-sp_cleanup.make_variable_declarations_final=true
-sp_cleanup.never_use_blocks=false
-sp_cleanup.never_use_parentheses_in_expressions=false
-sp_cleanup.on_save_use_additional_actions=true
-sp_cleanup.organize_imports=true
-sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
-sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
-sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
-sp_cleanup.remove_private_constructors=true
-sp_cleanup.remove_trailing_whitespaces=true
-sp_cleanup.remove_trailing_whitespaces_all=true
-sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
-sp_cleanup.remove_unnecessary_casts=true
-sp_cleanup.remove_unnecessary_nls_tags=false
-sp_cleanup.remove_unused_imports=true
-sp_cleanup.remove_unused_local_variables=false
-sp_cleanup.remove_unused_private_fields=true
-sp_cleanup.remove_unused_private_members=false
-sp_cleanup.remove_unused_private_methods=true
-sp_cleanup.remove_unused_private_types=true
-sp_cleanup.sort_members=false
-sp_cleanup.sort_members_all=false
-sp_cleanup.use_blocks=false
-sp_cleanup.use_blocks_only_for_return_and_throw=false
-sp_cleanup.use_parentheses_in_expressions=false
-sp_cleanup.use_this_for_non_static_field_access=true
-sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
-sp_cleanup.use_this_for_non_static_method_access=true
-sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/spring-security-basic-auth/.settings/org.eclipse.m2e.core.prefs b/spring-security-basic-auth/.settings/org.eclipse.m2e.core.prefs
deleted file mode 100644
index f897a7f1cb..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.m2e.core.prefs
+++ /dev/null
@@ -1,4 +0,0 @@
-activeProfiles=
-eclipse.preferences.version=1
-resolveWorkspaceProjects=true
-version=1
diff --git a/spring-security-basic-auth/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-basic-auth/.settings/org.eclipse.m2e.wtp.prefs
deleted file mode 100644
index ef86089622..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.m2e.wtp.prefs
+++ /dev/null
@@ -1,2 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false
diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.common.component b/spring-security-basic-auth/.settings/org.eclipse.wst.common.component
deleted file mode 100644
index 9a8276c85b..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.wst.common.component
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml
deleted file mode 100644
index f5888c1411..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container
deleted file mode 100644
index 3bd5d0a480..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container
+++ /dev/null
@@ -1 +0,0 @@
-org.eclipse.wst.jsdt.launching.baseBrowserLibrary
\ No newline at end of file
diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name
deleted file mode 100644
index 05bd71b6ec..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name
+++ /dev/null
@@ -1 +0,0 @@
-Window
\ No newline at end of file
diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.validation.prefs b/spring-security-basic-auth/.settings/org.eclipse.wst.validation.prefs
deleted file mode 100644
index 0d0aee4f72..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.wst.validation.prefs
+++ /dev/null
@@ -1,15 +0,0 @@
-DELEGATES_PREFERENCE=delegateValidatorList
-USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
-USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
-USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633
-disabled=06target
-eclipse.preferences.version=1
-override=true
-suspend=false
-vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01
-vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01
-vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02
-vf.version=3
diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-basic-auth/.settings/org.eclipse.wst.ws.service.policy.prefs
deleted file mode 100644
index 9cfcabe16f..0000000000
--- a/spring-security-basic-auth/.settings/org.eclipse.wst.ws.service.policy.prefs
+++ /dev/null
@@ -1,2 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.wst.ws.service.policy.projectEnabled=false
diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java
index 86b81cdcee..112d502105 100644
--- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java
+++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java
@@ -1,8 +1,5 @@
package org.baeldung.persistence.model;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
import java.util.Set;
import javax.persistence.Column;
@@ -16,14 +13,8 @@ import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import org.springframework.security.core.userdetails.UserDetails;
-
@Entity
-public class User implements UserDetails {
-
- private static final long serialVersionUID = 1L;
+public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@@ -57,7 +48,6 @@ public class User implements UserDetails {
this.id = id;
}
- @Override
public String getUsername() {
return username;
}
@@ -66,7 +56,6 @@ public class User implements UserDetails {
this.username = username;
}
- @Override
public String getPassword() {
return password;
}
@@ -93,37 +82,6 @@ public class User implements UserDetails {
//
- @Override
- public Collection extends GrantedAuthority> getAuthorities() {
- final List authorities = new ArrayList();
- for (final Privilege privilege : this.getPrivileges()) {
- authorities.add(new SimpleGrantedAuthority(privilege.getName()));
- }
- return authorities;
- }
-
- @Override
- public boolean isAccountNonExpired() {
- return true;
- }
-
- @Override
- public boolean isAccountNonLocked() {
- return true;
- }
-
- @Override
- public boolean isCredentialsNonExpired() {
- return true;
- }
-
- @Override
- public boolean isEnabled() {
- return true;
- }
-
- //
-
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java
index a3f4644592..2d84536a14 100644
--- a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java
+++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java
@@ -16,7 +16,7 @@ public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot i
//
public boolean isMember(Long OrganizationId) {
- final User user = (User) this.getPrincipal();
+ final User user = ((MyUserPrincipal) this.getPrincipal()).getUser();
return user.getOrganization().getId().longValue() == OrganizationId.longValue();
}
diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java
index e81f9f8939..5d96673a8f 100644
--- a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java
+++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java
@@ -10,17 +10,10 @@ public class CustomPermissionEvaluator implements PermissionEvaluator {
@Override
public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {
- System.out.println(auth);
if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)) {
return false;
}
- String targetType = "";
- if (targetDomainObject instanceof String) {
- targetType = targetDomainObject.toString().toUpperCase();
- } else {
- targetType = targetDomainObject.getClass().getSimpleName().toUpperCase();
- System.out.println(targetType);
- }
+ final String targetType = targetDomainObject.getClass().getSimpleName().toUpperCase();
return hasPrivilege(auth, targetType, permission.toString().toUpperCase());
}
diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java
index a09d166798..4d3561b325 100644
--- a/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java
+++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java
@@ -47,6 +47,14 @@ public class MySecurityExpressionRoot implements MethodSecurityExpressionOperati
throw new RuntimeException("method hasAuthority() not allowed");
}
+ //
+ public boolean isMember(Long OrganizationId) {
+ final User user = ((MyUserPrincipal) this.getPrincipal()).getUser();
+ return user.getOrganization().getId().longValue() == OrganizationId.longValue();
+ }
+
+ //
+
@Override
public final boolean hasAnyAuthority(String... authorities) {
return hasAnyAuthorityName(null, authorities);
@@ -168,14 +176,6 @@ public class MySecurityExpressionRoot implements MethodSecurityExpressionOperati
return defaultRolePrefix + role;
}
- //
- public boolean isMember(Long OrganizationId) {
- final User user = (User) this.getPrincipal();
- return user.getOrganization().getId().longValue() == OrganizationId.longValue();
- }
-
- //
-
@Override
public Object getFilterObject() {
return this.filterObject;
diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java
index 19276a906e..685219728f 100644
--- a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java
+++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java
@@ -26,6 +26,6 @@ public class MyUserDetailsService implements UserDetailsService {
if (user == null) {
throw new UsernameNotFoundException(username);
}
- return user;
+ return new MyUserPrincipal(user);
}
}
diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java
new file mode 100644
index 0000000000..437bb02cdb
--- /dev/null
+++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java
@@ -0,0 +1,72 @@
+package org.baeldung.security;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.baeldung.persistence.model.Privilege;
+import org.baeldung.persistence.model.User;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+public class MyUserPrincipal implements UserDetails {
+
+ private static final long serialVersionUID = 1L;
+
+ private final User user;
+
+ //
+
+ public MyUserPrincipal(User user) {
+ this.user = user;
+ }
+
+ //
+
+ @Override
+ public String getUsername() {
+ return user.getUsername();
+ }
+
+ @Override
+ public String getPassword() {
+ return user.getPassword();
+ }
+
+ @Override
+ public Collection extends GrantedAuthority> getAuthorities() {
+ final List authorities = new ArrayList();
+ for (final Privilege privilege : user.getPrivileges()) {
+ authorities.add(new SimpleGrantedAuthority(privilege.getName()));
+ }
+ return authorities;
+ }
+
+ @Override
+ public boolean isAccountNonExpired() {
+ return true;
+ }
+
+ @Override
+ public boolean isAccountNonLocked() {
+ return true;
+ }
+
+ @Override
+ public boolean isCredentialsNonExpired() {
+ return true;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+
+ //
+
+ public User getUser() {
+ return user;
+ }
+
+}
diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java
index 7e279907c6..4752f7bdd9 100644
--- a/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java
+++ b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java
@@ -21,7 +21,8 @@ public class MainController {
@Autowired
private OrganizationRepository organizationRepository;
- @PreAuthorize("hasPermission('Foo', 'read')")
+ // @PostAuthorize("hasPermission(returnObject, 'read')")
+ @PreAuthorize("hasPermission(#id, 'Foo', 'read')")
@RequestMapping(method = RequestMethod.GET, value = "/foos/{id}")
@ResponseBody
public Foo findById(@PathVariable final long id) {
diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java
index fcb28f6ae2..aeb2428326 100644
--- a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java
+++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java
@@ -44,8 +44,9 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter {
http
.csrf().disable()
.authorizeRequests()
- .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
- .anyRequest().authenticated()
+ .antMatchers("/auth/admin/*").hasRole("ADMIN")
+ .antMatchers("/auth/*").hasAnyRole("ADMIN","USER")
+ .antMatchers("/*").permitAll()
.and()
.httpBasic()
.and()
diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java
index 143e52d94e..3e5d6435b3 100644
--- a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java
+++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java
@@ -14,24 +14,25 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
- public WebConfig() {
- super();
- }
+ public WebConfig() {
+ super();
+ }
- @Bean
- public ViewResolver viewResolver() {
- final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
- viewResolver.setPrefix("/WEB-INF/view/");
- viewResolver.setSuffix(".jsp");
- return viewResolver;
- }
+ @Bean
+ public ViewResolver viewResolver() {
+ final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
+ viewResolver.setPrefix("/WEB-INF/view/");
+ viewResolver.setSuffix(".jsp");
+ return viewResolver;
+ }
- // API
- @Override
- public void addViewControllers(final ViewControllerRegistry registry) {
- super.addViewControllers(registry);
- registry.addViewController("/graph.html");
- registry.addViewController("/csrfHome.html");
- }
+ // API
+ @Override
+ public void addViewControllers(final ViewControllerRegistry registry) {
+ super.addViewControllers(registry);
+ registry.addViewController("/graph.html");
+ registry.addViewController("/csrfHome.html");
+ registry.addViewController("/homepage.html");
+ }
}
\ No newline at end of file
diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java
index 1a4322c611..64a29f20d3 100644
--- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java
+++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java
@@ -12,21 +12,22 @@ import org.springframework.web.bind.annotation.ResponseStatus;
// to test csrf
@Controller
+@RequestMapping(value = "/auth/")
public class BankController {
- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());
- @RequestMapping(value = "/transfer", method = RequestMethod.GET)
- @ResponseBody
- public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
- logger.info("Transfer to {}", accountNo);
- return amount;
- }
+ @RequestMapping(value = "/transfer", method = RequestMethod.GET)
+ @ResponseBody
+ public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
+ logger.info("Transfer to {}", accountNo);
+ return amount;
+ }
- // write - just for test
- @RequestMapping(value = "/transfer", method = RequestMethod.POST)
- @ResponseStatus(HttpStatus.OK)
- public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
- logger.info("Transfer to {}", accountNo);
+ // write - just for test
+ @RequestMapping(value = "/transfer", method = RequestMethod.POST)
+ @ResponseStatus(HttpStatus.OK)
+ public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
+ logger.info("Transfer to {}", accountNo);
- }
+ }
}
diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java
index 20307447b2..1e00d6350b 100644
--- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java
+++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java
@@ -29,93 +29,93 @@ import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.base.Preconditions;
@Controller
-@RequestMapping(value = "/foos")
+@RequestMapping(value = "/auth/foos")
public class FooController {
- @Autowired
- private ApplicationEventPublisher eventPublisher;
+ @Autowired
+ private ApplicationEventPublisher eventPublisher;
- @Autowired
- private IFooService service;
+ @Autowired
+ private IFooService service;
- public FooController() {
- super();
- }
+ public FooController() {
+ super();
+ }
- // API
+ // API
- @RequestMapping(method = RequestMethod.GET, value = "/count")
- @ResponseBody
- @ResponseStatus(value = HttpStatus.OK)
- public long count() {
- return 2l;
- }
+ @RequestMapping(method = RequestMethod.GET, value = "/count")
+ @ResponseBody
+ @ResponseStatus(value = HttpStatus.OK)
+ public long count() {
+ return 2l;
+ }
- // read - one
+ // read - one
- @RequestMapping(value = "/{id}", method = RequestMethod.GET)
- @ResponseBody
- public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
- final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
+ @RequestMapping(value = "/{id}", method = RequestMethod.GET)
+ @ResponseBody
+ public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
+ final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
- eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
- return resourceById;
- }
+ eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
+ return resourceById;
+ }
- // read - all
+ // read - all
- @RequestMapping(method = RequestMethod.GET)
- @ResponseBody
- public List findAll() {
- return service.findAll();
- }
+ @RequestMapping(method = RequestMethod.GET)
+ @ResponseBody
+ public List findAll() {
+ return service.findAll();
+ }
- @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
- @ResponseBody
- public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
- final Page resultPage = service.findPaginated(page, size);
- if (page > resultPage.getTotalPages()) {
- throw new MyResourceNotFoundException();
- }
- eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
+ @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
+ @ResponseBody
+ public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
+ final Page resultPage = service.findPaginated(page, size);
+ if (page > resultPage.getTotalPages()) {
+ throw new MyResourceNotFoundException();
+ }
+ eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
- return resultPage.getContent();
- }
+ return resultPage.getContent();
+ }
- // write
+ // write
- @RequestMapping(method = RequestMethod.POST)
- @ResponseStatus(HttpStatus.CREATED)
- @ResponseBody
- public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
- Preconditions.checkNotNull(resource);
- final Foo foo = service.create(resource);
- final Long idOfCreatedResource = foo.getId();
+ @RequestMapping(method = RequestMethod.POST)
+ @ResponseStatus(HttpStatus.CREATED)
+ @ResponseBody
+ public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
+ Preconditions.checkNotNull(resource);
+ final Foo foo = service.create(resource);
+ final Long idOfCreatedResource = foo.getId();
- eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
+ eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
- return foo;
- }
+ return foo;
+ }
- @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
- @ResponseStatus(HttpStatus.OK)
- public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
- Preconditions.checkNotNull(resource);
- RestPreconditions.checkFound(service.findOne(resource.getId()));
- service.update(resource);
- }
+ @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
+ @ResponseStatus(HttpStatus.OK)
+ public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
+ Preconditions.checkNotNull(resource);
+ RestPreconditions.checkFound(service.findOne(resource.getId()));
+ service.update(resource);
+ }
- @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
- @ResponseStatus(HttpStatus.OK)
- public void delete(@PathVariable("id") final Long id) {
- service.deleteById(id);
- }
+ @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
+ @ResponseStatus(HttpStatus.OK)
+ public void delete(@PathVariable("id") final Long id) {
+ service.deleteById(id);
+ }
- @RequestMapping(method = RequestMethod.HEAD)
- @ResponseStatus(HttpStatus.OK)
- public void head(final HttpServletResponse resp) {
- resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
- resp.setHeader("bar", "baz");
- }
+ @RequestMapping(method = RequestMethod.HEAD)
+ @ResponseStatus(HttpStatus.OK)
+ public void head(final HttpServletResponse resp) {
+ resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
+ resp.setHeader("bar", "baz");
+ }
}
diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java
new file mode 100644
index 0000000000..3e6a6627df
--- /dev/null
+++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java
@@ -0,0 +1,14 @@
+package org.baeldung.web.controller;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+@Controller
+@RequestMapping(value = "/")
+public class HomeController {
+
+ public String index() {
+ return "homepage";
+ }
+
+}
diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java
index e83b8cf5ba..bcf0ceb5e6 100644
--- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java
+++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java
@@ -20,65 +20,66 @@ import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriTemplate;
@Controller
+@RequestMapping(value = "/auth/")
public class RootController {
- @Autowired
- private IMetricService metricService;
+ @Autowired
+ private IMetricService metricService;
- @Autowired
- private IActuatorMetricService actMetricService;
+ @Autowired
+ private IActuatorMetricService actMetricService;
- public RootController() {
- super();
- }
+ public RootController() {
+ super();
+ }
- // API
+ // API
- // discover
+ // discover
- @RequestMapping(value = "admin", method = RequestMethod.GET)
- @ResponseStatus(value = HttpStatus.NO_CONTENT)
- public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
- final String rootUri = request.getRequestURL().toString();
+ @RequestMapping(value = "admin", method = RequestMethod.GET)
+ @ResponseStatus(value = HttpStatus.NO_CONTENT)
+ public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
+ final String rootUri = request.getRequestURL().toString();
- final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
- final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
- response.addHeader("Link", linkToFoo);
- }
+ final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
+ final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
+ response.addHeader("Link", linkToFoo);
+ }
- @RequestMapping(value = "/metric", method = RequestMethod.GET)
- @ResponseBody
- public Map getMetric() {
- return metricService.getFullMetric();
- }
+ @RequestMapping(value = "/metric", method = RequestMethod.GET)
+ @ResponseBody
+ public Map getMetric() {
+ return metricService.getFullMetric();
+ }
- @PreAuthorize("hasRole('ROLE_ADMIN')")
- @RequestMapping(value = "/status-metric", method = RequestMethod.GET)
- @ResponseBody
- public Map getStatusMetric() {
- return metricService.getStatusMetric();
- }
+ @PreAuthorize("hasRole('ROLE_ADMIN')")
+ @RequestMapping(value = "/status-metric", method = RequestMethod.GET)
+ @ResponseBody
+ public Map getStatusMetric() {
+ return metricService.getStatusMetric();
+ }
- @RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
- @ResponseBody
- public Object[][] drawMetric() {
- final Object[][] result = metricService.getGraphData();
- for (int i = 1; i < result[0].length; i++) {
- result[0][i] = result[0][i].toString();
- }
- return result;
- }
+ @RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
+ @ResponseBody
+ public Object[][] drawMetric() {
+ final Object[][] result = metricService.getGraphData();
+ for (int i = 1; i < result[0].length; i++) {
+ result[0][i] = result[0][i].toString();
+ }
+ return result;
+ }
- @RequestMapping(value = "/admin/x", method = RequestMethod.GET)
- @ResponseBody
- public String sampleAdminPage() {
- return "Hello";
- }
+ @RequestMapping(value = "/admin/x", method = RequestMethod.GET)
+ @ResponseBody
+ public String sampleAdminPage() {
+ return "Hello";
+ }
- @RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
- @ResponseBody
- public String sampleErrorPage() {
- return "Error Occurred";
- }
+ @RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
+ @ResponseBody
+ public String sampleErrorPage() {
+ return "Error Occurred";
+ }
}
diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java
index 7c28ed8e80..2228287f4d 100644
--- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java
+++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java
@@ -37,96 +37,97 @@ import cz.jirutka.rsql.parser.ast.Node;
//@EnableSpringDataWebSupport
@Controller
+@RequestMapping(value = "/auth/")
public class UserController {
- @Autowired
- private IUserDAO service;
+ @Autowired
+ private IUserDAO service;
- @Autowired
- private UserRepository dao;
+ @Autowired
+ private UserRepository dao;
- @Autowired
- private MyUserRepository myUserRepository;
+ @Autowired
+ private MyUserRepository myUserRepository;
- public UserController() {
- super();
- }
+ public UserController() {
+ super();
+ }
- // API - READ
+ // API - READ
- @RequestMapping(method = RequestMethod.GET, value = "/users")
- @ResponseBody
- public List findAll(@RequestParam(value = "search", required = false) final String search) {
- final List params = new ArrayList();
- if (search != null) {
- final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
- final Matcher matcher = pattern.matcher(search + ",");
- while (matcher.find()) {
- params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
- }
- }
- return service.searchUser(params);
- }
+ @RequestMapping(method = RequestMethod.GET, value = "/users")
+ @ResponseBody
+ public List findAll(@RequestParam(value = "search", required = false) final String search) {
+ final List params = new ArrayList();
+ if (search != null) {
+ final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
+ final Matcher matcher = pattern.matcher(search + ",");
+ while (matcher.find()) {
+ params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
+ }
+ }
+ return service.searchUser(params);
+ }
- @RequestMapping(method = RequestMethod.GET, value = "/users/spec")
- @ResponseBody
- public List findAllBySpecification(@RequestParam(value = "search") final String search) {
- final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
- final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
- final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
- final Matcher matcher = pattern.matcher(search + ",");
- while (matcher.find()) {
- builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
- }
+ @RequestMapping(method = RequestMethod.GET, value = "/users/spec")
+ @ResponseBody
+ public List findAllBySpecification(@RequestParam(value = "search") final String search) {
+ final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
+ final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
+ final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
+ final Matcher matcher = pattern.matcher(search + ",");
+ while (matcher.find()) {
+ builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
+ }
- final Specification spec = builder.build();
- return dao.findAll(spec);
- }
+ final Specification spec = builder.build();
+ return dao.findAll(spec);
+ }
- @RequestMapping(method = RequestMethod.GET, value = "/myusers")
- @ResponseBody
- public Iterable findAllByQuerydsl(@RequestParam(value = "search") final String search) {
- final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
- if (search != null) {
- final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
- final Matcher matcher = pattern.matcher(search + ",");
- while (matcher.find()) {
- builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
- }
- }
- final BooleanExpression exp = builder.build();
- return myUserRepository.findAll(exp);
- }
+ @RequestMapping(method = RequestMethod.GET, value = "/myusers")
+ @ResponseBody
+ public Iterable findAllByQuerydsl(@RequestParam(value = "search") final String search) {
+ final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
+ if (search != null) {
+ final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
+ final Matcher matcher = pattern.matcher(search + ",");
+ while (matcher.find()) {
+ builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
+ }
+ }
+ final BooleanExpression exp = builder.build();
+ return myUserRepository.findAll(exp);
+ }
- @RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
- @ResponseBody
- public List findAllByRsql(@RequestParam(value = "search") final String search) {
- final Node rootNode = new RSQLParser().parse(search);
- final Specification spec = rootNode.accept(new CustomRsqlVisitor());
- return dao.findAll(spec);
- }
+ @RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
+ @ResponseBody
+ public List findAllByRsql(@RequestParam(value = "search") final String search) {
+ final Node rootNode = new RSQLParser().parse(search);
+ final Specification spec = rootNode.accept(new CustomRsqlVisitor());
+ return dao.findAll(spec);
+ }
- @RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
- @ResponseBody
- public Iterable findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
- return myUserRepository.findAll(predicate);
- }
+ @RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
+ @ResponseBody
+ public Iterable findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
+ return myUserRepository.findAll(predicate);
+ }
- // API - WRITE
+ // API - WRITE
- @RequestMapping(method = RequestMethod.POST, value = "/users")
- @ResponseStatus(HttpStatus.CREATED)
- public void create(@RequestBody final User resource) {
- Preconditions.checkNotNull(resource);
- dao.save(resource);
- }
+ @RequestMapping(method = RequestMethod.POST, value = "/users")
+ @ResponseStatus(HttpStatus.CREATED)
+ public void create(@RequestBody final User resource) {
+ Preconditions.checkNotNull(resource);
+ dao.save(resource);
+ }
- @RequestMapping(method = RequestMethod.POST, value = "/myusers")
- @ResponseStatus(HttpStatus.CREATED)
- public void addMyUser(@RequestBody final MyUser resource) {
- Preconditions.checkNotNull(resource);
- myUserRepository.save(resource);
+ @RequestMapping(method = RequestMethod.POST, value = "/myusers")
+ @ResponseStatus(HttpStatus.CREATED)
+ public void addMyUser(@RequestBody final MyUser resource) {
+ Preconditions.checkNotNull(resource);
+ myUserRepository.save(resource);
- }
+ }
}
diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java
index 3af91b82a2..35b840a649 100644
--- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java
+++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java
@@ -23,26 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@WebAppConfiguration
public class CsrfAbstractIntegrationTest {
- @Autowired
- private WebApplicationContext context;
+ @Autowired
+ private WebApplicationContext context;
- @Autowired
- private Filter springSecurityFilterChain;
+ @Autowired
+ private Filter springSecurityFilterChain;
- protected MockMvc mvc;
+ protected MockMvc mvc;
- //
+ //
- @Before
- public void setup() {
- mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
- }
+ @Before
+ public void setup() {
+ mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
+ }
- protected RequestPostProcessor testUser() {
- return user("user").password("userPass").roles("USER");
- }
+ protected RequestPostProcessor testUser() {
+ return user("user").password("userPass").roles("USER");
+ }
- protected String createFoo() throws JsonProcessingException {
- return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
- }
+ protected RequestPostProcessor testAdmin() {
+ return user("admin").password("adminPass").roles("USER", "ADMIN");
+ }
+
+ protected String createFoo() throws JsonProcessingException {
+ return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
+ }
}
diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java
index 50b8ae3b44..1f5cf078f3 100644
--- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java
+++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java
@@ -1,5 +1,6 @@
package org.baeldung.security.csrf;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -13,14 +14,33 @@ import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
- @Test
- public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
- mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
- }
+ @Test
+ public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
+ mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
+ }
- @Test
- public void givenAuth_whenAddFoo_thenCreated() throws Exception {
- mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
- }
+ @Test
+ public void givenAuth_whenAddFoo_thenCreated() throws Exception {
+ mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
+ }
+
+ @Test
+ public void accessMainPageWithoutAuthorization() throws Exception {
+ mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
+ }
+
+ @Test
+ public void accessOtherPages() throws Exception {
+ mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100"))
+ .andExpect(status().isUnauthorized()); // without authorization
+ mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser()))
+ .andExpect(status().isOk()); // with authorization
+ }
+
+ @Test
+ public void accessAdminPage() throws Exception {
+ mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); //without authorization
+ mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); //with authorization
+ }
}
diff --git a/webjars/webjarsdemo/pom.xml b/webjars/pom.xml
similarity index 100%
rename from webjars/webjarsdemo/pom.xml
rename to webjars/pom.xml
diff --git a/webjars/webjarsdemo/src/main/java/com/baeldung/TestController.java b/webjars/src/main/java/com/baeldung/TestController.java
similarity index 100%
rename from webjars/webjarsdemo/src/main/java/com/baeldung/TestController.java
rename to webjars/src/main/java/com/baeldung/TestController.java
diff --git a/webjars/webjarsdemo/src/main/java/com/baeldung/WebjarsdemoApplication.java b/webjars/src/main/java/com/baeldung/WebjarsdemoApplication.java
similarity index 100%
rename from webjars/webjarsdemo/src/main/java/com/baeldung/WebjarsdemoApplication.java
rename to webjars/src/main/java/com/baeldung/WebjarsdemoApplication.java
diff --git a/webjars/webjarsdemo/src/main/resources/templates/index.html b/webjars/src/main/resources/templates/index.html
similarity index 100%
rename from webjars/webjarsdemo/src/main/resources/templates/index.html
rename to webjars/src/main/resources/templates/index.html
diff --git a/webjars/webjarsdemo/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java
similarity index 100%
rename from webjars/webjarsdemo/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java
rename to webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java
diff --git a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java
index d0e099e591..175250f47b 100644
--- a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java
+++ b/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java
@@ -15,6 +15,7 @@ import static org.xmlunit.matchers.HasXPathMatcher.hasXPath;
import java.io.File;
import java.util.Iterator;
+import org.junit.Ignore;
import org.junit.Test;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
@@ -36,10 +37,10 @@ public class XMLUnitTest {
public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(
- new XMLUnitTest().getClass().getResourceAsStream(
+ XMLUnitTest.class.getResourceAsStream(
"/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(
- new XMLUnitTest().getClass().getResourceAsStream(
+ XMLUnitTest.class.getResourceAsStream(
"/students_with_error.xml")).build());
assertFalse(r.isValid());
}
@@ -48,10 +49,10 @@ public class XMLUnitTest {
public void givenXmlWithErrors_whenReturnsValidationProblems_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(
- new XMLUnitTest().getClass().getResourceAsStream(
+ XMLUnitTest.class.getResourceAsStream(
"/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(
- new XMLUnitTest().getClass().getResourceAsStream(
+ XMLUnitTest.class.getResourceAsStream(
"/students_with_error.xml")).build());
Iterator probs = r.getProblems().iterator();
int count = 0;
@@ -66,10 +67,10 @@ public class XMLUnitTest {
public void givenXml_whenValidatesAgainstXsd_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(
- new XMLUnitTest().getClass().getResourceAsStream(
+ XMLUnitTest.class.getResourceAsStream(
"/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(
- new XMLUnitTest().getClass().getResourceAsStream(
+ XMLUnitTest.class.getResourceAsStream(
"/students.xml")).build());
Iterator probs = r.getProblems().iterator();
while (probs.hasNext()) {
@@ -117,11 +118,27 @@ public class XMLUnitTest {
@Test
public void givenXmlSource_whenFailsToValidateInExistentXPath_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
-
assertThat(Input.fromFile(new File(classLoader.getResource(
"teachers.xml").getFile())), not(hasXPath("//sujet")));
}
+ // NOTE: ignore as this test demonstrates that two XMLs that contain the same data
+ // will fail the isSimilarTo test.
+ @Test @Ignore
+ public void given2XMLS_whenSimilar_thenCorrect_fails() {
+ String controlXml = "3 false ";
+ String testXml = "false 3 ";
+ assertThat(testXml, isSimilarTo(controlXml));
+ }
+
+ @Test
+ public void given2XMLS_whenSimilar_thenCorrect() {
+ String controlXml = "3 false ";
+ String testXml = "false 3 ";
+ assertThat(testXml,isSimilarTo(controlXml).withNodeMatcher(
+ new DefaultNodeMatcher(ElementSelectors.byName)));
+ }
+
@Test
public void given2XMLs_whenSimilarWithDiff_thenCorrect() throws Exception {
String myControlXML = "3 false ";
@@ -160,6 +177,7 @@ public class XMLUnitTest {
Diff myDiff = DiffBuilder.compare(control).withTest(test)
.checkForSimilar().build();
+ // assertFalse(myDiff.toString(), myDiff.hasDifferences());
assertTrue(myDiff.toString(), myDiff.hasDifferences());
}
@@ -177,27 +195,23 @@ public class XMLUnitTest {
@Test
public void givenFileSourceAsObject_whenAbleToInput_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
- assertThat(Input.from(new File(classLoader.getResource("test.xml")
- .getFile())), isSimilarTo(Input.from(new File(classLoader
- .getResource("control.xml").getFile()))));
-
+ assertThat(Input.from(new File(classLoader.getResource("test.xml").getFile())),
+ isSimilarTo(Input.from(new File(classLoader.getResource("control.xml").getFile()))));
}
@Test
public void givenStreamAsSource_whenAbleToInput_thenCorrect() {
- assertThat(Input.fromStream(new XMLUnitTest().getClass()
+ assertThat(Input.fromStream(XMLUnitTest.class
.getResourceAsStream("/test.xml")),
- isSimilarTo(Input.fromStream(new XMLUnitTest().getClass()
+ isSimilarTo(Input.fromStream(XMLUnitTest.class
.getResourceAsStream("/control.xml"))));
}
@Test
public void givenStreamAsObject_whenAbleToInput_thenCorrect() {
- assertThat(Input.from(new XMLUnitTest().getClass().getResourceAsStream(
- "/test.xml")), isSimilarTo(Input.from(new XMLUnitTest()
- .getClass().getResourceAsStream("/control.xml"))));
-
+ assertThat(Input.from(XMLUnitTest.class.getResourceAsStream("/test.xml")),
+ isSimilarTo(Input.from(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
}
@Test
@@ -206,7 +220,6 @@ public class XMLUnitTest {
Input.from("3 false "),
isSimilarTo(Input
.from("3 false ")));
-
}
@Test
@@ -216,7 +229,6 @@ public class XMLUnitTest {
String controlPath = classLoader.getResource("control.xml").getPath();
assertThat(Input.fromFile(testPath),
isSimilarTo(Input.fromFile(controlPath)));
-
}
@Test