diff --git a/PRA/PRA02-H2.png b/PRA/PRA02-H2.png new file mode 100644 index 000000000..81b4e094e Binary files /dev/null and b/PRA/PRA02-H2.png differ diff --git a/PRA/PRA02-PostgresTerminal.png b/PRA/PRA02-PostgresTerminal.png new file mode 100644 index 000000000..4e8c2eeeb Binary files /dev/null and b/PRA/PRA02-PostgresTerminal.png differ diff --git a/PRA/PRA02-PostmanRunner-Postgres.png b/PRA/PRA02-PostmanRunner-Postgres.png new file mode 100644 index 000000000..40deadc25 Binary files /dev/null and b/PRA/PRA02-PostmanRunner-Postgres.png differ diff --git a/PRA/PRA02-PostmanRunner.png b/PRA/PRA02-PostmanRunner.png new file mode 100644 index 000000000..3566dc8a2 Binary files /dev/null and b/PRA/PRA02-PostmanRunner.png differ diff --git a/PRA/PRA02-pgAdmin4.png b/PRA/PRA02-pgAdmin4.png new file mode 100644 index 000000000..8bf190241 Binary files /dev/null and b/PRA/PRA02-pgAdmin4.png differ diff --git a/README.md b/README.md new file mode 100644 index 000000000..036b42226 --- /dev/null +++ b/README.md @@ -0,0 +1,95 @@ +# PRA#02-SpringBoot: Create User API Rest + +## CIFO La Violeta - FullStack IFCD0210-25 MF01 + +This document serves as a guide and log for the backend development of the PRA#02 Spring Boot project. + +--- + +## PR Submission Checklist + +### **Common Tasks:** + +- [x] Create User @Entity +- [x] Create UserController (Rest API controller) +- [x] Implement UserRepository +- [x] Configure application properties with local H2 database +- [x] Develop UserService +- [x] Test all endpoints with Postman + +### Optional Tasks: + +- [x] Configure Postgres database +- [x] Implement Faker for test data +- [x] Add unit tests for services +- [x] Integration tests for controllers + +### **Testing**: + +- [x] All endpoints tested in Postman. +- [x] Error handling implemented in controllers. +- [x] Data persistence verified in H2 database. + +--- + +## Estimated Time for Tasks + +### Common Part + +| Task | Estimated Time | Actual Time | Impediments (if any) | New Concepts | +| --------------------------- | -------------- | -------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | +| Create User @Entity | 1 hours | 45 min | | @PrePersist
@GeneratedValue(strategy = GenerationType.UUID)
@Column(unique = true, nullable = false) | +| Create UserController | 1 hours | 1.5 hour | | ResponseEntity utility methods
 Centralize headers handling using helper method | +| Implement UserRepository | 0.5 hours | 0.5 hours | | | +| Configure H2 database | 0.5 hours | 0.5 hours | | | +| Develop UserService | 2 hours | 1 hours | | | +| Test endpoints with Postman | 1.5 hours | 2 hours | data.sql only executes correctly if the table has been created previously | data.sql to introduce mock data
