diff --git a/Step01.md b/Step01.md
index 56d3f20..4e841d9 100644
--- a/Step01.md
+++ b/Step01.md
@@ -19,45 +19,42 @@
- If you are comfortable with Spring, try to create a few dependencies and see if are automatically auto-wired!
## Files List
-### /pom.xml
+### pom.xml
```
- 4.0.0
- com.in28minutes
- springboot-for-beginners-example
- 0.0.1-SNAPSHOT
- Your First Spring Boot Example
- jar
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.in28minutes.springboot
+ first-springboot-project
+ 0.0.1-SNAPSHOT
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 1.4.0.RELEASE
+
-
- org.springframework.boot
- spring-boot-starter-parent
- 1.4.0.RELEASE
-
+
+ 1.8
+
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
-
- 1.8
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
```
-### /src/main/java/com/in28minutes/springboot/Application.java
+### src/main/java/com/in28minutes/springboot/Application.java
```
package com.in28minutes.springboot;
@@ -68,10 +65,10 @@ import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
- public static void main(String[] args) {
- ApplicationContext ctx = SpringApplication.run(Application.class, args);
+ public static void main(String[] args) {
+ ApplicationContext ctx = SpringApplication.run(Application.class, args);
- }
+ }
}
```
diff --git a/Step02.md b/Step02.md
index d8fe9ef..cf8a8ba 100644
--- a/Step02.md
+++ b/Step02.md
@@ -8,10 +8,38 @@
- @RestController
## Useful Snippets and References
+```
+package com.in28minutes.springboot;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class WelcomeController {
+
+ //Auto wiring
+ @Autowired
+ private WelcomeService service;
+
+ @RequestMapping("/welcome")
+ public String welcome() {
+ return service.retrieveWelcomeMessage();
+ }
+}
+@Component
+class WelcomeService {
+ public String retrieveWelcomeMessage() {
+ //Complex Method
+ return "Good Morning updated";
+ }
+}
+```
## Files List
-### /pom.xml
+### pom.xml
```
@@ -19,17 +47,16 @@
com.in28minutes.springboot
first-springboot-project
0.0.1-SNAPSHOT
-
-
- 1.8
-
-
org.springframework.boot
spring-boot-starter-parent
1.4.0.RELEASE
+
+ 1.8
+
+
org.springframework.boot
@@ -37,38 +64,32 @@
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
-
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
-
-
-
-
-
```
-### /src/main/java/com/in28minutes/service/WelcomeService.java
+### src/main/java/com/in28minutes/service/WelcomeService.java
```
package com.in28minutes.service;
import org.springframework.stereotype.Component;
-//Spring to manage this bean and create an instance of this
@Component
-public class WelcomeService{
+public class WelcomeService {
+
public String retrieveWelcomeMessage() {
//Complex Method
- return "Good Morning updated! ";
+ return "Good Morning updated";
}
}
```
-### /src/main/java/com/in28minutes/springboot/Application.java
+### src/main/java/com/in28minutes/springboot/Application.java
```
package com.in28minutes.springboot;
@@ -83,18 +104,16 @@ public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
- for (int i = 0; i < 10; i++)
- System.out.println("");
+
}
}
```
-### /src/main/java/com/in28minutes/springboot/WelcomeController.java
+### src/main/java/com/in28minutes/springboot/WelcomeController.java
```
package com.in28minutes.springboot;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -102,15 +121,14 @@ import com.in28minutes.service.WelcomeService;
@RestController
public class WelcomeController {
-
+
//Auto wiring
@Autowired
private WelcomeService service;
-
+
@RequestMapping("/welcome")
public String welcome() {
return service.retrieveWelcomeMessage();
}
}
-
```
diff --git a/Step03.md b/Step03.md
index 2f7a0e8..b2c5004 100644
--- a/Step03.md
+++ b/Step03.md
@@ -21,90 +21,97 @@
logging.level.org.springframework: DEBUG
```
-##Files List
-### /pom.xml
+## Files List
+### pom.xml
```
- 4.0.0
- com.in28minutes
- springboot-for-beginners-example
- 0.0.1-SNAPSHOT
- Your First Spring Boot Example
- jar
-
-
- org.springframework.boot
- spring-boot-starter-parent
- 1.4.0.RELEASE
-
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
-
-
- 1.8
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.in28minutes.springboot
+ first-springboot-project
+ 0.0.1-SNAPSHOT
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 1.4.0.RELEASE
+
+
+
+ 1.8
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
```
-### /src/main/java/com/in28minutes/springboot/Application.java
+### src/main/java/com/in28minutes/springboot/Application.java
```
package com.in28minutes.springboot;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
-import org.springframework.stereotype.Component;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class Application {
- public static void main(String[] args) {
- ApplicationContext ctx = SpringApplication.run(Application.class, args);
+ public static void main(String[] args) {
+ ApplicationContext ctx = SpringApplication.run(Application.class, args);
- }
+ }
- @RestController
- class SomeBean {
+}
+```
+### src/main/java/com/in28minutes/springboot/WelcomeController.java
+```
+package com.in28minutes.springboot;
- @Autowired
- private SomeDependency someDependency;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
- @RequestMapping("/")
- public String index() {
- return someDependency.getSomething();
- }
+@RestController
+public class WelcomeController {
- }
+ //Auto wiring
+ @Autowired
+ private WelcomeService service;
- @Component
- class SomeDependency {
+ @RequestMapping("/welcome")
+ public String welcome() {
+ return service.retrieveWelcomeMessage();
+ }
+}
+```
+### src/main/java/com/in28minutes/springboot/WelcomeService.java
+```
+package com.in28minutes.springboot;
- public String getSomething() {
- return "Hello! Welcome!";
- }
+import org.springframework.stereotype.Component;
- }
+@Component
+public class WelcomeService {
+ public String retrieveWelcomeMessage() {
+ //Complex Method
+ return "Good Morning updated";
+ }
}
```
-### /src/main/resources/application.properties
+### src/main/resources/application.properties
```
logging.level.org.springframework: DEBUG
```
diff --git a/src/main/java/com/in28minutes/springboot/Application.java b/src/main/java/com/in28minutes/springboot/Application.java
index b751928..476ab9c 100644
--- a/src/main/java/com/in28minutes/springboot/Application.java
+++ b/src/main/java/com/in28minutes/springboot/Application.java
@@ -9,16 +9,16 @@
@SpringBootApplication
public class Application {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- ApplicationContext ctx = SpringApplication.run(Application.class, args);
- String[] beanNames = ctx.getBeanDefinitionNames();
- Arrays.sort(beanNames);
+ ApplicationContext ctx = SpringApplication.run(Application.class, args);
+ String[] beanNames = ctx.getBeanDefinitionNames();
+ Arrays.sort(beanNames);
- for (String beanName : beanNames) {
- System.out.println(beanName);
- }
+ for (String beanName : beanNames) {
+ System.out.println(beanName);
+ }
- }
+ }
}
\ No newline at end of file
diff --git a/src/main/java/com/in28minutes/springboot/WelcomeController.java b/src/main/java/com/in28minutes/springboot/WelcomeController.java
index 5992780..6e39b35 100644
--- a/src/main/java/com/in28minutes/springboot/WelcomeController.java
+++ b/src/main/java/com/in28minutes/springboot/WelcomeController.java
@@ -14,37 +14,37 @@
@RestController
public class WelcomeController {
- @Autowired
- private SomeDependency someDependency;
-
- @Autowired
- private BasicConfiguration configuration;
-
- @RequestMapping("/")
- public String index() {
- return someDependency.getSomething();
- }
-
- @RequestMapping("/dynamic-configuration")
- public Map dynamicConfiguration() {
- // Not the best practice to use a map to store differnt types!
- Map map = new HashMap();
- map.put("message", configuration.getMessage());
- map.put("number", configuration.getNumber());
- map.put("key", configuration.isValue());
- return map;
- }
+ @Autowired
+ private SomeDependency someDependency;
+
+ @Autowired
+ private BasicConfiguration configuration;
+
+ @RequestMapping("/")
+ public String index() {
+ return someDependency.getSomething();
+ }
+
+ @RequestMapping("/dynamic-configuration")
+ public Map dynamicConfiguration() {
+ // Not the best practice to use a map to store differnt types!
+ Map map = new HashMap();
+ map.put("message", configuration.getMessage());
+ map.put("number", configuration.getNumber());
+ map.put("key", configuration.isValue());
+ return map;
+ }
}
@Component
class SomeDependency {
- @Value("${welcome.message}")
- private String welcomeMessage;
+ @Value("${welcome.message}")
+ private String welcomeMessage;
- public String getSomething() {
- return welcomeMessage;
- }
+ public String getSomething() {
+ return welcomeMessage;
+ }
}
diff --git a/src/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java b/src/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java
index 58b3b5e..72ce83f 100644
--- a/src/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java
+++ b/src/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java
@@ -6,32 +6,32 @@
@Component
@ConfigurationProperties("basic")
public class BasicConfiguration {
- private boolean value;
- private String message;
- private int number;
+ private boolean value;
+ private String message;
+ private int number;
- public boolean isValue() {
- return value;
- }
+ public boolean isValue() {
+ return value;
+ }
- public void setValue(boolean value) {
- this.value = value;
- }
+ public void setValue(boolean value) {
+ this.value = value;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public int getNumber() {
- return number;
- }
+ public int getNumber() {
+ return number;
+ }
- public void setNumber(int number) {
- this.number = number;
- }
+ public void setNumber(int number) {
+ this.number = number;
+ }
}
diff --git a/src/main/java/com/in28minutes/springboot/controller/SurveyController.java b/src/main/java/com/in28minutes/springboot/controller/SurveyController.java
index 4c98353..c1b5202 100644
--- a/src/main/java/com/in28minutes/springboot/controller/SurveyController.java
+++ b/src/main/java/com/in28minutes/springboot/controller/SurveyController.java
@@ -17,35 +17,35 @@
@RestController
class SurveyController {
- @Autowired
- private SurveyService surveyService;
+ @Autowired
+ private SurveyService surveyService;
- @GetMapping("/surveys/{surveyId}/questions")
- public List retrieveQuestions(@PathVariable String surveyId) {
- return surveyService.retrieveQuestions(surveyId);
- }
+ @GetMapping("/surveys/{surveyId}/questions")
+ public List retrieveQuestions(@PathVariable String surveyId) {
+ return surveyService.retrieveQuestions(surveyId);
+ }
- @GetMapping(path = "/surveys/{surveyId}/questions/{questionId}")
- public Question retrieveQuestion(@PathVariable String surveyId,
- @PathVariable String questionId) {
- return surveyService.retrieveQuestion(surveyId, questionId);
- }
+ @GetMapping(path = "/surveys/{surveyId}/questions/{questionId}")
+ public Question retrieveQuestion(@PathVariable String surveyId,
+ @PathVariable String questionId) {
+ return surveyService.retrieveQuestion(surveyId, questionId);
+ }
- @PostMapping("/surveys/{surveyId}/questions")
- ResponseEntity> add(@PathVariable String surveyId,
- @RequestBody Question question) {
+ @PostMapping("/surveys/{surveyId}/questions")
+ ResponseEntity> add(@PathVariable String surveyId,
+ @RequestBody Question question) {
- Question createdTodo = surveyService.addQuestion(surveyId, question);
+ Question createdTodo = surveyService.addQuestion(surveyId, question);
- if (createdTodo == null) {
- return ResponseEntity.noContent().build();
- }
+ if (createdTodo == null) {
+ return ResponseEntity.noContent().build();
+ }
- URI location = ServletUriComponentsBuilder.fromCurrentRequest()
- .path("/{id}").buildAndExpand(createdTodo.getId()).toUri();
+ URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(
+ "/{id}").buildAndExpand(createdTodo.getId()).toUri();
- return ResponseEntity.created(location).build();
+ return ResponseEntity.created(location).build();
- }
+ }
}
diff --git a/src/main/java/com/in28minutes/springboot/jpa/User.java b/src/main/java/com/in28minutes/springboot/jpa/User.java
index 4bcfc74..d15b9f7 100644
--- a/src/main/java/com/in28minutes/springboot/jpa/User.java
+++ b/src/main/java/com/in28minutes/springboot/jpa/User.java
@@ -8,37 +8,37 @@
@Entity
public class User {
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
-
- private String name;// Not perfect!! Should be a proper object!
- private String role;// Not perfect!! An enum should be a better choice!
-
- protected User() {
- }
-
- public User(String name, String role) {
- super();
- this.name = name;
- this.role = role;
- }
-
- public Long getId() {
- return id;
- }
-
- public String getName() {
- return name;
- }
-
- public String getRole() {
- return role;
- }
-
- @Override
- public String toString() {
- return String.format("User [id=%s, name=%s, role=%s]", id, name, role);
- }
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ private String name;// Not perfect!! Should be a proper object!
+ private String role;// Not perfect!! An enum should be a better choice!
+
+ protected User() {
+ }
+
+ public User(String name, String role) {
+ super();
+ this.name = name;
+ this.role = role;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("User [id=%s, name=%s, role=%s]", id, name, role);
+ }
}
diff --git a/src/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java b/src/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java
index 18805f0..96ef3c9 100644
--- a/src/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java
+++ b/src/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java
@@ -9,40 +9,40 @@
@Component
public class UserCommandLineRunner implements CommandLineRunner {
- private static final Logger log = LoggerFactory
- .getLogger(UserCommandLineRunner.class);
-
- @Autowired
- private UserRepository repository;
-
- @Override
- public void run(String... args) {
- // save a couple of customers
- repository.save(new User("Ranga", "Admin"));
- repository.save(new User("Ravi", "User"));
- repository.save(new User("Satish", "Admin"));
- repository.save(new User("Raghu", "User"));
-
- log.info("-------------------------------");
- log.info("Finding all users");
- log.info("-------------------------------");
- for (User user : repository.findAll()) {
- log.info(user.toString());
- }
-
- log.info("-------------------------------");
- log.info("Finding user with id 1");
- log.info("-------------------------------");
- User user = repository.findOne(1L);
- log.info(user.toString());
-
- log.info("-------------------------------");
- log.info("Finding all Admins");
- log.info("-------------------------------");
- for (User admin : repository.findByRole("Admin")) {
- log.info(admin.toString());
- // Do something...
- }
- }
+ private static final Logger log = LoggerFactory
+ .getLogger(UserCommandLineRunner.class);
+
+ @Autowired
+ private UserRepository repository;
+
+ @Override
+ public void run(String... args) {
+ // save a couple of customers
+ repository.save(new User("Ranga", "Admin"));
+ repository.save(new User("Ravi", "User"));
+ repository.save(new User("Satish", "Admin"));
+ repository.save(new User("Raghu", "User"));
+
+ log.info("-------------------------------");
+ log.info("Finding all users");
+ log.info("-------------------------------");
+ for (User user : repository.findAll()) {
+ log.info(user.toString());
+ }
+
+ log.info("-------------------------------");
+ log.info("Finding user with id 1");
+ log.info("-------------------------------");
+ User user = repository.findOne(1L);
+ log.info(user.toString());
+
+ log.info("-------------------------------");
+ log.info("Finding all Admins");
+ log.info("-------------------------------");
+ for (User admin : repository.findByRole("Admin")) {
+ log.info(admin.toString());
+ // Do something...
+ }
+ }
}
diff --git a/src/main/java/com/in28minutes/springboot/jpa/UserRepository.java b/src/main/java/com/in28minutes/springboot/jpa/UserRepository.java
index b9ddfbb..c0cffc0 100644
--- a/src/main/java/com/in28minutes/springboot/jpa/UserRepository.java
+++ b/src/main/java/com/in28minutes/springboot/jpa/UserRepository.java
@@ -5,5 +5,5 @@
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository {
- List findByRole(String description);
+ List findByRole(String description);
}
\ No newline at end of file
diff --git a/src/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java b/src/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java
index a661a78..4e3caa2 100644
--- a/src/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java
+++ b/src/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java
@@ -8,6 +8,6 @@
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRestRepository extends
-PagingAndSortingRepository {
- List findByRole(@Param("role") String role);
+ PagingAndSortingRepository {
+ List findByRole(@Param("role") String role);
}
\ No newline at end of file
diff --git a/src/main/java/com/in28minutes/springboot/model/Question.java b/src/main/java/com/in28minutes/springboot/model/Question.java
index 24eb87f..51b450b 100644
--- a/src/main/java/com/in28minutes/springboot/model/Question.java
+++ b/src/main/java/com/in28minutes/springboot/model/Question.java
@@ -3,84 +3,84 @@
import java.util.List;
public class Question {
- private String id;
- private String description;
- private String correctAnswer;
- private List options;
+ private String id;
+ private String description;
+ private String correctAnswer;
+ private List options;
- // Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:
- // Can not construct instance of com.in28minutes.springboot.model.Question:
- // no suitable constructor found, can not deserialize from Object value
- // (missing default constructor or creator, or perhaps need to add/enable
- // type information?)
- public Question() {
+ // Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:
+ // Can not construct instance of com.in28minutes.springboot.model.Question:
+ // no suitable constructor found, can not deserialize from Object value
+ // (missing default constructor or creator, or perhaps need to add/enable
+ // type information?)
+ public Question() {
- }
+ }
- public Question(String id, String description, String correctAnswer,
- List options) {
- super();
- this.id = id;
- this.description = description;
- this.correctAnswer = correctAnswer;
- this.options = options;
- }
+ public Question(String id, String description, String correctAnswer,
+ List options) {
+ super();
+ this.id = id;
+ this.description = description;
+ this.correctAnswer = correctAnswer;
+ this.options = options;
+ }
- public String getId() {
- return id;
- }
+ public String getId() {
+ return id;
+ }
- public void setId(String id) {
- this.id = id;
- }
+ public void setId(String id) {
+ this.id = id;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public String getCorrectAnswer() {
- return correctAnswer;
- }
+ public String getCorrectAnswer() {
+ return correctAnswer;
+ }
- public List getOptions() {
- return options;
- }
+ public List getOptions() {
+ return options;
+ }
- @Override
- public String toString() {
- return String
- .format("Question [id=%s, description=%s, correctAnswer=%s, options=%s]",
- id, description, correctAnswer, options);
- }
+ @Override
+ public String toString() {
+ return String
+ .format("Question [id=%s, description=%s, correctAnswer=%s, options=%s]",
+ id, description, correctAnswer, options);
+ }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (id == null ? 0 : id.hashCode());
- return result;
- }
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + (id == null ? 0 : id.hashCode());
+ return result;
+ }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- Question other = (Question) obj;
- if (id == null) {
- if (other.id != null) {
- return false;
- }
- } else if (!id.equals(other.id)) {
- return false;
- }
- return true;
- }
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ Question other = (Question) obj;
+ if (id == null) {
+ if (other.id != null) {
+ return false;
+ }
+ } else if (!id.equals(other.id)) {
+ return false;
+ }
+ return true;
+ }
}
diff --git a/src/main/java/com/in28minutes/springboot/model/Survey.java b/src/main/java/com/in28minutes/springboot/model/Survey.java
index 3619868..8cf53e4 100644
--- a/src/main/java/com/in28minutes/springboot/model/Survey.java
+++ b/src/main/java/com/in28minutes/springboot/model/Survey.java
@@ -3,41 +3,41 @@
import java.util.List;
public class Survey {
- private String id;
- private String title;
- private String description;
- private List questions;
-
- public Survey(String id, String title, String description,
- List questions) {
- super();
- this.id = id;
- this.title = title;
- this.description = description;
- this.questions = questions;
- }
-
- public String getId() {
- return id;
- }
-
- public String getTitle() {
- return title;
- }
-
- public String getDescription() {
- return description;
- }
-
- public List getQuestions() {
- return questions;
- }
-
- @Override
- public String toString() {
- return String.format(
- "Survey [id=%s, title=%s, description=%s, questions=%s]", id,
- title, description, questions);
- }
+ private String id;
+ private String title;
+ private String description;
+ private List questions;
+
+ public Survey(String id, String title, String description,
+ List questions) {
+ super();
+ this.id = id;
+ this.title = title;
+ this.description = description;
+ this.questions = questions;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public List getQuestions() {
+ return questions;
+ }
+
+ @Override
+ public String toString() {
+ return String.format(
+ "Survey [id=%s, title=%s, description=%s, questions=%s]", id,
+ title, description, questions);
+ }
}
diff --git a/src/main/java/com/in28minutes/springboot/security/SecurityConfig.java b/src/main/java/com/in28minutes/springboot/security/SecurityConfig.java
index badb688..58c4e6c 100644
--- a/src/main/java/com/in28minutes/springboot/security/SecurityConfig.java
+++ b/src/main/java/com/in28minutes/springboot/security/SecurityConfig.java
@@ -9,19 +9,19 @@
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(AuthenticationManagerBuilder auth)
- throws Exception {
- auth.inMemoryAuthentication().withUser("user1").password("secret1")
- .roles("USER").and().withUser("admin1").password("secret1")
- .roles("ADMIN");
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth)
+ throws Exception {
+ auth.inMemoryAuthentication().withUser("user1").password("secret1")
+ .roles("USER").and().withUser("admin1").password("secret1")
+ .roles("ADMIN");
+ }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.httpBasic().and().authorizeRequests().antMatchers("/surveys/**")
- .hasRole("USER").antMatchers("/users/**").hasRole("USER")
- .antMatchers("/**").hasRole("ADMIN").and().csrf().disable()
- .headers().frameOptions().disable();
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.httpBasic().and().authorizeRequests().antMatchers("/surveys/**")
+ .hasRole("USER").antMatchers("/users/**").hasRole("USER")
+ .antMatchers("/**").hasRole("ADMIN").and().csrf().disable()
+ .headers().frameOptions().disable();
+ }
}
\ No newline at end of file
diff --git a/src/main/java/com/in28minutes/springboot/service/SurveyService.java b/src/main/java/com/in28minutes/springboot/service/SurveyService.java
index 0d3fae5..b3f3ccb 100644
--- a/src/main/java/com/in28minutes/springboot/service/SurveyService.java
+++ b/src/main/java/com/in28minutes/springboot/service/SurveyService.java
@@ -13,83 +13,83 @@
@Component
public class SurveyService {
- private static List surveys = new ArrayList<>();
- static {
- Question question1 = new Question("Question1",
- "Largest Country in the World", "Russia", Arrays.asList(
- "India", "Russia", "United States", "China"));
- Question question2 = new Question("Question2",
- "Most Populus Country in the World", "China", Arrays.asList(
- "India", "Russia", "United States", "China"));
- Question question3 = new Question("Question3",
- "Highest GDP in the World", "United States", Arrays.asList(
- "India", "Russia", "United States", "China"));
- Question question4 = new Question("Question4",
- "Second largest english speaking country", "India",
- Arrays.asList("India", "Russia", "United States", "China"));
-
- List questions = new ArrayList<>(Arrays.asList(question1,
- question2, question3, question4));
-
- Survey survey = new Survey("Survey1", "My Favorite Survey",
- "Description of the Survey", questions);
-
- surveys.add(survey);
- }
-
- public List retrieveAllSurveys() {
- return surveys;
- }
-
- public Survey retrieveSurvey(String surveyId) {
- for (Survey survey : surveys) {
- if (survey.getId().equals(surveyId)) {
- return survey;
- }
- }
- return null;
- }
-
- public List retrieveQuestions(String surveyId) {
- Survey survey = retrieveSurvey(surveyId);
-
- if (survey == null) {
- return null;
- }
-
- return survey.getQuestions();
- }
-
- public Question retrieveQuestion(String surveyId, String questionId) {
- Survey survey = retrieveSurvey(surveyId);
-
- if (survey == null) {
- return null;
- }
-
- for (Question question : survey.getQuestions()) {
- if (question.getId().equals(questionId)) {
- return question;
- }
- }
-
- return null;
- }
-
- private SecureRandom random = new SecureRandom();
-
- public Question addQuestion(String surveyId, Question question) {
- Survey survey = retrieveSurvey(surveyId);
-
- if (survey == null) {
- return null;
- }
-
- String randomId = new BigInteger(130, random).toString(32);
- question.setId(randomId);
-
- survey.getQuestions().add(question);
-
- return question;
- }
+ private static List surveys = new ArrayList<>();
+ static {
+ Question question1 = new Question("Question1",
+ "Largest Country in the World", "Russia", Arrays.asList(
+ "India", "Russia", "United States", "China"));
+ Question question2 = new Question("Question2",
+ "Most Populus Country in the World", "China", Arrays.asList(
+ "India", "Russia", "United States", "China"));
+ Question question3 = new Question("Question3",
+ "Highest GDP in the World", "United States", Arrays.asList(
+ "India", "Russia", "United States", "China"));
+ Question question4 = new Question("Question4",
+ "Second largest english speaking country", "India", Arrays
+ .asList("India", "Russia", "United States", "China"));
+
+ List questions = new ArrayList<>(Arrays.asList(question1,
+ question2, question3, question4));
+
+ Survey survey = new Survey("Survey1", "My Favorite Survey",
+ "Description of the Survey", questions);
+
+ surveys.add(survey);
+ }
+
+ public List retrieveAllSurveys() {
+ return surveys;
+ }
+
+ public Survey retrieveSurvey(String surveyId) {
+ for (Survey survey : surveys) {
+ if (survey.getId().equals(surveyId)) {
+ return survey;
+ }
+ }
+ return null;
+ }
+
+ public List retrieveQuestions(String surveyId) {
+ Survey survey = retrieveSurvey(surveyId);
+
+ if (survey == null) {
+ return null;
+ }
+
+ return survey.getQuestions();
+ }
+
+ public Question retrieveQuestion(String surveyId, String questionId) {
+ Survey survey = retrieveSurvey(surveyId);
+
+ if (survey == null) {
+ return null;
+ }
+
+ for (Question question : survey.getQuestions()) {
+ if (question.getId().equals(questionId)) {
+ return question;
+ }
+ }
+
+ return null;
+ }
+
+ private SecureRandom random = new SecureRandom();
+
+ public Question addQuestion(String surveyId, Question question) {
+ Survey survey = retrieveSurvey(surveyId);
+
+ if (survey == null) {
+ return null;
+ }
+
+ String randomId = new BigInteger(130, random).toString(32);
+ question.setId(randomId);
+
+ survey.getQuestions().add(question);
+
+ return question;
+ }
}
\ No newline at end of file
diff --git a/src/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java b/src/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java
index 63809fc..efc982d 100644
--- a/src/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java
+++ b/src/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java
@@ -28,75 +28,76 @@
import com.in28minutes.springboot.model.Question;
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@SpringBootTest(classes = Application.class,
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SurveyControllerIT {
- @LocalServerPort
- private int port;
-
- private TestRestTemplate template = new TestRestTemplate();
-
- HttpHeaders headers = createHeaders("user1", "secret1");
-
- @Before
- public void setupJSONAcceptType() {
- headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
- }
-
- @Test
- public void retrieveSurveyQuestion() throws Exception {
-
- String expected = "{id:Question1,description:Largest Country in the World,correctAnswer:Russia,options:[India,Russia,United States,China]}";
-
- ResponseEntity response = template.exchange(
- createUrl("/surveys/Survey1/questions/Question1"),
- HttpMethod.GET, new HttpEntity("DUMMY_DOESNT_MATTER",
- headers), String.class);
-
- JSONAssert.assertEquals(expected, response.getBody(), false);
- }
-
- @Test
- public void retrieveSurveyQuestions() throws Exception {
- ResponseEntity> response = template.exchange(
- createUrl("/surveys/Survey1/questions/"), HttpMethod.GET,
- new HttpEntity("DUMMY_DOESNT_MATTER", headers),
- new ParameterizedTypeReference>() {
- });
-
- Question sampleQuestion = new Question("Question1",
- "Largest Country in the World", "Russia", Arrays.asList(
- "India", "Russia", "United States", "China"));
-
- assertTrue(response.getBody().contains(sampleQuestion));
- }
-
- @Test
- public void createSurveyQuestion() throws Exception {
- Question question = new Question("DOESN'T MATTER", "Smallest Number",
- "1", Arrays.asList("1", "2", "3", "4"));
-
- ResponseEntity response = template.exchange(
- createUrl("/surveys/Survey1/questions/"), HttpMethod.POST,
- new HttpEntity(question, headers), String.class);
-
- assertThat(response.getHeaders().get(HttpHeaders.LOCATION).get(0),
- containsString("/surveys/Survey1/questions/"));
- }
-
- private String createUrl(String uri) {
- return "http://localhost:" + port + uri;
- }
-
- HttpHeaders createHeaders(String username, String password) {
- return new HttpHeaders() {
- {
- String auth = username + ":" + password;
- byte[] encodedAuth = Base64.encode(auth.getBytes(Charset
- .forName("US-ASCII")));
- String authHeader = "Basic " + new String(encodedAuth);
- set("Authorization", authHeader);
- }
- };
- }
+ @LocalServerPort
+ private int port;
+
+ private TestRestTemplate template = new TestRestTemplate();
+
+ HttpHeaders headers = createHeaders("user1", "secret1");
+
+ @Before
+ public void setupJSONAcceptType() {
+ headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
+ }
+
+ @Test
+ public void retrieveSurveyQuestion() throws Exception {
+
+ String expected = "{id:Question1,description:Largest Country in the World,correctAnswer:Russia,options:[India,Russia,United States,China]}";
+
+ ResponseEntity response = template.exchange(
+ createUrl("/surveys/Survey1/questions/Question1"),
+ HttpMethod.GET, new HttpEntity("DUMMY_DOESNT_MATTER",
+ headers), String.class);
+
+ JSONAssert.assertEquals(expected, response.getBody(), false);
+ }
+
+ @Test
+ public void retrieveSurveyQuestions() throws Exception {
+ ResponseEntity> response = template.exchange(
+ createUrl("/surveys/Survey1/questions/"), HttpMethod.GET,
+ new HttpEntity("DUMMY_DOESNT_MATTER", headers),
+ new ParameterizedTypeReference>() {
+ });
+
+ Question sampleQuestion = new Question("Question1",
+ "Largest Country in the World", "Russia", Arrays.asList(
+ "India", "Russia", "United States", "China"));
+
+ assertTrue(response.getBody().contains(sampleQuestion));
+ }
+
+ @Test
+ public void createSurveyQuestion() throws Exception {
+ Question question = new Question("DOESN'T MATTER", "Smallest Number",
+ "1", Arrays.asList("1", "2", "3", "4"));
+
+ ResponseEntity response = template.exchange(
+ createUrl("/surveys/Survey1/questions/"), HttpMethod.POST,
+ new HttpEntity(question, headers), String.class);
+
+ assertThat(response.getHeaders().get(HttpHeaders.LOCATION).get(0),
+ containsString("/surveys/Survey1/questions/"));
+ }
+
+ private String createUrl(String uri) {
+ return "http://localhost:" + port + uri;
+ }
+
+ HttpHeaders createHeaders(String username, String password) {
+ return new HttpHeaders() {
+ {
+ String auth = username + ":" + password;
+ byte[] encodedAuth = Base64.encode(auth.getBytes(Charset
+ .forName("US-ASCII")));
+ String authHeader = "Basic " + new String(encodedAuth);
+ set("Authorization", authHeader);
+ }
+ };
+ }
}
\ No newline at end of file
diff --git a/src/test/java/com/in28minutes/springboot/controller/SurveyControllerTest.java b/src/test/java/com/in28minutes/springboot/controller/SurveyControllerTest.java
index cebc5ad..dcffbcf 100644
--- a/src/test/java/com/in28minutes/springboot/controller/SurveyControllerTest.java
+++ b/src/test/java/com/in28minutes/springboot/controller/SurveyControllerTest.java
@@ -29,78 +29,72 @@
@WebMvcTest(value = SurveyController.class, secure = false)
public class SurveyControllerTest {
- @Autowired
- private MockMvc mvc;
-
- @MockBean
- private SurveyService service;
-
- @Test
- public void retrieveQuestion() throws Exception {
-
- Question mockQuestion = new Question("Question1", "First Alphabet",
- "A", Arrays.asList("A", "B", "C", "D"));
-
- when(service.retrieveQuestion(anyString(), anyString())).thenReturn(
- mockQuestion);
-
- MvcResult result = mvc
- .perform(
- MockMvcRequestBuilders.get(
- "/surveys/Survey1/questions/1").accept(
- MediaType.APPLICATION_JSON))
- .andExpect(status().isOk()).andReturn();
-
- String expected = "{id:Question1,description:First Alphabet,correctAnswer:A,options:[A,B,C,D]}";
-
- JSONAssert.assertEquals(expected, result.getResponse()
- .getContentAsString(), false);
-
- }
-
- @Test
- public void retrieveSurveyQuestions() throws Exception {
- List mockList = Arrays.asList(
- new Question("Question1", "First Alphabet", "A", Arrays.asList(
- "A", "B", "C", "D")),
- new Question("Question2", "Last Alphabet", "Z", Arrays.asList(
- "A", "X", "Y", "Z")));
-
- when(service.retrieveQuestions(anyString())).thenReturn(mockList);
-
- MvcResult result = mvc
- .perform(
- MockMvcRequestBuilders
- .get("/surveys/Survey1/questions").accept(
- MediaType.APPLICATION_JSON))
- .andExpect(status().isOk()).andReturn();
-
- String expected = "["
- + "{id:Question1,description:First Alphabet,correctAnswer:A,options:[A,B,C,D]},"
- + "{id:Question2,description:Last Alphabet,correctAnswer:Z,options:[A,X,Y,Z]}"
- + "]";
-
- JSONAssert.assertEquals(expected, result.getResponse()
- .getContentAsString(), false);
- }
-
- @Test
- public void createSurveyQuestion() throws Exception {
- Question mockQuestion = new Question("1", "Smallest Number", "1",
- Arrays.asList("1", "2", "3", "4"));
-
- String question = "{\"description\":\"Smallest Number\",\"correctAnswer\":\"1\",\"options\":[\"1\",\"2\",\"3\",\"4\"]}";
-
- when(service.addQuestion(anyString(), any(Question.class))).thenReturn(
- mockQuestion);
-
- mvc.perform(
- MockMvcRequestBuilders.post("/surveys/Survey1/questions")
- .content(question)
- .contentType(MediaType.APPLICATION_JSON))
- .andExpect(status().isCreated())
- .andExpect(
- header().string("location",
- containsString("/surveys/Survey1/questions/1")));
- }
+ @Autowired
+ private MockMvc mvc;
+
+ @MockBean
+ private SurveyService service;
+
+ @Test
+ public void retrieveQuestion() throws Exception {
+
+ Question mockQuestion = new Question("Question1", "First Alphabet",
+ "A", Arrays.asList("A", "B", "C", "D"));
+
+ when(service.retrieveQuestion(anyString(), anyString())).thenReturn(
+ mockQuestion);
+
+ MvcResult result = mvc.perform(
+ MockMvcRequestBuilders.get("/surveys/Survey1/questions/1")
+ .accept(MediaType.APPLICATION_JSON)).andExpect(
+ status().isOk()).andReturn();
+
+ String expected = "{id:Question1,description:First Alphabet,correctAnswer:A,options:[A,B,C,D]}";
+
+ JSONAssert.assertEquals(expected, result.getResponse()
+ .getContentAsString(), false);
+
+ }
+
+ @Test
+ public void retrieveSurveyQuestions() throws Exception {
+ List mockList = Arrays.asList(new Question("Question1",
+ "First Alphabet", "A", Arrays.asList("A", "B", "C", "D")),
+ new Question("Question2", "Last Alphabet", "Z", Arrays.asList(
+ "A", "X", "Y", "Z")));
+
+ when(service.retrieveQuestions(anyString())).thenReturn(mockList);
+
+ MvcResult result = mvc.perform(
+ MockMvcRequestBuilders.get("/surveys/Survey1/questions")
+ .accept(MediaType.APPLICATION_JSON)).andExpect(
+ status().isOk()).andReturn();
+
+ String expected = "["
+ + "{id:Question1,description:First Alphabet,correctAnswer:A,options:[A,B,C,D]},"
+ + "{id:Question2,description:Last Alphabet,correctAnswer:Z,options:[A,X,Y,Z]}"
+ + "]";
+
+ JSONAssert.assertEquals(expected, result.getResponse()
+ .getContentAsString(), false);
+ }
+
+ @Test
+ public void createSurveyQuestion() throws Exception {
+ Question mockQuestion = new Question("1", "Smallest Number", "1",
+ Arrays.asList("1", "2", "3", "4"));
+
+ String question = "{\"description\":\"Smallest Number\",\"correctAnswer\":\"1\",\"options\":[\"1\",\"2\",\"3\",\"4\"]}";
+
+ when(service.addQuestion(anyString(), any(Question.class))).thenReturn(
+ mockQuestion);
+
+ mvc.perform(
+ MockMvcRequestBuilders.post("/surveys/Survey1/questions")
+ .content(question).contentType(
+ MediaType.APPLICATION_JSON)).andExpect(
+ status().isCreated()).andExpect(
+ header().string("location",
+ containsString("/surveys/Survey1/questions/1")));
+ }
}
\ No newline at end of file