postman data file to test and run collections | +| **Total** | **6.5 hours** | **6.25 hours** | | | + +### Optional Part + +| Task | Estimated Time | Actual Time | Impediments (if any) | New Concepts | +| --------------------------------- | -------------- | ------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| Configure Postgres database | 2.5 hours | 2.5 hours | | | +| Implement Faker for test data | 1 hours | 1.5 hours | | Use Faker dinamically via API (not implemented)
 Streams: IntStream.range(x, y).mapToObj(i -> ...).collect(Collectors.toList() | +| Add unit tests for services | 2 hours | 1.5 hours | | Mockito JUnit integration | +| Integration tests for controllers | 2 hours | 1 hour so far | | MockMvc and Fluent API | +| **Total** | **7.5 hours** | **6.5 hours** | | | + +--- + +## Images + +### H2 + +#### Database Connection + +![](./PRA/PRA02-H2.png) + +#### Postman Runner Results + +![](./PRA/PRA02-PostmanRunner.png) + +### Postgres + +#### Database Connection (pgAdmin 4 & terminal) + +![](./PRA/PRA02-pgAdmin4.png) + +![](/./PRA/PRA02-PostgresTerminal.png) + +#### Postman Runner Results + +![](./PRA/PRA02-PostmanRunner-Postgres.png) + +--- + +## Future Improvements + +- Implement Global Exception Handling. +- Add more unit and integration tests for key functionalities. +- Implement custom queries for enhanced user search. +- Optimize service layer for better performance and maintainability. +- Enhance validation for user input fields. + +--- diff --git a/backend/pronunciationAppBack/pom.xml b/backend/pronunciationAppBack/pom.xml index 5963cf3b7..7a9177a85 100644 --- a/backend/pronunciationAppBack/pom.xml +++ b/backend/pronunciationAppBack/pom.xml @@ -34,6 +34,11 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.projectlombok + lombok + true + org.springframework.boot spring-boot-starter-web @@ -65,6 +70,11 @@ spring-boot-starter-test test + + com.github.javafaker + javafaker + 1.0.2 + diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/HealthController.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/HealthController.java new file mode 100644 index 000000000..92467cd9f --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/HealthController.java @@ -0,0 +1,86 @@ +package dev.pronunciationAppBack.controller; + + +import dev.pronunciationAppBack.service.UserService; +import dev.pronunciationAppBack.service.WordService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api/health") +public class HealthController { + + @Autowired + private WordService wordService; + + @Autowired + private UserService userService; + + @GetMapping + public ResponseEntity> healthCheck() { + Map healthStatus = new HashMap<>(); + healthStatus.put("status", "UP"); + healthStatus.put("timestamp", new Date()); + healthStatus.put("wordCount", wordService.getWordCount()); + healthStatus.put("userCount", userService.getUserCount()); + + // verify database connection + boolean databaseConnection = checkDatabaseConnection(); + healthStatus.put("database", databaseConnection ? "Connected" : "Disconnected"); + + // Add more health checks as needed + healthStatus.put("memoryUsage", getMemoryUsage()); + healthStatus.put("diskSpace", getDiskSpace()); + + HttpHeaders headers = getCommonHeaders("Health check endpoint"); + HttpStatus status = databaseConnection ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE; + + return new ResponseEntity<>(healthStatus, headers, status); + } + + private boolean checkDatabaseConnection() { + try { + wordService.getAllWords(); + return true; + } catch (Exception e) { + return false; + } + } + + private Map getMemoryUsage() { + Runtime runtime = Runtime.getRuntime(); + Map memoryInfo = new HashMap<>(); + memoryInfo.put("total", runtime.totalMemory()); + memoryInfo.put("free", runtime.freeMemory()); + memoryInfo.put("used", runtime.totalMemory() - runtime.freeMemory()); + return memoryInfo; + } + + private Map getDiskSpace() { + java.io.File root = new java.io.File("/"); + Map diskInfo = new HashMap<>(); + diskInfo.put("total", root.getTotalSpace()); + diskInfo.put("free", root.getFreeSpace()); + diskInfo.put("usable", root.getUsableSpace()); + return diskInfo; + } + + private HttpHeaders getCommonHeaders(String description) { + HttpHeaders headers = new HttpHeaders(); + headers.add("desc", description); + headers.add("content-type", "application/json"); + headers.add("date", new Date().toString()); + headers.add("server", "Spring Boot"); + headers.add("version", "1.0.0"); + return headers; + } +} diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/UserController.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/UserController.java new file mode 100644 index 000000000..318b7acd6 --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/UserController.java @@ -0,0 +1,98 @@ +package dev.pronunciationAppBack.controller; + +import dev.pronunciationAppBack.service.UserService; +import dev.pronunciationAppBack.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.util.Date; +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/api/users") +public class UserController { + + @Autowired + public UserService userService; + + private HttpHeaders getHeaders(String message) { + HttpHeaders headers = new HttpHeaders(); + headers.add("Description", message); + return headers; + } + + @GetMapping + public ResponseEntity> getAllUsers() { + List users = userService.getAllUsers(); + + return !users.isEmpty() + ? ResponseEntity.ok().headers(getHeaders("Returning all users")).body(users) + : ResponseEntity.notFound().headers(getHeaders("No users found")).build(); + } + + @GetMapping("/{id}") + public ResponseEntity getUserById(@PathVariable String id) { + Optional user = userService.getUserById(id); + + return user.map(u -> ResponseEntity.ok().headers(getHeaders("User found")).body(u)) + .orElseGet(() -> ResponseEntity.notFound().headers(getHeaders("User not found")).build()); + } + + @PostMapping("/createUser") + public ResponseEntity createUser(@RequestBody User user){ + User createdUser = userService.createUser(user); + + //return ResponseEntity.ok().body(createdUser); + return ResponseEntity.status(HttpStatus.CREATED).body(createdUser); + + //URI location = URI.create("/users/" + createdUser.getId()); + //return ResponseEntity.created(location).headers(getHeaders("User created successfully")).body(user); + } + + @PutMapping("/{id}") + public ResponseEntity updateUser(@PathVariable String id, @RequestBody User user) { + if (user.getId() != null && !user.getId().equals(id)) { + return ResponseEntity.badRequest().headers(getHeaders("Mismatch between ID and user ID in body request")).build(); + } else { + User updatedUser = userService.updateUser(user); + return ResponseEntity.ok().headers(getHeaders("User updated")).body(updatedUser); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteUserById(@PathVariable String id){ + if (userService.existsById(id)) { + userService.deleteUser(id); + return ResponseEntity.ok().headers(getHeaders("User deleted successfully")).build(); + } else { + return ResponseEntity.notFound().headers(getHeaders("User not found")).build(); + } + } + + @DeleteMapping + public ResponseEntity deleteAllUsers(){ + userService.deleteAllUsers(); + if (userService.getAllUsers().isEmpty()){ + return ResponseEntity.ok().headers(getHeaders("All users deleted succesfully")).build(); + } else { + return ResponseEntity.notFound().headers(getHeaders("Could not delete all users")).build(); + } + } + +// private HttpHeaders getCommonHeaders(String description) { +// HttpHeaders headers = new HttpHeaders(); +// headers.add("desc", description); +// headers.add("content-type", "application/json"); +// headers.add("date", new Date().toString()); +// headers.add("server", "Spring Boot"); +// headers.add("version", "1.0.0"); +// headers.add("word-count", String.valueOf(userService.getUserCount())); +// headers.add("object", "words"); +// return headers; +// } +} \ No newline at end of file diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/WordController.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/WordController.java new file mode 100644 index 000000000..348c691ff --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/controller/WordController.java @@ -0,0 +1,94 @@ +package dev.pronunciationAppBack.controller; + +import dev.pronunciationAppBack.model.Word; +import dev.pronunciationAppBack.service.WordService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/api/words") +public class WordController { + + @Autowired + private WordService wordService; + + /* @GetMapping("/hello") + public ResponseEntity hello() { + HttpHeaders headers = getCommonHeaders("Hello endpoint"); + return new ResponseEntity<>("hello Emiliano, are you sleeping?", headers, HttpStatus.OK); + }*/ + + @GetMapping + public ResponseEntity> getAllWords() { + List words = wordService.getAllWords(); + HttpHeaders headers = getCommonHeaders("Get all words"); + + return !words.isEmpty() + ? new ResponseEntity<>(words, headers, HttpStatus.OK) + : new ResponseEntity<>(headers, HttpStatus.NOT_FOUND); + } + + @GetMapping("/{id}") + public ResponseEntity getWordById(@PathVariable String id) { + Optional word = wordService.getWordById(id); + HttpHeaders headers = getCommonHeaders("Get word by ID"); + + return word.map(value -> new ResponseEntity<>(value, headers, HttpStatus.OK)) + .orElseGet(() -> new ResponseEntity<>(headers, HttpStatus.NOT_FOUND)); + } + + @PostMapping("/createWord") + public ResponseEntity createWord(@RequestBody Word word) { + Word createdWord = wordService.createWord(word); + HttpHeaders headers = getCommonHeaders("Create a new word"); + + return new ResponseEntity<>(createdWord, headers, HttpStatus.CREATED); + } + + @PutMapping("/{id}") + public ResponseEntity updateWord(@PathVariable String id, @RequestBody Word word) { + Word updatedWord = wordService.updateWord(word); + HttpHeaders headers = getCommonHeaders("Update a word"); + + return new ResponseEntity<>(updatedWord, headers, HttpStatus.OK); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteWord(@PathVariable("id") String idToDelete) { + HttpHeaders headers = getCommonHeaders("Delete a word"); + + if (wordService.existsById(idToDelete)) { + wordService.deleteWord(idToDelete); + return new ResponseEntity<>("Word deleted", headers, HttpStatus.OK); + } else { + return new ResponseEntity<>("Word not found", headers, HttpStatus.NOT_FOUND); + } + } + + @DeleteMapping + public ResponseEntity deleteAllWords() { + wordService.deleteAllWords(); + HttpHeaders headers = getCommonHeaders("Delete all words"); + return new ResponseEntity<>("All words deleted", headers, HttpStatus.OK); + } + + private HttpHeaders getCommonHeaders(String description) { + HttpHeaders headers = new HttpHeaders(); + headers.add("desc", description); + headers.add("content-type", "application/json"); + headers.add("date", new Date().toString()); + headers.add("server", "Spring Boot"); + headers.add("version", "1.0.0"); + headers.add("word-count", String.valueOf(wordService.getWordCount())); + headers.add("object", "words"); + return headers; + } +} + diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/model/User.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/model/User.java new file mode 100644 index 000000000..ea3c4403c --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/model/User.java @@ -0,0 +1,62 @@ +package dev.pronunciationAppBack.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDateTime; + +@NoArgsConstructor +@AllArgsConstructor +//@Data // combines @Getter, @Setter, @ToString, @EqualsAndHashCode, and @RequiredArgsConstructor into a single annotation. +@Setter +@Getter +@Entity +@Table(name = "`USER`") +public class User { + + // @Getter + // @Setter + @JsonProperty("id") + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private String id; + + @JsonProperty("username") + // @Column(unique = true, nullable = false) + private String username; + + @JsonProperty("email") + // @Column(unique = true, nullable = false) + private String email; + + @JsonProperty("password") + private String password; + + @JsonProperty("joinDate") + private LocalDateTime joinDate; + private boolean isActive; + + @PrePersist // call the annotated method before entity is persisted in db + protected void onCreate(){ + joinDate = LocalDateTime.now(); + } + + @Override + public String toString() { + return "User{" + + "id='" + id + '\'' + + ", username='" + username + '\'' + + ", email='" + email + '\'' + + ", password='" + password + '\'' + + ", joinDate=" + joinDate + + ", isActive=" + isActive + + '}'; + } + + public String getId() { + return id; + } + + +} diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/model/Word.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/model/Word.java new file mode 100644 index 000000000..7fea0037b --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/model/Word.java @@ -0,0 +1,98 @@ +package dev.pronunciationAppBack.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Word { + + @Id + private String id; + private String wordName; + private String definition; + private String phoneticSpelling; + private String sentence; + private boolean isActive; + private int level; + + public Word() {} + + public Word(String id, String wordName, String definition, String phoneticSpelling, String sentence, boolean isActive, int level) { + this.id = id; + this.wordName = wordName; + this.definition = definition; + this.phoneticSpelling = phoneticSpelling; + this.sentence = sentence; + this.isActive = isActive; + this.level = level; + } + + public String getId() { + return id; + } + + public String getWordName() { + return wordName; + } + + public String getDefinition() { + return definition; + } + + public String getPhoneticSpelling() { + return phoneticSpelling; + } + + public String getSentence() { + return sentence; + } + + public boolean isActive() { + return isActive; + } + + public int getLevel() { + return level; + } + + public void setId(String id) { + this.id = id; + } + + public void setWordName(String wordName) { + this.wordName = wordName; + } + + public void setDefinition(String definition) { + this.definition = definition; + } + + public void setPhoneticSpelling(String phoneticSpelling) { + this.phoneticSpelling = phoneticSpelling; + } + + public void setSentence(String sentence) { + this.sentence = sentence; + } + + public void setActive(boolean active) { + isActive = active; + } + + public void setLevel(int level) { + this.level = level; + } + + @Override + public String toString() { + return "Word{" + + "id='" + id + '\'' + + ", wordName='" + wordName + '\'' + + ", definition='" + definition + '\'' + + ", phoneticSpelling='" + phoneticSpelling + '\'' + + ", sentence='" + sentence + '\'' + + ", isActive=" + isActive + + ", level=" + level + + '}'; + } +} diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/repository/UserRepository.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/repository/UserRepository.java new file mode 100644 index 000000000..418da7f47 --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/repository/UserRepository.java @@ -0,0 +1,8 @@ +package dev.pronunciationAppBack.repository; + +import dev.pronunciationAppBack.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + User getUserById(String id); +} diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/repository/WordRepository.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/repository/WordRepository.java new file mode 100644 index 000000000..e0d4c25cb --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/repository/WordRepository.java @@ -0,0 +1,10 @@ +package dev.pronunciationAppBack.repository; + +import dev.pronunciationAppBack.model.Word; +import org.springframework.data.jpa.repository.JpaRepository; + + +public interface WordRepository extends JpaRepository { + Word getWordById(String id); + Word getWordByPhoneticSpelling(String pronunciation); +} diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/service/UserService.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/service/UserService.java new file mode 100644 index 000000000..59772c1c4 --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/service/UserService.java @@ -0,0 +1,49 @@ +package dev.pronunciationAppBack.service; + +import dev.pronunciationAppBack.model.User; +import dev.pronunciationAppBack.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class UserService { + + @Autowired + private UserRepository userRepository; + + public List getAllUsers() { + return userRepository.findAll(); + } + + public Optional getUserById(String id) { + return Optional.ofNullable(userRepository.getUserById(id)); + } + + public User createUser(User user) { + return userRepository.save(user); + } + + public User updateUser(User user) { + return userRepository.save(user); + } + + public void deleteUser(String id) { + userRepository.deleteById(id); + } + + public void deleteAllUsers() { + userRepository.deleteAll(); + } + + public boolean existsById(String id) { + return userRepository.existsById(id); + } + + public long getUserCount() { + return userRepository.count(); + } + +} diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/service/WordService.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/service/WordService.java new file mode 100644 index 000000000..fba5d3e1b --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/service/WordService.java @@ -0,0 +1,53 @@ +package dev.pronunciationAppBack.service; + +import dev.pronunciationAppBack.model.Word; +import dev.pronunciationAppBack.repository.WordRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class WordService { + + @Autowired + private WordRepository wordRepository; + + public List getAllWords() { + return wordRepository.findAll(); + } + + public Optional getWordById(String id) { + return Optional.ofNullable(wordRepository.getWordById(id)); + } + + public Word createWord(Word word) { + return wordRepository.save(word); + } + + public Word updateWord(Word word) { + return wordRepository.save(word); + } + + public void deleteWord(String id) { + wordRepository.deleteById(id); + } + + public void deleteAllWords() { + wordRepository.deleteAll(); + } + + public boolean existsById(String id) { + return wordRepository.existsById(id); + } + + public long getWordCount() { + return wordRepository.count(); + } + + // Additional business logic can be added here + public Word getWordByPhoneticSpelling(String pronunciation) { + return wordRepository.getWordByPhoneticSpelling(pronunciation); + } +} \ No newline at end of file diff --git a/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/utilities/DataInitializer.java b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/utilities/DataInitializer.java new file mode 100644 index 000000000..8fa5be6b5 --- /dev/null +++ b/backend/pronunciationAppBack/src/main/java/dev/pronunciationAppBack/utilities/DataInitializer.java @@ -0,0 +1,66 @@ +package dev.pronunciationAppBack.utilities; + +import com.github.javafaker.Faker; +import dev.pronunciationAppBack.model.User; +import dev.pronunciationAppBack.repository.UserRepository; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +@Component // This ensures it runs at startup +public class DataInitializer implements CommandLineRunner { + + private final UserRepository userRepository; + private final Faker faker = new Faker(); + + public DataInitializer(UserRepository userRepository) { + this.userRepository = userRepository; + } + +// @Override +// public void run(String... args) { +// if (userRepository.count() == 0) { // Prevent duplicate inserts +// List users = new ArrayList<>(); +// for (int i = 0; i < 10; i++) { +// User user = new User(); +// user.setId(faker.internet().uuid()); // Explicit UUID +// user.setUsername(faker.name().username()); +// user.setEmail(faker.internet().emailAddress()); +// user.setPassword(faker.internet().password()); +// user.setJoinDate(faker.date().birthday().toInstant() +// .atZone(java.time.ZoneId.systemDefault()).toLocalDateTime()); +// user.setActive(faker.bool().bool()); +// +// users.add(user); +// } +// userRepository.saveAll(users); +// } +// } + + // streams version + @Override + public void run(String... args) { + if (userRepository.count() == 0) { // Prevent duplicate inserts + List users = IntStream.range(0, 10) //create an int stream + .mapToObj(i -> new User( //transforms int into object + faker.internet().uuid(), // Explicit UUID + faker.name().username(), + faker.internet().emailAddress(), + faker.internet().password(), + faker.date().birthday().toInstant() + .atZone(ZoneId.systemDefault()).toLocalDateTime(), + faker.bool().bool() + )) + .collect(Collectors.toList()); //collects objects to list + + userRepository.saveAll(users); + } + } + +} + diff --git a/backend/pronunciationAppBack/src/main/resources/application.properties b/backend/pronunciationAppBack/src/main/resources/application.properties index edb9ea0d2..451e92535 100644 --- a/backend/pronunciationAppBack/src/main/resources/application.properties +++ b/backend/pronunciationAppBack/src/main/resources/application.properties @@ -1 +1,32 @@ spring.application.name=pronunciationAppBack + +# H2 DATABASE SERVER +#spring.datasource.driverClassName=org.h2.Driver +#spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.h2.console.enabled=false + +# H2 IN MEMORY +#spring.datasource.url=jdbc:h2:mem:testdb +#spring.datasource.username=sa +#spring.datasource.password= + + +# H2 LOCAL DB SERVER +#spring.datasource.url=jdbc:h2:/home/emma/MyProjects/DataBase/pronunciationDB/pronunciationDB.db +#spring.datasource.username=emma +#spring.datasource.password=1234 + +# POSTGRES DB SERVER +spring.datasource.url=jdbc:postgresql://localhost:5432/pronunciationapp +spring.datasource.username=emma +spring.datasource.password=1234 +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect + + +# DDL OPTIONS: create-drop, create, update, none, validate +spring.jpa.hibernate.ddl-auto=create-drop + +# Ensure SQL scripts are executed +#spring.sql.init.mode=always +#spring.sql.init.platform=postgres \ No newline at end of file diff --git a/backend/pronunciationAppBack/src/main/resources/data.sql b/backend/pronunciationAppBack/src/main/resources/data.sql new file mode 100644 index 000000000..c3ba90bd4 --- /dev/null +++ b/backend/pronunciationAppBack/src/main/resources/data.sql @@ -0,0 +1,21 @@ +-- Enable UUID generation if not already enabled +CREATE EXTENSION IF NOT EXISTS "pgcrypto"; + +-- User mock data. + +-- INSERT INTO "user" (id, username, email, password, join_Date, is_Active) VALUES +-- (gen_random_uuid(), 'emma_dev', 'emma@example.com', 'securePass', CURRENT_TIMESTAMP, TRUE), + +-- Insert 10 users with explicit IDs +INSERT INTO "user" (id, username, email, password, join_date, is_active) VALUES +('111e4567-e89b-12d3-a456-426614174000', 'emma_dev', 'emma@example.com', 'securePass', CURRENT_TIMESTAMP, TRUE), +('112e4567-e89b-12d3-a456-426614174001', 'john_doe', 'john.doe@example.com', 'password456', CURRENT_TIMESTAMP, FALSE), +('113e4567-e89b-12d3-a456-426614174002', 'jane_smith', 'jane.smith@example.com', 'testpass', CURRENT_TIMESTAMP, TRUE), +('114e4567-e89b-12d3-a456-426614174003', 'alice_wonder', 'alice@example.com', 'wonder123', CURRENT_TIMESTAMP, TRUE), +('115e4567-e89b-12d3-a456-426614174004', 'bob_marley', 'bob@example.com', 'oneLove', CURRENT_TIMESTAMP, FALSE), +('116e4567-e89b-12d3-a456-426614174005', 'charlie_brown', 'charlie@example.com', 'peanuts', CURRENT_TIMESTAMP, TRUE), +('117e4567-e89b-12d3-a456-426614174006', 'david_garcia', 'david@example.com', 'strongPass', CURRENT_TIMESTAMP, TRUE), +('118e4567-e89b-12d3-a456-426614174007', 'eva_green', 'eva@example.com', 'greenTea', CURRENT_TIMESTAMP, FALSE), +('119e4567-e89b-12d3-a456-426614174008', 'frank_castle', 'frank@example.com', 'punisher', CURRENT_TIMESTAMP, TRUE), +('120e4567-e89b-12d3-a456-426614174009', 'grace_hopper', 'grace@example.com', 'coder', CURRENT_TIMESTAMP, TRUE); + diff --git a/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/PronunciationAppBackApplicationTests.java b/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/PronunciationAppBackApplicationTests.java index ea361613f..b2842b725 100644 --- a/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/PronunciationAppBackApplicationTests.java +++ b/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/PronunciationAppBackApplicationTests.java @@ -1,13 +1,65 @@ package dev.pronunciationAppBack; +import dev.pronunciationAppBack.model.Word; +import dev.pronunciationAppBack.repository.WordRepository; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; -@SpringBootTest -class PronunciationAppBackApplicationTests { +import static org.assertj.core.api.Assertions.assertThat; + +@DataJpaTest +public class PronunciationAppBackApplicationTests { + + @Autowired + private TestEntityManager entityManager; + + @Autowired + private WordRepository wordRepository; + + @Test + public void testCreateWord() { + Word word = new Word("1", "Example", "A thing characteristic of its kind", "ɪɡˈzæmpəl", "This is an example sentence.", true, 1); + // assign the word object to the repository and save to H2 + Word savedWord = wordRepository.save(word); + assertThat(savedWord).isNotNull(); + assertThat(savedWord.getId()).isEqualTo("1"); + } + + @Test + public void testReadWord() { + Word word = new Word("2", "Test", "A procedure to evaluate", "test", "This is a test sentence.", true, 2); + entityManager.persist(word); + + Word foundWord = wordRepository.findById("2").orElse(null); + assertThat(foundWord).isNotNull(); + assertThat(foundWord.getWordName()).isEqualTo("Test"); + } @Test - void contextLoads() { + public void testUpdateWord() { + Word word = new Word("3", "Update", "To bring up to date", "ˈʌpdeɪt", "This word will be updated.", true, 3); + entityManager.persist(word); + + Word wordToUpdate = wordRepository.findById("3").orElse(null); + assertThat(wordToUpdate).isNotNull(); + wordToUpdate.setDefinition("To make something more modern or up to date"); + wordRepository.save(wordToUpdate); + + Word updatedWord = wordRepository.findById("3").orElse(null); + assertThat(updatedWord).isNotNull(); + assertThat(updatedWord.getDefinition()).isEqualTo("To make something more modern or up to date"); } + @Test + public void testDeleteWord() { + Word word = new Word("4", "Delete", "To remove or erase", "dɪˈliːt", "This word will be deleted.", true, 4); + entityManager.persist(word); + + wordRepository.deleteById("4"); + + Word deletedWord = wordRepository.findById("4").orElse(null); + assertThat(deletedWord).isNull(); + } } diff --git a/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/UserControllerIntegrationTest.java b/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/UserControllerIntegrationTest.java new file mode 100644 index 000000000..4e5a06824 --- /dev/null +++ b/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/UserControllerIntegrationTest.java @@ -0,0 +1,106 @@ +package dev.pronunciationAppBack; + +import com.fasterxml.jackson.databind.ObjectMapper; +import dev.pronunciationAppBack.model.User; +import dev.pronunciationAppBack.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@Transactional +class UserControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserRepository userRepository; + + @Autowired + private ObjectMapper objectMapper; + + private User user; + + @BeforeEach + void setUp() { + userRepository.deleteAll(); // Clean database before each test + + user = new User(); + user.setUsername("testuser"); + user.setEmail("test@example.com"); + user.setPassword("password123"); + + userRepository.save(user); + } + + @Test + void testGetAllUsers() throws Exception { + mockMvc.perform(get("/api/users")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$[0].username").value("testuser")); + } + + @Test + void testGetUserById() throws Exception { + mockMvc.perform(get("/api/users/" + user.getId())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value("testuser")); + } + + @Test + void testCreateUser() throws Exception { + User newUser = new User(); + newUser.setUsername("newuser"); + newUser.setEmail("newuser@example.com"); + newUser.setPassword("securePass"); + + mockMvc.perform(post("/api/users/createUser") // Perform a POST request to the specified endpoint + .contentType(MediaType.APPLICATION_JSON) // Set the request's content type to JSON + .content(objectMapper.writeValueAsString(newUser))) // Convert 'newUser' to a JSON string and send it as the request body + .andExpect(status().isCreated()) // Expect the response status to be 201 CREATED + .andExpect(jsonPath("$.username").value("newuser")); // Expect the JSON response to contain "username": "newuser" + } + + + + @Test + void testUpdateUser() throws Exception { + user.setUsername("updateduser"); + + mockMvc.perform(put("/api/users/" + user.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(user))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value("updateduser")); + } + + @Test + void testDeleteUser() throws Exception { + assertTrue(userRepository.existsById(user.getId())); + + mockMvc.perform(delete("/api/users/" + user.getId())) + .andExpect(status().isOk()); + + assertFalse(userRepository.existsById(user.getId())); + } +} + diff --git a/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/UserServiceUnitTest.java b/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/UserServiceUnitTest.java new file mode 100644 index 000000000..02fc6cffb --- /dev/null +++ b/backend/pronunciationAppBack/src/test/java/dev/pronunciationAppBack/UserServiceUnitTest.java @@ -0,0 +1,135 @@ +package dev.pronunciationAppBack; + +import com.github.javafaker.Faker; +import dev.pronunciationAppBack.model.User; +import dev.pronunciationAppBack.repository.UserRepository; +import dev.pronunciationAppBack.service.UserService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class UserServiceUnitTest { + + @Mock + private UserRepository userRepository; + + @InjectMocks + private UserService userService; + + private List mockUsers; + private Faker faker = new Faker(); + + @BeforeEach + void setUp() { + mockUsers = IntStream.range(0, 10) + .mapToObj(i -> new User( + String.valueOf(i + 1), // ID as String + faker.name().username(), + faker.internet().emailAddress(), + faker.internet().password(), + LocalDateTime.now(), + faker.bool().bool() + )) + .collect(Collectors.toList()); + } + + @Test + void testCreateUser() { + User user = mockUsers.get(0); + when(userRepository.save(any(User.class))).thenReturn(user); + + User createdUser = userService.createUser(user); + + assertNotNull(createdUser); // user is not empty + assertEquals(user.getUsername(), createdUser.getUsername()); //they have the same username + verify(userRepository, times(1)).save(user); // userRepository's method save() is called once + } + + @Test + void testGetAllUsers() { + when(userRepository.findAll()).thenReturn(mockUsers); + + List retrievedUsers = userService.getAllUsers(); + + assertFalse(retrievedUsers.isEmpty()); //list is not empty + assertEquals(mockUsers.size(), retrievedUsers.size()); //size of lists is the same + verify(userRepository, times(1)).findAll(); //method findAll() runs once + } + + @Test + void testGetUserById() { + User user = mockUsers.get(0); + when(userRepository.getUserById(user.getId())).thenReturn(user); + + Optional retrievedUser = userService.getUserById(user.getId()); + + assertTrue(retrievedUser.isPresent()); // user exists + assertEquals(user.getUsername(), retrievedUser.get().getUsername()); // username from mock and service is the same + verify(userRepository, times(1)).getUserById(user.getId()); // method runs once + } + + @Test + void testUpdateUser() { + User user = mockUsers.get(0); + when(userRepository.save(any(User.class))).thenReturn(user); + + User updatedUser = userService.updateUser(user); + + assertNotNull(updatedUser); // user is not null + assertEquals(user.getUsername(), updatedUser.getUsername()); // username from mock and service are the same + verify(userRepository, times(1)).save(user); // method runs + } + + @Test + void testDeleteUser() { + String userId = mockUsers.get(0).getId(); + doNothing().when(userRepository).deleteById(userId); // no need for a mock response from repository + + userService.deleteUser(userId); + + verify(userRepository, times(1)).deleteById(userId); // method runs + } + + @Test + void testDeleteAllUsers() { + doNothing().when(userRepository).deleteAll(); + + userService.deleteAllUsers(); + + verify(userRepository, times(1)).deleteAll(); + } + + @Test + void testExistsById() { + String userId = mockUsers.get(0).getId(); + when(userRepository.existsById(userId)).thenReturn(true); + + boolean exists = userService.existsById(userId); + + assertTrue(exists); + verify(userRepository, times(1)).existsById(userId); + } + + @Test + void testGetUserCount() { + when(userRepository.count()).thenReturn((long) mockUsers.size()); + + long count = userService.getUserCount(); + + assertEquals(mockUsers.size(), count); // check mock and service lists are the same size + verify(userRepository, times(1)).count(); + } +} diff --git a/backend/resources/Test-JUnit DB/test-JUnit-Word.md b/backend/resources/Test-JUnit DB/test-JUnit-Word.md new file mode 100644 index 000000000..e9312dc38 --- /dev/null +++ b/backend/resources/Test-JUnit DB/test-JUnit-Word.md @@ -0,0 +1,171 @@ +# Test JUnit Word H2 DB + +## Test + +Here are 4 simple test cases for CRUD operations using `JUnit` and `Spring Boot` for the Word `entity`: + +```java +package dev.pronunciationAppBack; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; + +import static org.assertj.core.api.Assertions.assertThat; + +@DataJpaTest +public class WordRepositoryTest { + + @Autowired + private TestEntityManager entityManager; + + @Autowired + private WordRepository wordRepository; + + @Test + public void testCreateWord() { + Word word = new Word("1", "Example", "A thing characteristic of its kind", "ɪɡˈzæmpəl", "This is an example sentence.", true, 1); + Word savedWord = wordRepository.save(word); + assertThat(savedWord).isNotNull(); + assertThat(savedWord.getId()).isEqualTo("1"); + } + + @Test + public void testReadWord() { + Word word = new Word("2", "Test", "A procedure to evaluate", "test", "This is a test sentence.", true, 2); + entityManager.persist(word); + + Word foundWord = wordRepository.findById("2").orElse(null); + assertThat(foundWord).isNotNull(); + assertThat(foundWord.getWordName()).isEqualTo("Test"); + } + + @Test + public void testUpdateWord() { + Word word = new Word("3", "Update", "To bring up to date", "ˈʌpdeɪt", "This word will be updated.", true, 3); + entityManager.persist(word); + + Word wordToUpdate = wordRepository.findById("3").orElse(null); + assertThat(wordToUpdate).isNotNull(); + wordToUpdate.setDefinition("To make something more modern or up to date"); + wordRepository.save(wordToUpdate); + + Word updatedWord = wordRepository.findById("3").orElse(null); + assertThat(updatedWord).isNotNull(); + assertThat(updatedWord.getDefinition()).isEqualTo("To make something more modern or up to date"); + } + + @Test + public void testDeleteWord() { + Word word = new Word("4", "Delete", "To remove or erase", "dɪˈliːt", "This word will be deleted.", true, 4); + entityManager.persist(word); + + wordRepository.deleteById("4"); + + Word deletedWord = wordRepository.findById("4").orElse(null); + assertThat(deletedWord).isNull(); + } +} +``` + +These test cases cover the basic CRUD (Create, Read, Update, Delete) operations for the Word entity. Here's a brief explanation of each test: + +1. `testCreateWord`: Tests the creation of a new Word entity. +2. `testReadWord`: Tests reading a Word entity from the database. +3. `testUpdateWord`: Tests updating an existing Word entity. +4. `testDeleteWord`: Tests deleting a Word entity from the database. + +## Repository + +Note that these tests assume you have a `WordRepository` interface that extends `JpaRepository`. You'll need to create this interface in your project: + +```java +package dev.pronunciationAppBack; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface WordRepository extends JpaRepository { +} +``` + +Also, make sure you have the necessary dependencies in your `pom.xml` or `build.gradle` file for Spring Boot Test and JPA Test. + +## H2 and application.properties + +> For these JUnit tests to run properly with an in-memory database, we need to add the `H2 database` dependency and configure the `application.properties` file. + +Here's what you need to add: + +1. H2 Database Dependency: + Add this to your `pom.xml` if you're using Maven: + +```xml + + com.h2database + h2 + test + +``` + +Or if you're using Gradle, add this to your `build.gradle`: + +```gradle +dependencies { + testImplementation 'com.h2database:h2' +} +``` + +2. Application Properties: + Create a file named `application.properties` in your `src/test/resources` directory with the following content: + +```properties +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=password +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.show-sql=true +``` + +These settings will: + +- Configure an **in-memory H2 database for testing** +- Set up the database to create tables based on your entities and drop them after the tests +- Show SQL statements in the console, which can be helpful for debugging + +## Local DB + +First you must create the DB: + +```properties +# DDL OPTIONS: create-drop, create, update, none, validate +spring.jpa.hibernate.ddl-auto=create +``` + +Once created, change DDL to none + +```properties +spring.application.name=pronunciationAppBack + +# H2 DATABASE SERVER +spring.datasource.driverClassName=org.h2.Driver +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.h2.console.enabled=true + +# H2 IN MEMORY +#spring.datasource.url=jdbc:h2:mem:testdb +#spring.datasource.username=sa +#spring.datasource.password= + + +# H2 LOCAL DB SERVER +spring.datasource.url=jdbc:h2:/home/albert/MyProjects/DataBase/pronunciationDB/pronunciationDB.db +spring.datasource.username=albert +spring.datasource.password=1234 + +# DDL OPTIONS: create-drop, create, update, none, validate +spring.jpa.hibernate.ddl-auto=none +``` diff --git a/backend/resources/annotations/Param-PathVariable.md b/backend/resources/annotations/Param-PathVariable.md new file mode 100644 index 000000000..386848a2f --- /dev/null +++ b/backend/resources/annotations/Param-PathVariable.md @@ -0,0 +1,66 @@ +# Param vs Path Variable + +## Using @DeleteMapping in Spring Boot with Postman + +Spring Boot's `@DeleteMapping` annotation simplifies the process of handling HTTP DELETE requests. + +> The `@DeleteMapping` annotation in Spring Boot provides a clean and efficient way to handle DELETE requests. Whether you choose to use path variables or query parameters depends on your API design preferences and requirements. Postman is an excellent tool for testing these endpoints, allowing you to easily send DELETE requests and verify the results. + +## DeleteWord Example + +Here's a simple example of a delete operation in a Spring Boot controller: + +```java +@RestController +@RequestMapping("/words") +public class WordController { + + @Autowired + private WordRepository wordRepository; + + @DeleteMapping("/{id}") + public String deleteWord(@PathVariable("id") String idToDelete) { + wordRepository.deleteById(idToDelete); + return "Word deleted"; + } +} +``` + +In this example, the `deleteWord` method is mapped to handle DELETE requests to the `/words/{id}` endpoint[1][4]. The `@PathVariable` annotation binds the `id` from the URL to the `idToDelete` parameter[3]. + +## Testing with Postman + +To test this endpoint using Postman, follow these steps: + +1. Open Postman and create a new request. +2. Set the HTTP method to DELETE. +3. Enter the URL: `http://localhost:8080/words/{id}` (replace `{id}` with the actual ID you want to delete). +4. Click the "Send" button to execute the request. + +### Using Path Variable + +For our `deleteWord` example, we're using a path variable. The ID is part of the URL path: + +``` +DELETE http://localhost:8080/words/123 +``` + +Here, `123` is the ID of the word to be deleted[5]. + +### Using Query Parameter (Alternative Approach) + +While our example uses a path variable, you could also design your endpoint to use a query parameter: + +```java +@DeleteMapping +public String deleteWord(@RequestParam("id") String idToDelete) { + wordRepository.deleteById(idToDelete); + return "Word deleted"; +} +``` + +To test this with Postman: + +1. Set the URL to `http://localhost:8080/words` +2. Add a query parameter: Key: `id`, Value: `123` +3. The full URL will look like: `http://localhost:8080/words?id=123` diff --git a/backend/resources/annotations/jpa-hibernate-jdbc.png b/backend/resources/annotations/jpa-hibernate-jdbc.png new file mode 100644 index 000000000..a1b0eff9f Binary files /dev/null and b/backend/resources/annotations/jpa-hibernate-jdbc.png differ diff --git a/backend/resources/annotations/jpa.md b/backend/resources/annotations/jpa.md new file mode 100644 index 000000000..5c084e4ce --- /dev/null +++ b/backend/resources/annotations/jpa.md @@ -0,0 +1,12 @@ +# JPA + +[In Spring Boot what is the difference between CrudRepository and JpaRepository in extending a Java repository interface - Stack Overflow](https://stackoverflow.com/questions/72058502/in-spring-boot-what-is-the-difference-between-crudrepository-and-jparepository-i) + +## CrudRepository vs. JpaRepository + +| CrudRepository | JpaRepository | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| CrudRepository does not provide any method for pagination and sorting. | JpaRepository extends PagingAndSortingRepository. It provides all the methods for implementing the pagination. | +| It works as a **marker** interface. | JpaRepository extends both **CrudRepository** and **PagingAndSortingRepository**. | +| It provides CRUD function only. For example **findById(), findAll(),** etc. | It provides some extra methods along with the method of PagingAndSortingRepository and CrudRepository. For example, **flush(), deleteInBatch().** | +| It is used when we do not need the functions provided by JpaRepository and PagingAndSortingRepository. | It is used when we want to implement pagination and sorting functionality in an application. | diff --git a/backend/resources/annotations/jparepository.png b/backend/resources/annotations/jparepository.png new file mode 100644 index 000000000..82c5d07b6 Binary files /dev/null and b/backend/resources/annotations/jparepository.png differ diff --git a/backend/resources/containers/Containers-Spring.md b/backend/resources/containers/Containers-Spring.md new file mode 100644 index 000000000..4da920796 --- /dev/null +++ b/backend/resources/containers/Containers-Spring.md @@ -0,0 +1,150 @@ +# Popular Containers in Spring Boot + +> Containers in Java are typically defined by their ability to hold and manage collections of objects or references. + +However, for example, List`and`Optional` serve fundamentally different purposes: + +- `List` is a collection container designed to store multiple elements with order and allow dynamic manipulation. +- `Optional` is a wrapper to explicitly handle the presence or absence of a single value, preventing null reference issues. + +While both can "contain" elements, they solve distinct programming challenges: data storage versus null-safety management. + +#### Wrapper and Collection + +> A **wrapper** is a layer of code that "wraps around" something simpler, adding extra functionality or protection. Like a protective cover that makes something easier to use or more powerful. +> +> In Java, a wrapper takes a basic object or value and provides additional methods or behaviors to interact with it more conveniently. + + + +> A **Collection** is a more structured way of storing and managing those items, with methods to add, remove, and manipulate the group of elements. +> +> An **Iterable** is something you can loop through, like a collection of items. +> +> + +**Container Comparison: List vs Optional** + +| Characteristic | List | Optional | +| -------------------- | ------------------------------- | ------------------------------------------- | +| **Purpose** | Store multiple elements | Represent optional value | +| **Nullability** | Can contain null elements | Explicitly prevents null | +| **Size** | Dynamic, variable length | Always contains 0 or 1 element | +| **Mutability** | Mutable (add/remove elements) | Immutable | +| **Creation** | `new ArrayList<>()` | `Optional.of()`, `Optional.empty()` | +| **Common Methods** | `.add()`, `.remove()`, `.get()` | `.isPresent()`, `.orElse()`, `.ifPresent()` | +| **Java 8+ Feature** | Pre-Java 8 | Introduced in Java 8 | +| **Typical Use Case** | Collection storage | Avoiding null checks | +| **Stream Support** | `.stream()` directly | Treated as stream with `.stream()` | +| **Performance** | Higher memory overhead | Lightweight wrapper | + +### Response Containers + +1. **ResponseEntity** + + - Full control over HTTP response + - Set status codes, headers, body + - Example: + + ```java + return ResponseEntity.ok(word); + return ResponseEntity.notFound().build(); + return ResponseEntity.status(HttpStatus.CREATED).body(word); + ``` + +2. **Optional** + + - Prevent null pointer exceptions + - Avoid explicit null checks + - Example: + + ```java + Optional word = repository.findById(id); + return word.orElseThrow(() -> new ResourceNotFoundException()); + ``` + +3. **Page** + + - Pagination support + - Metadata about result set + - Example: + + ```java + Page words = repository.findAll(PageRequest.of(0, 10)); + ``` + +4. **Mono** and **Flux** (Reactive Programming) + + - Asynchronous data streams + - Non-blocking operations + - Example: + + ```java + Mono wordMono = wordRepository.findById(id); + Flux wordFlux = wordRepository.findAll(); + ``` + +5. **Resource** (HATEOAS) + + - Include hyperlinks in responses + - Support for hypermedia-driven APIs + - Example: + + ```java + Resource resource = new Resource<>(word); + resource.add(linkTo(methodOn(WordController.class).getWord(id)).withSelfRel()); + ``` + +### Key Benefits + +- Type safety +- Explicit error handling +- Flexible response management +- Support for modern architectural patterns + +## Non-Response + +### Data Containers + +1. **List** + + - Basic collection of elements + - Dynamic sizing + - Example: `List words = new ArrayList<>();` + +2. **Set** + + - Unique elements + - No duplicates + - Example: `Set uniqueWordNames = new HashSet<>();` + +3. **Map** + + - Key-value pairs + - Fast lookups + - Example: `Map wordMap = new HashMap<>();` + +4. **Stream** + + - Functional-style operations + - Lazy evaluation + - Example: `words.stream().filter(w -> w.getLevel() > 2)` + +5. **CompletableFuture** + + - Asynchronous computation + - Chaining operations + - Example: `CompletableFuture wordFuture = CompletableFuture.supplyAsync(() -> createWord());` + +6. **Queue** + + - First-In-First-Out (FIFO) + - Task scheduling + - Example: `Queue wordQueue = new LinkedList<>();` + +### Key Characteristics + +- Thread-safety +- Performance optimization +- Flexible data manipulation +- Support for functional programming diff --git a/backend/resources/CreateSpringBootproject.md b/backend/resources/create project/CreateSpringBootproject.md similarity index 100% rename from backend/resources/CreateSpringBootproject.md rename to backend/resources/create project/CreateSpringBootproject.md diff --git a/backend/resources/create project/create-spring-boot-b.png b/backend/resources/create project/create-spring-boot-b.png new file mode 100644 index 000000000..7230e9fdd Binary files /dev/null and b/backend/resources/create project/create-spring-boot-b.png differ diff --git a/backend/resources/create project/create-spring-boot.png b/backend/resources/create project/create-spring-boot.png new file mode 100644 index 000000000..415b8d1dd Binary files /dev/null and b/backend/resources/create project/create-spring-boot.png differ diff --git a/backend/resources/pronunciationAppBack-v0.0-project-structure.png b/backend/resources/create project/pronunciationAppBack-v0.0-project-structure.png similarity index 100% rename from backend/resources/pronunciationAppBack-v0.0-project-structure.png rename to backend/resources/create project/pronunciationAppBack-v0.0-project-structure.png diff --git a/backend/resources/start-spring-io-create-project.png b/backend/resources/create project/pronunciationAppBack-v0.0-spring-io-create-project.png similarity index 100% rename from backend/resources/start-spring-io-create-project.png rename to backend/resources/create project/pronunciationAppBack-v0.0-spring-io-create-project.png diff --git a/backend/resources/images/pronunciationAppBack-v0.0-api-rest-words.png b/backend/resources/images/pronunciationAppBack-v0.0-api-rest-words.png new file mode 100644 index 000000000..43e002693 Binary files /dev/null and b/backend/resources/images/pronunciationAppBack-v0.0-api-rest-words.png differ diff --git a/backend/resources/images/pronunciationAppBack-v0.0-basic-CRUD-controller-2.png b/backend/resources/images/pronunciationAppBack-v0.0-basic-CRUD-controller-2.png new file mode 100644 index 000000000..e97453151 Binary files /dev/null and b/backend/resources/images/pronunciationAppBack-v0.0-basic-CRUD-controller-2.png differ diff --git a/backend/resources/images/pronunciationAppBack-v0.0-basic-CRUD-controller.png b/backend/resources/images/pronunciationAppBack-v0.0-basic-CRUD-controller.png new file mode 100644 index 000000000..2d4acde25 Binary files /dev/null and b/backend/resources/images/pronunciationAppBack-v0.0-basic-CRUD-controller.png differ diff --git a/backend/resources/images/pronunciationAppBack-v0.0-db-2.png b/backend/resources/images/pronunciationAppBack-v0.0-db-2.png new file mode 100644 index 000000000..c6672f82a Binary files /dev/null and b/backend/resources/images/pronunciationAppBack-v0.0-db-2.png differ diff --git a/backend/resources/images/pronunciationAppBack-v0.0-db.png b/backend/resources/images/pronunciationAppBack-v0.0-db.png new file mode 100644 index 000000000..2a496ab0a Binary files /dev/null and b/backend/resources/images/pronunciationAppBack-v0.0-db.png differ diff --git a/backend/resources/images/pronunciationAppBack-v0.0-project-structure-2.png b/backend/resources/images/pronunciationAppBack-v0.0-project-structure-2.png new file mode 100644 index 000000000..22a050a1f Binary files /dev/null and b/backend/resources/images/pronunciationAppBack-v0.0-project-structure-2.png differ diff --git a/backend/resources/images/pronunciationAppBack-v0.0-project-structure.png b/backend/resources/images/pronunciationAppBack-v0.0-project-structure.png new file mode 100644 index 000000000..3dbc4ee10 Binary files /dev/null and b/backend/resources/images/pronunciationAppBack-v0.0-project-structure.png differ diff --git a/backend/resources/mock-data/bash-script/cli-execute-bash.png b/backend/resources/mock-data/bash-script/cli-execute-bash.png new file mode 100644 index 000000000..3af293426 Binary files /dev/null and b/backend/resources/mock-data/bash-script/cli-execute-bash.png differ diff --git a/backend/resources/mock-data/bash-script/data.json b/backend/resources/mock-data/bash-script/data.json new file mode 100644 index 000000000..edfdfa618 --- /dev/null +++ b/backend/resources/mock-data/bash-script/data.json @@ -0,0 +1,318 @@ +[ + { + "id": "8f7d1b9e3a2c5f6e", + "wordName": "aberration", + "definition": "a departure from what is normal, usual, or expected", + "phoneticSpelling": "ˌæbəˈreɪʃən", + "sentence": "The sudden drop in temperature was an aberration for this time of year.", + "level": 3, + "active": true + }, + { + "id": "2c4a6b8d0e1f3g5h", + "wordName": "benevolent", + "definition": "kind, generous, and caring about others", + "phoneticSpelling": "bəˈnevələnt", + "sentence": "The benevolent donor provided funds for the new hospital wing.", + "level": 2, + "active": true + }, + { + "id": "7j9k1l3m5n2o4p6q", + "wordName": "cacophony", + "definition": "a harsh, discordant mixture of sounds", + "phoneticSpelling": "kəˈkɒfəni", + "sentence": "The cacophony of car horns filled the busy street.", + "level": 4, + "active": true + }, + { + "id": "1r3s5t7u9v2w4x6y", + "wordName": "diligent", + "definition": "having or showing care and conscientiousness in one's work or duties", + "phoneticSpelling": "ˈdɪlɪdʒənt", + "sentence": "The diligent student always completed her homework on time.", + "level": 2, + "active": true + }, + { + "id": "8z0a2b4c6d1e3f5g", + "wordName": "ephemeral", + "definition": "lasting for a very short time", + "phoneticSpelling": "ɪˈfemərəl", + "sentence": "The beauty of cherry blossoms is ephemeral, lasting only a few days.", + "level": 3, + "active": true + }, + { + "id": "7h9i1j3k5l2m4n6o", + "wordName": "facetious", + "definition": "treating serious issues with deliberately inappropriate humor", + "phoneticSpelling": "fəˈsiːʃəs", + "sentence": "His facetious remarks about the company's financial troubles were not well-received.", + "level": 4, + "active": true + }, + { + "id": "5p7q9r1s3t5u2v4w", + "wordName": "gregarious", + "definition": "fond of company; sociable", + "phoneticSpelling": "ɡrɪˈɡeəriəs", + "sentence": "The gregarious host made sure all the guests felt welcome at the party.", + "level": 3, + "active": true + }, + { + "id": "6x8y0z2a4b1c3d5e", + "wordName": "harbinger", + "definition": "a person or thing that announces or signals the approach of another", + "phoneticSpelling": "ˈhɑːbɪndʒə", + "sentence": "The robin is often seen as a harbinger of spring.", + "level": 4, + "active": true + }, + { + "id": "9f1g3h5i7j2k4l6m", + "wordName": "incessant", + "definition": "continuing without pause or interruption", + "phoneticSpelling": "ɪnˈsesənt", + "sentence": "The incessant barking of the neighbor's dog kept us awake all night.", + "level": 3, + "active": true + }, + { + "id": "2n4o6p8q0r1s3t5u", + "wordName": "juxtapose", + "definition": "to place or deal with close together for contrasting effect", + "phoneticSpelling": "ˈdʒʌkstəpəʊz", + "sentence": "The artist decided to juxtapose images of war and peace in her latest work.", + "level": 4, + "active": true + }, + { + "id": "7v9w1x3y5z2a4b6c", + "wordName": "kinetic", + "definition": "relating to or resulting from motion", + "phoneticSpelling": "kɪˈnetɪk", + "sentence": "The sculpture's kinetic elements moved gently in the breeze.", + "level": 3, + "active": true + }, + { + "id": "8d0e2f4g6h1i3j5k", + "wordName": "lethargic", + "definition": "sluggish and apathetic", + "phoneticSpelling": "lɪˈθɑːdʒɪk", + "sentence": "The hot weather made everyone feel lethargic and unmotivated.", + "level": 2, + "active": true + }, + { + "id": "1l3m5n7o9p2q4r6s", + "wordName": "mellifluous", + "definition": "sweet or musical; pleasant to hear", + "phoneticSpelling": "məˈlɪfluəs", + "sentence": "The singer's mellifluous voice captivated the audience.", + "level": 4, + "active": true + }, + { + "id": "5t7u9v1w3x5y2z4a", + "wordName": "nefarious", + "definition": "wicked or criminal", + "phoneticSpelling": "nɪˈfeəriəs", + "sentence": "The detective uncovered the CEO's nefarious scheme to embezzle company funds.", + "level": 3, + "active": true + }, + { + "id": "6b8c0d2e4f1g3h5i", + "wordName": "obfuscate", + "definition": "to render obscure, unclear, or unintelligible", + "phoneticSpelling": "ˈɒbfʌskeɪt", + "sentence": "The politician tried to obfuscate the issue by using complex jargon.", + "level": 4, + "active": true + }, + { + "id": "9j1k3l5m7n2o4p6q", + "wordName": "panacea", + "definition": "a solution or remedy for all difficulties or diseases", + "phoneticSpelling": "ˌpænəˈsiːə", + "sentence": "Exercise is not a panacea for all health problems, but it certainly helps.", + "level": 3, + "active": true + }, + { + "id": "2r4s6t8u0v1w3x5y", + "wordName": "quintessential", + "definition": "representing the most perfect or typical example of a quality or class", + "phoneticSpelling": "ˌkwɪntɪˈsenʃəl", + "sentence": "The small town diner was the quintessential American eating establishment.", + "level": 4, + "active": true + }, + { + "id": "7z9a1b3c5d2e4f6g", + "wordName": "resilient", + "definition": "able to withstand or recover quickly from difficult conditions", + "phoneticSpelling": "rɪˈzɪliənt", + "sentence": "The resilient community quickly rebuilt after the natural disaster.", + "level": 3, + "active": true + }, + { + "id": "8h0i2j4k6l1m3n5o", + "wordName": "surreptitious", + "definition": "kept secret, especially because it would not be approved of", + "phoneticSpelling": "ˌsʌrəpˈtɪʃəs", + "sentence": "He made a surreptitious attempt to leave the party without saying goodbye.", + "level": 4, + "active": true + }, + { + "id": "1p3q5r7s9t2u4v6w", + "wordName": "tenacious", + "definition": "tending to keep a firm hold of something; clinging or adhering closely", + "phoneticSpelling": "təˈneɪʃəs", + "sentence": "The tenacious climber refused to give up, even when faced with steep cliffs.", + "level": 3, + "active": true + }, + { + "id": "5x7y9z1a3b5c2d4e", + "wordName": "ubiquitous", + "definition": "present, appearing, or found everywhere", + "phoneticSpelling": "juːˈbɪkwɪtəs", + "sentence": "Smartphones have become ubiquitous in modern society.", + "level": 4, + "active": true + }, + { + "id": "6f8g0h2i4j1k3l5m", + "wordName": "vociferous", + "definition": "expressing or characterized by vehement opinions; loud and forceful", + "phoneticSpelling": "və(ʊ)ˈsɪfərəs", + "sentence": "The vociferous crowd demanded justice for the wrongly accused man.", + "level": 4, + "active": true + }, + { + "id": "9n1o3p5q7r2s4t6u", + "wordName": "whimsical", + "definition": "playfully quaint or fanciful, especially in an appealing and amusing way", + "phoneticSpelling": "ˈwɪmzɪkəl", + "sentence": "The artist's whimsical sculptures brought a smile to everyone's face.", + "level": 3, + "active": true + }, + { + "id": "2v4w6x8y0z1a3b5c", + "wordName": "xenophobia", + "definition": "dislike of or prejudice against people from other countries", + "phoneticSpelling": "ˌzenəˈfəʊbiə", + "sentence": "The politician's xenophobia was evident in his discriminatory policies.", + "level": 4, + "active": true + }, + { + "id": "7d9e1f3g5h2i4j6k", + "wordName": "yearn", + "definition": "to have an intense feeling of longing for something", + "phoneticSpelling": "jɜːn", + "sentence": "After months away, she yearned to return to her hometown.", + "level": 2, + "active": true + }, + { + "id": "8l0m2n4o6p1q3r5s", + "wordName": "zealous", + "definition": "having or showing zeal; enthusiastic and diligent", + "phoneticSpelling": "ˈzeləs", + "sentence": "The zealous volunteer dedicated all her free time to the charity.", + "level": 3, + "active": true + }, + { + "id": "1t3u5v7w9x2y4z6a", + "wordName": "ambivalent", + "definition": "having mixed feelings or contradictory ideas about something or someone", + "phoneticSpelling": "æmˈbɪvələnt", + "sentence": "She felt ambivalent about moving to a new city for her job.", + "level": 3, + "active": true + }, + { + "id": "5b7c9d1e3f5g2h4i", + "wordName": "brevity", + "definition": "concise and exact use of words in writing or speech", + "phoneticSpelling": "ˈbrevɪti", + "sentence": "The speaker's brevity was appreciated by the audience.", + "level": 3, + "active": true + }, + { + "id": "6j8k0l2m4n1o3p5q", + "wordName": "cognizant", + "definition": "having knowledge or awareness", + "phoneticSpelling": "ˈkɒɡnɪzənt", + "sentence": "The manager was cognizant of the team's concerns about the new project.", + "level": 4, + "active": true + }, + { + "id": "9r1s3t5u7v2w4x6y", + "wordName": "dexterous", + "definition": "showing or having skill, especially with the hands", + "phoneticSpelling": "ˈdekstərəs", + "sentence": "The dexterous magician amazed the crowd with his sleight of hand.", + "level": 3, + "active": true + }, + { + "id": "2z4a6b8c0d1e3f5g", + "wordName": "eloquent", + "definition": "fluent or persuasive in speaking or writing", + "phoneticSpelling": "ˈeləkwənt", + "sentence": "Her eloquent speech moved the entire audience to tears.", + "level": 3, + "active": true + }, + { + "id": "7h9i1j3k5l2m4n6o", + "wordName": "fortuitous", + "definition": "happening by chance rather than intention", + "phoneticSpelling": "fɔːˈtjuːɪtəs", + "sentence": "Their meeting at the airport was entirely fortuitous.", + "level": 4, + "active": true + }, + { + "id": "8p0q2r4s6t1u3v5w", + "wordName": "garrulous", + "definition": "excessively talkative, especially on trivial matters", + "phoneticSpelling": "ˈɡærʊləs", + "sentence": "The garrulous passenger talked throughout the entire flight.", + "level": 4, + "active": true + }, + { + "id": "1x3y5z7a9b2c4d6e", + "wordName": "haphazard", + "definition": "lacking any obvious principle of organization", + "phoneticSpelling": "hæpˈhæzəd", + "sentence": "The room was in a haphazard state, with clothes and books strewn everywhere.", + "level": 3, + "active": true + }, + { + "id": "5f7g9h1i3j5k2l4m", + "wordName": "iconoclast", + "definition": "a person who attacks or criticizes cherished beliefs or institutions", + "phoneticSpelling": "aɪˈkɒnəklæst", + "sentence": "The young artist was seen as an iconoclast in the conservative art world.", + "level": 4, + "active": true + } +] + diff --git a/backend/resources/mock-data/bash-script/h2-db-fill-with-mock-data.png b/backend/resources/mock-data/bash-script/h2-db-fill-with-mock-data.png new file mode 100644 index 000000000..9587257d3 Binary files /dev/null and b/backend/resources/mock-data/bash-script/h2-db-fill-with-mock-data.png differ diff --git a/backend/resources/mock-data/bash-script/import_words.sh b/backend/resources/mock-data/bash-script/import_words.sh new file mode 100755 index 000000000..568b90fdd --- /dev/null +++ b/backend/resources/mock-data/bash-script/import_words.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +# Check if jq is installed +if ! command -v jq &> /dev/null +then + echo "jq is required but not installed. Please install jq and try again." + exit 1 +fi + +# Read the JSON file and process each word object +jq -c '.[]' data.json | while read -r word; do + # Send POST request for each word + curl -X POST \ + -H "Content-Type: application/json" \ + -d "$word" \ + http://localhost:8080/api/words/createWord + + echo -e "\nWord processed" + echo "----------" + + # Optional: Add a small delay between requests to avoid overwhelming the server + sleep 0.5 +done + +echo -e "\nAll words have been posted" + + diff --git a/backend/resources/mock-data/faker-java/java-faker.md b/backend/resources/mock-data/faker-java/java-faker.md new file mode 100644 index 000000000..0f7562bee --- /dev/null +++ b/backend/resources/mock-data/faker-java/java-faker.md @@ -0,0 +1,98 @@ +# Java Faker + +> **Java Faker is a tool that creates realistic-looking fake data**, including names, addresses, phone numbers, and much more. + +- [GitHub - DiUS/java-faker: Brings the popular ruby faker gem to Java](https://github.com/DiUS/java-faker) + +It’s useful for: + +1. **Populating** databases with test data +2. Creating **mock objects for unit testing** +3. Generating sample data for applications +4. Prototyping user interfaces + +The library provides a wide range of pre-defined categories (like name, address, phone number) and methods to generate fake data within those categories. It’s easy to use and can generate data in multiple languages and locales. + +For example, you can create a Faker instance and generate fake data like this: + +```java +Faker faker = new Faker(); + // Generates a random full name +String name = faker.name().fullName(); +// Generates a random email address +String email = faker.internet().emailAddress(); +``` + +Dependency for maven: + +```xml + + com.github.javafaker + javafaker + 1.0.2 + +``` + +## Example #1 + +- [CustomerDataLoader.java at master · AlbertProfe/restaurantManager · GitHub](https://github.com/AlbertProfe/restaurantManager/blob/master/src/main/java/dev/example/restaurantManager/utilities/CustomerDataLoader.java) + +- [DataLoader.java at master · AlbertProfe/restaurantManager · GitHub](https://github.com/AlbertProfe/restaurantManager/blob/master/src/main/java/dev/example/restaurantManager/utilities/DataLoader.java) + +In this example, it's used to create fake customer data for a restaurant management system. Here's how it works: + +1. The `CustomerDataLoader` class is annotated with `@Component`, making it a Spring-managed bean[3]. + +2. It uses `@Autowired` to inject the `CustomerRepository`, which will be used to save the generated data[3]. + +3. The `createFakeCustomers()` method first checks if the database is empty: + +```java +if (customerRepository.count() == 0) { + // Generate fake data +} +``` + +4. A new `Faker` instance is created with the US locale: + +```java +Faker faker = new Faker(new Locale("en-US")); +``` + +5. The method then generates 50 fake customers in a loop: + +```java +for (int i = 0; i < qty; i++) { + Customer customer = new Customer( + UUID.randomUUID().toString(), + faker.name().fullName(), + faker.internet().emailAddress(), + faker.phoneNumber().cellPhone(), + faker.random().nextInt(18, 130), + faker.random().nextBoolean(), + faker.random().nextBoolean() + ); + customerRepository.save(customer); +} +``` + +6. For each customer, Java Faker generates: + + - A random full name using `faker.name().fullName()` + - A random email address using `faker.internet().emailAddress()` + - A random cell phone number using `faker.phoneNumber().cellPhone()` + - A random age between 18 and 130 using `faker.random().nextInt(18, 130)` + - Two random boolean values using `faker.random().nextBoolean()` + +7. Each generated customer is saved to the database using `customerRepository.save(customer)`[3]. + +This approach allows the application to populate the database with realistic-looking customer data for testing or development purposes, without the need for manual data entry. + +Citations: +[1] https://github.com/AlbertProfe/restaurantManager/tree/master +[2] https://albertprofe.dev/springboot/sblab8-1.html +[3] https://albertprofe.dev/springboot/sblab8-3.html + +--- + +Answer from Perplexity: pplx.ai/share diff --git a/backend/resources/mock-data/import-csv/import-csv.md b/backend/resources/mock-data/import-csv/import-csv.md new file mode 100644 index 000000000..ff13c8d9d --- /dev/null +++ b/backend/resources/mock-data/import-csv/import-csv.md @@ -0,0 +1,32 @@ +# Import CSV to H2 + +> To test the H2 database CSV import functionality with a basic CSV file for a UserApp object, follow these steps: + +1. Create a CSV file named `users.csv` with the following content: + +``` +id,username,email,created_at +1,john_doe,john@example.com,2025-01-24 20:00:00 +2,jane_smith,jane@example.com,2025-01-24 20:15:00 +3,bob_johnson,bob@example.com,2025-01-24 20:30:00 +``` + +2. Save this file in a location accessible to your H2 database, for example, `/path/to/users.csv`. + +3. Connect to your H2 database and execute the following SQL command: + +```sql +CREATE TABLE UserApp AS SELECT * FROM CSVREAD('/path/to/users.csv'); +``` + +This command will create a new table named `UserApp` with columns matching the CSV file structure. + +4. To verify the import, you can run a SELECT query: + +```sql +SELECT * FROM UserApp; +``` + +This should display the imported data from the CSV file. + +> **Note** that the H2 database will automatically infer the column types based on the data in the CSV file[2]. In this case, `id` will likely be treated as an INTEGER, while `username` and `email` will be VARCHAR, and `created_at` will be TIMESTAMP. diff --git a/backend/resources/mock-data/import-csv/userApp-from-csv.png b/backend/resources/mock-data/import-csv/userApp-from-csv.png new file mode 100644 index 000000000..163c5bd77 Binary files /dev/null and b/backend/resources/mock-data/import-csv/userApp-from-csv.png differ diff --git a/backend/resources/mock-data/import-csv/userApp-sql-import-csv.png b/backend/resources/mock-data/import-csv/userApp-sql-import-csv.png new file mode 100644 index 000000000..7b92d9239 Binary files /dev/null and b/backend/resources/mock-data/import-csv/userApp-sql-import-csv.png differ diff --git a/backend/resources/mock-data/import-csv/users.csv b/backend/resources/mock-data/import-csv/users.csv new file mode 100644 index 000000000..d4ca3dc38 --- /dev/null +++ b/backend/resources/mock-data/import-csv/users.csv @@ -0,0 +1,4 @@ +id,username,email,created_at +1,john_doe,john@example.com,2025-01-24 20:00:00 +2,jane_smith,jane@example.com,2025-01-24 20:15:00 +3,bob_johnson,bob@example.com,2025-01-24 20:30:00 diff --git a/backend/resources/mock-data/mockServer-postman/mock-serverPostman.md b/backend/resources/mock-data/mockServer-postman/mock-serverPostman.md new file mode 100644 index 000000000..62829a7a2 --- /dev/null +++ b/backend/resources/mock-data/mockServer-postman/mock-serverPostman.md @@ -0,0 +1,49 @@ +# How to create a mock server in Postman from a collection? + +> Mock servers simulate real API behavior and are useful for testing and development without relying on live APIs. + +## Reference + +- https://86c6ea23-f1a9-4a53-85a9-9c9869d64809.mock.pstmn.io/api/words/ + +- [Configure and use a Postman mock server | Postman Docs](https://learning.postman.com/docs/designing-and-developing-your-api/mocking-data/setting-up-mock/) + +## Step-by-step + + + +To create a mock server in Postman from a collection, follow these steps: + +1. **Select the Collection**: + + - In the Postman sidebar, go to **Collections**. + - Find the collection you want to mock, click **View more actions** (three dots), and select **Mock Collection**. + +2. **Configure Mock Server Details**: + + - Provide a name for your mock server. + - (Optional) Choose an environment to use environment variables with your mock server. + - Decide whether to make the mock server private or public. Private servers require an API key in the request header. + - Optionally, simulate a fixed network delay by specifying a response delay. + +3. **Create the Mock Server**: + + - Click **Create Mock Server** to finalize the setup. + - Postman will display the mock server URL, which can be used in requests. + +4. **Add Examples to Requests**: + + - Ensure that each request in your collection has at least one saved example. Postman uses these examples to generate responses for mock requests. + +5. **Use the Mock Server**: + + - Copy the mock server URL and use it in your API requests. + - If the server is private, include your Postman API key as an `x-api-key` header. + +6. **Edit or Delete Mock Servers**: + + - To edit, go to **Mock Servers** in the sidebar, select the desired server, and click **Edit Configuration**. + - To delete, click **View more actions** next to the server name and select **Delete**. + +Citations: +[1] https://learning.postman.com/docs/designing-and-developing-your-api/mocking-data/setting-up-mock/ diff --git a/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-1.png b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-1.png new file mode 100644 index 000000000..23c7bb50c Binary files /dev/null and b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-1.png differ diff --git a/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-2.png b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-2.png new file mode 100644 index 000000000..e925ef98e Binary files /dev/null and b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-2.png differ diff --git a/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-3.png b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-3.png new file mode 100644 index 000000000..80a3d7bca Binary files /dev/null and b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-3.png differ diff --git a/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-4.png b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-4.png new file mode 100644 index 000000000..afa299449 Binary files /dev/null and b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-4.png differ diff --git a/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-5.png b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-5.png new file mode 100644 index 000000000..09d0cbe06 Binary files /dev/null and b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-5.png differ diff --git a/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-6.png b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-6.png new file mode 100644 index 000000000..00cef8081 Binary files /dev/null and b/backend/resources/mock-data/mockServer-postman/mockServer_Postman_from_collection-6.png differ diff --git a/backend/resources/pronunciationApp-v0.1.md b/backend/resources/pronunciationApp-v0.1.md new file mode 100644 index 000000000..62dbb8fcd --- /dev/null +++ b/backend/resources/pronunciationApp-v0.1.md @@ -0,0 +1,390 @@ +# PronunciationApp Backend v0.1 + +## Project + +- pronunciationApp Backend **GitHub** [code](https://github.com/AlbertProfe/pronunciationApp/tree/backend-spring-boot/backend/pronunciationAppBack) + +- pronunciatoinApp Backend [resources](https://github.com/AlbertProfe/pronunciationApp/tree/backend-spring-boot/backend/resources) **documentation** + +### Project Structure + +A Spring Boot backend application for the `Pronunciation App`, using: + +- H2 Database (local file-based or memory for certain purposes) +- `Spring Data JPA` +- REST Controller +- Service Layer +- Entity Mapping: `@Entity` + +### Dependencies + +Add these to your `pom.xml`: + +```xml + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + com.h2database + h2 + runtime + + +``` + +### Entity + +`Word.java`: + +```java +package com.pronunciationapp.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Word { + + @Id + private String id; + private String wordName; + private String definition; + private String phoneticSpelling; + private String sentence; + private boolean isActive; + private int level; + + // Constructors + public Word() {} + + public Word(String id, String wordName, String definition, + String phoneticSpelling, String sentence, + boolean isActive, int level) { + this.id = id; + this.wordName = wordName; + this.definition = definition; + this.phoneticSpelling = phoneticSpelling; + this.sentence = sentence; + this.isActive = isActive; + this.level = level; + } + + // Getters and Setters + // ... (generate these for all fields) +} +``` + +### Repository + +`WordRepository.java`: + +```java +package com.pronunciationapp.repository; + +import com.pronunciationapp.model.Word; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface WordRepository extends JpaRepository { + List findByIsActiveTrue(); + List findByLevel(int level); + Word findByWordName(String wordName); +} +``` + +### Service + +`WordService.java`: + +```java +package com.pronunciationapp.service; + +import com.pronunciationapp.model.Word; +import com.pronunciationapp.repository.WordRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Service +public class WordService { + + @Autowired + private WordRepository wordRepository; + + public List getAllWords() { + return wordRepository.findAll(); + } + + public Optional getWordById(String id) { + return wordRepository.findById(id); + } + + public Word createWord(Word word) { + if (word.getId() == null) { + word.setId(UUID.randomUUID().toString()); + } + return wordRepository.save(word); + } + + public Word updateWord(String id, Word wordDetails) { + Word word = wordRepository.findById(id) + .orElseThrow(() -> new RuntimeException("Word not found")); + + word.setWordName(wordDetails.getWordName()); + word.setDefinition(wordDetails.getDefinition()); + word.setPhoneticSpelling(wordDetails.getPhoneticSpelling()); + word.setSentence(wordDetails.getSentence()); + word.setActive(wordDetails.isActive()); + word.setLevel(wordDetails.getLevel()); + + return wordRepository.save(word); + } + + public void deleteWord(String id) { + Word word = wordRepository.findById(id) + .orElseThrow(() -> new RuntimeException("Word not found")); + wordRepository.delete(word); + } + + public List getActiveWords() { + return wordRepository.findByIsActiveTrue(); + } + + public List getWordsByLevel(int level) { + return wordRepository.findByLevel(level); + } +} +``` + +### REST Controller + +`WordController.java`: + +```java +package com.pronunciationapp.controller; + +import com.pronunciationapp.model.Word; +import com.pronunciationapp.service.WordService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/words") +public class WordController { + + @Autowired + private WordService wordService; + + @GetMapping + public List getAllWords() { + return wordService.getAllWords(); + } + + @GetMapping("/{id}") + public ResponseEntity getWordById(@PathVariable String id) { + return wordService.getWordById(id) + .map(ResponseEntity::ok) + .orElse(ResponseEntity.notFound().build()); + } + + @PostMapping + public Word createWord(@RequestBody Word word) { + return wordService.createWord(word); + } + + @PutMapping("/{id}") + public ResponseEntity updateWord( + @PathVariable String id, + @RequestBody Word wordDetails + ) { + Word updatedWord = wordService.updateWord(id, wordDetails); + return ResponseEntity.ok(updatedWord); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteWord(@PathVariable String id) { + wordService.deleteWord(id); + return ResponseEntity.ok().build(); + } + + @GetMapping("/active") + public List getActiveWords() { + return wordService.getActiveWords(); + } + + @GetMapping("/level/{level}") + public List getWordsByLevel(@PathVariable int level) { + return wordService.getWordsByLevel(level); + } +} +``` + +### Application Properties + +`application.properties`: + +```properties +spring.application.name=pronunciationAppBack + +# H2 DATABASE SERVER +spring.datasource.driverClassName=org.h2.Driver +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.h2.console.enabled=true + +# H2 LOCAL DB SERVER +spring.datasource.url=jdbc:h2:/home/albert/MyProjects/DataBase/pronunciationDB/pronunciationDB.db +spring.datasource.username=albert +spring.datasource.password=1234 + +# DDL OPTIONS: create-drop, create, update, none, validate +spring.jpa.hibernate.ddl-auto=update + +# Enable H2 web console +spring.h2.console.path=/h2-console +``` + +## Testing with Postman + +Sample JSON for testing: + +```json +{ + "words": [ + { + "id": "8b9248a4e0b64bbccf82e7723a3734279bf9bbc4", + "wordName": "benevolent", + "definition": "Kind and generous", + "phoneticSpelling": "/bɪˈnɛvələnt/", + "sentence": "Her benevolent actions helped many people in need.", + "isActive": true, + "level": 2 + }, + { + "id": "3a7bd3e2a07e8c7e9b6e0d2c1f4a5b8d9c0e3f2", + "wordName": "serendipity", + "definition": "A fortunate discovery", + "phoneticSpelling": "/ˌserənˈdɪpɪti/", + "sentence": "Meeting her was pure serendipity.", + "isActive": true, + "level": 3 + } + ] +} +``` + +### Postman Collection Setup + +Create a new collection for `PronunciationApp` with these CRUD endpoints: + +1. **GET All Words** + + - Method: GET + - URL: `http://localhost:8080/api/words` + - Expected: Returns full list of words + +2. **GET Word by ID** + + - Method: GET + - URL: `http://localhost:8080/api/words/{id}` + - Params: Replace `{id}` with a specific word ID + - Expected: Returns single word details + +3. **POST Create Word** + + - Method: POST + + - URL: `http://localhost:8080/api/words` + + - Body (raw JSON): + + ```json + { + "wordName": "ephemeral", + "definition": "Lasting for a very short time", + "phoneticSpelling": "/ɪˈfɛmərəl/", + "sentence": "The beauty of cherry blossoms is ephemeral.", + "isActive": true, + "level": 2 + } + ``` + + - Expected: Returns created word with auto-generated ID + +4. **PUT Update Word** + + - Method: PUT + + - URL: `http://localhost:8080/api/words/{id}` + + - Params: Replace `{id}` with existing word ID + + - Body (raw JSON): + + ```json + { + "wordName": "ephemeral", + "definition": "Lasting for a very short time", + "phoneticSpelling": "/ɪˈfɛmərəl/", + "sentence": "The beauty of cherry blossoms is ephemeral.", + "isActive": false, + "level": 3 + } + ``` + + - Expected: Returns updated word + +5. **DELETE Word** + + - Method: DELETE + - URL: `http://localhost:8080/api/words/{id}` + - Params: Replace `{id}` with word ID to delete + - Expected: 200 OK response + +### Additional Test Endpoints + +- **GET Active Words**: `http://localhost:8080/api/words/active` +- **GET Words by Level**: `http://localhost:8080/api/words/level/2` + +### Testing Workflow + +1. Import collection in Postman +2. Start Spring Boot application +3. Execute requests in sequence +4. Verify responses match expected results + +### Common Testing Scenarios + +- Test creating words with missing fields +- Validate ID generation +- Check level and active status constraints +- Test boundary conditions (max/min levels) + +## Running the Application + +1. Ensure you have Java 17+ and Maven installed +2. Configure the database path in `application.properties` +3. Run the Spring Boot application +4. Access H2 console at `http://localhost:8080/h2-console` +5. Access API endpoints at `http://localhost:8080/api/words` + +## Notes + +- The application uses a **local** H2 database file +- UUID is used for generating unique word IDs +- Basic CRUD operations are implemented +- Additional **query methods are available in the repository** and service layers diff --git a/backend/resources/pronunciationApp-v0.2.md b/backend/resources/pronunciationApp-v0.2.md new file mode 100644 index 000000000..b902675e9 --- /dev/null +++ b/backend/resources/pronunciationApp-v0.2.md @@ -0,0 +1,445 @@ +# PronunciationApp Backend v0.2 + +## Refactoring @RestController and adding @Service + +> Implementing a `WordService` and refactoring the `WordController` is a good practice in Spring Boot applications for several reasons. + +Let's implement the `WordService`, refactor the `WordController`, and discuss why this approach is beneficial. + +### Implementing WordService + +```java +package dev.pronunciationAppBack.service; + +import dev.pronunciationAppBack.model.Word; +import dev.pronunciationAppBack.repository.WordRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class WordService { + + @Autowired + private WordRepository wordRepository; + + public List getAllWords() { + return wordRepository.findAll(); + } + + public Optional getWordById(String id) { + return Optional.ofNullable(wordRepository.getWordById(id)); + } + + public Word createWord(Word word) { + return wordRepository.save(word); + } + + public Word updateWord(Word word) { + return wordRepository.save(word); + } + + public void deleteWord(String id) { + wordRepository.deleteById(id); + } + + public void deleteAllWords() { + wordRepository.deleteAll(); + } + + public boolean existsById(String id) { + return wordRepository.existsById(id); + } + + public long getWordCount() { + return wordRepository.count(); + } + + // Additional business logic can be added here + public Word getWordByPhoneticSpelling(String pronunciation) { + return wordRepository.getWordByPhoneticSpelling(pronunciation); + } +} +``` + +### Refactoring WordController + +```java +@RestController +@RequestMapping("/api/words") +public class WordController { + + @Autowired + private WordService wordService; + + /* + @GetMapping("/hello") + public ResponseEntity hello() { + HttpHeaders headers = getCommonHeaders("Hello endpoint"); + return new ResponseEntity<>("hello Emiliano, are you sleeping?", headers, HttpStatus.OK); + } + */ + + @GetMapping + public ResponseEntity> getAllWords() { + List words = wordService.getAllWords(); + HttpHeaders headers = getCommonHeaders("Get all words"); + + return !words.isEmpty() + ? new ResponseEntity<>(words, headers, HttpStatus.OK) + : new ResponseEntity<>(headers, HttpStatus.NOT_FOUND); + } + + @GetMapping("/{id}") + public ResponseEntity getWordById(@PathVariable String id) { + Optional word = wordService.getWordById(id); + HttpHeaders headers = getCommonHeaders("Get word by ID"); + + return word.map(value -> new ResponseEntity<>(value, headers, HttpStatus.OK)) + .orElseGet(() -> new ResponseEntity<>(headers, HttpStatus.NOT_FOUND)); + } + + @PostMapping("/createWord") + public ResponseEntity createWord(@RequestBody Word word) { + Word createdWord = wordService.createWord(word); + HttpHeaders headers = getCommonHeaders("Create a new word"); + + return new ResponseEntity<>(createdWord, headers, HttpStatus.CREATED); + } + + @PutMapping("/{id}") + public ResponseEntity updateWord(@PathVariable String id, @RequestBody Word word) { + Word updatedWord = wordService.updateWord(word); + HttpHeaders headers = getCommonHeaders("Update a word"); + + return new ResponseEntity<>(updatedWord, headers, HttpStatus.OK); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteWord(@PathVariable("id") String idToDelete) { + HttpHeaders headers = getCommonHeaders("Delete a word"); + + if (wordService.existsById(idToDelete)) { + wordService.deleteWord(idToDelete); + return new ResponseEntity<>("Word deleted", headers, HttpStatus.OK); + } else { + return new ResponseEntity<>("Word not found", headers, HttpStatus.NOT_FOUND); + } + } + + @DeleteMapping + public ResponseEntity deleteAllWords() { + wordService.deleteAllWords(); + HttpHeaders headers = getCommonHeaders("Delete all words"); + return new ResponseEntity<>("All words deleted", headers, HttpStatus.OK); + } + + private HttpHeaders getCommonHeaders(String description) { + HttpHeaders headers = new HttpHeaders(); + headers.add("desc", description); + headers.add("content-type", "application/json"); + headers.add("date", new Date().toString()); + headers.add("server", "Spring Boot"); + headers.add("version", "1.0.0"); + headers.add("word-count", String.valueOf(wordService.getWordCount())); + headers.add("object", "words"); + return headers; + } +} +``` + +## Why is this refactoring necessary? + +1. **Separation of Concerns**: The service layer separates business logic from the controller, making the code more modular and easier to maintain. + +2. **Reusability**: Business logic in the service can be reused across different controllers or other services. + +3. **Testability**: It's easier to unit test business logic in a service class than in a controller. + +4. **Scalability**: As the application grows, having a separate service layer makes it easier to manage and scale the codebase. + +5. **Abstraction**: The controller doesn't need to know about the repository implementation, providing better abstraction. + +### Check health + +Well create a new controller class that incorporates the health check endpoint along with other best practices. + +Here's the new `HealthController` class: + +```java +package dev.pronunciationAppBack.controller; + +import dev.pronunciationAppBack.model.Word; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api/health") +public class HealthController { + + @Autowired + private WordService wordService; + + @GetMapping + public ResponseEntity> healthCheck() { + Map healthStatus = new HashMap<>(); + healthStatus.put("status", "UP"); + healthStatus.put("timestamp", new Date()); + healthStatus.put("wordCount", wordService.getWordCount()); + + boolean databaseConnection = checkDatabaseConnection(); + healthStatus.put("database", databaseConnection ? "Connected" : "Disconnected"); + + // Add more health checks as needed + healthStatus.put("memoryUsage", getMemoryUsage()); + healthStatus.put("diskSpace", getDiskSpace()); + + HttpHeaders headers = getCommonHeaders("Health check endpoint"); + HttpStatus status = databaseConnection ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE; + + return new ResponseEntity<>(healthStatus, headers, status); + } + + private boolean checkDatabaseConnection() { + try { + wordService.getAllWords(); + return true; + } catch (Exception e) { + return false; + } + } + + private Map getMemoryUsage() { + Runtime runtime = Runtime.getRuntime(); + Map memoryInfo = new HashMap<>(); + memoryInfo.put("total", runtime.totalMemory()); + memoryInfo.put("free", runtime.freeMemory()); + memoryInfo.put("used", runtime.totalMemory() - runtime.freeMemory()); + return memoryInfo; + } + + private Map getDiskSpace() { + java.io.File root = new java.io.File("/"); + Map diskInfo = new HashMap<>(); + diskInfo.put("total", root.getTotalSpace()); + diskInfo.put("free", root.getFreeSpace()); + diskInfo.put("usable", root.getUsableSpace()); + return diskInfo; + } + + private HttpHeaders getCommonHeaders(String description) { + HttpHeaders headers = new HttpHeaders(); + headers.add("desc", description); + headers.add("content-type", "application/json"); + headers.add("date", new Date().toString()); + headers.add("server", "Spring Boot"); + headers.add("version", "1.0.0"); + return headers; + } +} +``` + +This new `HealthController` class offers several improvements: + +1. **Dedicated controller**: It's a separate controller focused on health and monitoring, following the Single Responsibility Principle. + +2. **Comprehensive health check**: The `healthCheck()` method provides a detailed health status, including database connectivity, word count, memory usage, and disk space. + +3. **Modular design**: Different aspects of the health check are separated into methods, making the code more maintainable and easier to extend. + +4. **Resource monitoring**: It includes basic system resource monitoring (memory and disk space), which can be crucial for identifying potential issues. + +5. **Consistent headers**: It uses a `getCommonHeaders()` method similar to the `WordController`, maintaining consistency across the API. + +6. **Appropriate mapping**: The controller uses the `/api/health` endpoint, which is a common convention for health check APIs. + + + +> This health check endpoint provides a comprehensive overview of your application's health, making it valuable for monitoring and troubleshooting in production environments. + +### @Service business logic examples + +#### Real Use Case #1 + +Let's consider a real use case where the service layer becomes key: + +Imagine you're expanding your pronunciation app to include a feature for generating word lists based on difficulty levels. This involves complex logic that shouldn't be in the controller. + +Add this method to `WordService`: + +```java +public List getWordsByDifficultyLevel(int level) { + List allWords = wordRepository.findAll(); + return allWords.stream() + .filter(word -> calculateDifficulty(word) == level) + .collect(Collectors.toList()); +} + +private int calculateDifficulty(Word word) { + // Complex logic to determine word difficulty + // Based on factors like length, rarity, phonetic complexity, etc. + // This is a simplified example + int difficulty = word.getWord().length(); + difficulty += word.getPhoneticSpelling().length(); + // More factors... + return difficulty / 5; // Normalize to a 1-10 scale +} +``` + +And in `WordController`: + +```java +@GetMapping("/difficulty/{level}") +public ResponseEntity> getWordsByDifficulty(@PathVariable int level) { + List words = wordService.getWordsByDifficultyLevel(level); + HttpHeaders headers = getCommonHeaders("Get words by difficulty"); + + return !words.isEmpty() + ? new ResponseEntity<>(words, headers, HttpStatus.OK) + : new ResponseEntity<>(headers, HttpStatus.NOT_FOUND); +} +``` + +In this case, the service layer is key because: + +1. It encapsulates complex business logic (difficulty calculation) that doesn't belong in the controller. +2. This logic can be reused in other parts of the application. +3. It's easier to test and modify the difficulty calculation independently of the controller. +4. If you decide to change how difficulty is calculated or stored (e.g., moving to a database-computed value), you only need to change the service, not the controller. + +> This structure allows your application to grow and adapt to new requirements more easily, demonstrating the importance of a well-structured service layer in a Spring Boot application. + +#### Real Use Case #2 + +Let's consider another real-world use case where the WordService would be essential: implementing a personalized word recommendation system based on a user's learning history and performance. + +Here's how we could implement this feature: + +```java +@Service +public class WordService { + @Autowired + private WordRepository wordRepository; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserProgressRepository userProgressRepository; + + public List getPersonalizedWordRecommendations(String userId, int count) { + User user = userRepository.findById(userId) + .orElseThrow(() -> new UserNotFoundException("User not found")); + + List userProgress = userProgressRepository.findByUserId(userId); + + Set masteredWords = userProgress.stream() + .filter(progress -> progress.getMasteryLevel() > 0.8) + .map(UserProgress::getWordId) + .collect(Collectors.toSet()); + + List allWords = wordRepository.findAll(); + + return allWords.stream() + .filter(word -> !masteredWords.contains(word.getId())) + .sorted(Comparator.comparingDouble(word -> calculateRelevance(word, user, userProgress))) + .limit(count) + .collect(Collectors.toList()); + } + + private double calculateRelevance(Word word, User user, List userProgress) { + double difficultyScore = calculateDifficulty(word); + double userLevelScore = user.getProficiencyLevel(); + double progressScore = userProgress.stream() + .filter(progress -> progress.getWordId().equals(word.getId())) + .mapToDouble(UserProgress::getMasteryLevel) + .findFirst() + .orElse(0.0); + + // Complex algorithm to determine word relevance based on user's level, + // word difficulty, and user's progress on this word + return (difficultyScore * 0.4) + (userLevelScore * 0.3) + ((1 - progressScore) * 0.3); + } + + private double calculateDifficulty(Word word) { + // Implementation of difficulty calculation + // ... + } +} +``` + +In the controller: + +```java +@RestController +@RequestMapping("/api/words") +public class WordController { + @Autowired + private WordService wordService; + + @GetMapping("/recommendations/{userId}") + public ResponseEntity> getPersonalizedRecommendations( + @PathVariable String userId, + @RequestParam(defaultValue = "10") int count) { + List recommendations = wordService.getPersonalizedWordRecommendations(userId, count); + HttpHeaders headers = getCommonHeaders("Get personalized word recommendations"); + + return !recommendations.isEmpty() + ? new ResponseEntity<>(recommendations, headers, HttpStatus.OK) + : new ResponseEntity<>(headers, HttpStatus.NOT_FOUND); + } +} +``` + +This use case demonstrates why the service layer is key: + +1. Complex Business Logic: The recommendation system involves complex calculations and data processing that shouldn't be in the controller. + +2. Data Integration: It requires integration of data from multiple repositories (words, users, and user progress), which is better handled in a service. + +3. Reusability: The recommendation logic can be reused in other parts of the application, such as generating daily practice sessions or progress reports. + +4. Scalability: As the recommendation algorithm becomes more sophisticated (e.g., incorporating machine learning), the service can be easily extended without affecting the controller. + +5. Testability: The complex recommendation logic can be unit tested independently of the web layer. + +6. Separation of Concerns: The controller remains focused on handling HTTP requests and responses, while the service manages the business logic. + +7. Flexibility: If you decide to change how recommendations are generated (e.g., using a third-party AI service), you only need to modify the service, not the controller. + +> This example showcases how a well-structured service layer can handle complex, data-intensive operations while keeping the controller lean and focused on its primary responsibility of managing HTTP interactions. + +## Repository + +```java +public interface WordRepository extends JpaRepository { +``` + +> JpaRepository is an interface provided by Spring Data JPA that simplifies database operations. +> +> It extends other repository interfaces, offering a complete set of CRUD (Create, Read, Update, Delete) operations, as well as paging and sorting capabilities. + +An interface in Java is a contract that specifies a set of abstract methods that a class must implement. It defines what a class should do, without specifying how it should do it. + +In the case of `WordRepository`, extending` JpaRepository` is a good idea because: + +1. Automatic implementation: Spring Data JPA automatically generates the implementation of the repository interface at runtime, saving developers from writing boilerplate code. + +2. Built-in methods: It provides common database operations like save(), findAll(), and deleteById() out of the box. + +3. Custom queries: You can define custom query methods, as seen with getWordById() and getWordByPhoneticSpelling(), by simply declaring them in the interface. + +4. Type safety: JpaRepository uses generics (), ensuring type safety for the entity (Word) and its ID type (String). + +5. Extensibility: You can easily add more custom methods as your application's requirements grow. diff --git a/backend/resources/springboot-for-5yo.md b/backend/resources/springboot-for-5yo.md new file mode 100644 index 000000000..37463525d --- /dev/null +++ b/backend/resources/springboot-for-5yo.md @@ -0,0 +1,41 @@ +# Spring Boot and MVC to a 5yo kid + +> Imagine a big restaurant called `Spring Boot`. + +Here's how it works: + +- The menu is like the `View`. It shows you all the yummy food you can order. + +- When you come in, you meet the maitre. They're like the `Front Controller`, welcoming you and guiding you to your table. + +- The waiter is like the `Controller`. They take your order and make sure you get what you wan. + +- Once the waiter has the order, our restaurant is so big that all the waiters are queuing to deliver the orders to the **kitchen**: it's where all the food is prepared. Our restaurant has a orders-board where the waiter boss pins the order, it is like the `Service`. + +- In the kitchen, there's a chef who's like `JPA`. They know all the recipes and how to make the dishes just right. + +- The cook is like `SQL queries.` They do the actual cooking, following the chef's instructions. + +- Each plate has a super-sercret code just for superheroes, this secret code is the `id` at `database`. + +- All the ingredients are kept in the pantry and fridge, which is like the `database`. + +- And finally, the plates and dishes are like the `Model`. They hold all the delicious food that comes to your table. + +- Imagine you want pizza at home. The `API Rest` is like a super-fast delivery superhero who brings your yummy food exactly where you want it! + +- What if you could watch chefs cooking? The `WebSocket` is like a magical window where you see everything happening in the kitchen, right when it's happening! + +- The `Security` is like a kind and strong firend who makes sure only nice people can enter and keeps all the secret recipes safe. + +- The `Thymeleaf Templates` and `Vaadin` create super cool, colorful menus that make you smile and want to try everything. + +- When you want the perfect meal, the `AI` is like a magic waiter who knows exactly what you like and suggests the most delicious food just for you! + +- Someone needs to make sure everything works perfectly. The `Actuator` is like the restaurant's superhero manager who watches over everything. + +- What if restaurants could help each other? The `Spring Cloud` is like a big friendly restaurant family that shares cool tricks and helps everyone. + +- Want to cook something amazing super fast? The `Spring Initializr` is like a magic kitchen that appears instantly, ready to make any delicious meal you want! + +All these parts work together to make sure you have a great meal at the Spring Boot restaurant!