cleaned up code format

This commit is contained in:
durn
2026-03-04 01:27:15 -07:00
parent 0a38aa3ded
commit 4bdb449f47
29 changed files with 865 additions and 822 deletions
@@ -21,50 +21,48 @@ import com.example.demo.service.RecipeService;
@RestController @RestController
@RequestMapping("/api/recipes") @RequestMapping("/api/recipes")
public class RecipeController { public class RecipeController {
private RecipeService recipeService; private RecipeService recipeService;
public RecipeController(RecipeService recipeService) { public RecipeController(RecipeService recipeService) {
super(); super();
this.recipeService = recipeService; this.recipeService = recipeService;
} }
//build create recipe REST API // build create recipe REST API
@PostMapping @PostMapping
public ResponseEntity<RecipeDto> saveUser(@RequestBody Recipe recipe){ public ResponseEntity<RecipeDto> saveUser(@RequestBody Recipe recipe) {
RecipeDto recipeDto = recipeService.convertToDto(recipe); RecipeDto recipeDto = recipeService.convertToDto(recipe);
return new ResponseEntity<RecipeDto>(recipeService.saveRecipe(recipeDto), HttpStatus.CREATED); return new ResponseEntity<RecipeDto>(recipeService.saveRecipe(recipeDto), HttpStatus.CREATED);
} }
//build get all recipes REST API // build get all recipes REST API
@GetMapping @GetMapping
public List<RecipeDto> getAllRecipes(){ public List<RecipeDto> getAllRecipes() {
return recipeService.getAllRecipes(); return recipeService.getAllRecipes();
} }
//build get recipe by id REST API // build get recipe by id REST API
// http://localhost:8080/api/recipes/(id number goes here) // http://localhost:8080/api/recipes/(id number goes here)
@GetMapping("{id}") @GetMapping("{id}")
public ResponseEntity<RecipeDto> getRecipeById(@PathVariable("id") Integer recipeId){ public ResponseEntity<RecipeDto> getRecipeById(@PathVariable("id") Integer recipeId) {
return new ResponseEntity<RecipeDto>(recipeService.getRecipeById(recipeId), HttpStatus.OK); return new ResponseEntity<RecipeDto>(recipeService.getRecipeById(recipeId), HttpStatus.OK);
} }
//build update recipe REST API // build update recipe REST API
//http://localhost:8080/api/recipes/(id number goes here) // http://localhost:8080/api/recipes/(id number goes here)
@PutMapping("{id}") @PutMapping("{id}")
public ResponseEntity<RecipeDto> updateUser(@PathVariable("id") Integer recipeId, @RequestBody Recipe recipe){ public ResponseEntity<RecipeDto> updateUser(@PathVariable("id") Integer recipeId, @RequestBody Recipe recipe) {
RecipeDto recipeDto = recipeService.convertToDto(recipe); RecipeDto recipeDto = recipeService.convertToDto(recipe);
return new ResponseEntity<RecipeDto>(recipeService.updateRecipe(recipeDto, recipeId), HttpStatus.OK); return new ResponseEntity<RecipeDto>(recipeService.updateRecipe(recipeDto, recipeId), HttpStatus.OK);
} }
//build delete recipe REST API // build delete recipe REST API
//http://localhost:8080/api/recipes/(id number goes here) // http://localhost:8080/api/recipes/(id number goes here)
@DeleteMapping("{id}") @DeleteMapping("{id}")
public ResponseEntity<String> deleteUser(@PathVariable("id") Integer recipeId){ public ResponseEntity<String> deleteUser(@PathVariable("id") Integer recipeId) {
recipeService.deleteRecipe(recipeId); recipeService.deleteRecipe(recipeId);
return new ResponseEntity<String>("Recipe deleted succesfully!", HttpStatus.OK); return new ResponseEntity<String>("Recipe deleted succesfully!", HttpStatus.OK);
} }
} }
@@ -20,63 +20,63 @@ import com.example.demo.service.UserService;
@RestController @RestController
@RequestMapping("/api/users") @RequestMapping("/api/users")
public class UserController { public class UserController {
private UserService userService; private UserService userService;
public UserController(UserService userService) { public UserController(UserService userService) {
super(); super();
this.userService = userService; this.userService = userService;
} }
//build create user REST API // build create user REST API
@PostMapping @PostMapping
public ResponseEntity<User> saveUser(@RequestBody User user){ public ResponseEntity<User> saveUser(@RequestBody User user) {
return new ResponseEntity<User>(userService.saveUser(user), HttpStatus.CREATED); return new ResponseEntity<User>(userService.saveUser(user), HttpStatus.CREATED);
} }
//build get all users REST API // build get all users REST API
@GetMapping @GetMapping
public List<UserDto> getAllUsers(){ public List<UserDto> getAllUsers() {
return userService.getAllUsers(); return userService.getAllUsers();
} }
//build get user by id REST API // build get user by id REST API
// http://localhost:8080/api/users/(id number goes here) // http://localhost:8080/api/users/(id number goes here)
@GetMapping("{id}") @GetMapping("{id}")
public ResponseEntity<UserDto> getUserById(@PathVariable("id") Integer userId){ public ResponseEntity<UserDto> getUserById(@PathVariable("id") Integer userId) {
return new ResponseEntity<UserDto>(userService.getUserById(userId), HttpStatus.OK); return new ResponseEntity<UserDto>(userService.getUserById(userId), HttpStatus.OK);
} }
//build create favorite REST API // build create favorite REST API
@PostMapping("/{userId}/favorites/{recipeId}") @PostMapping("/{userId}/favorites/{recipeId}")
public ResponseEntity<UserDto> saveFavorite( @PathVariable Integer userId, @PathVariable Integer recipeId) { public ResponseEntity<UserDto> saveFavorite(@PathVariable Integer userId, @PathVariable Integer recipeId) {
UserDto updatedUser = userService.saveFavorite(userId, recipeId); UserDto updatedUser = userService.saveFavorite(userId, recipeId);
return new ResponseEntity<>(updatedUser, HttpStatus.OK); return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} }
//build update user REST API // build update user REST API
// http://localhost:8080/api/users/(id number goes here) // http://localhost:8080/api/users/(id number goes here)
@PutMapping("{id}") @PutMapping("{id}")
public ResponseEntity<UserDto> updateUser(@PathVariable("id") Integer userId, @RequestBody User user){ public ResponseEntity<UserDto> updateUser(@PathVariable("id") Integer userId, @RequestBody User user) {
return new ResponseEntity<UserDto>(userService.updateUser(user, userId), HttpStatus.OK); return new ResponseEntity<UserDto>(userService.updateUser(user, userId), HttpStatus.OK);
} }
//build delete user REST API // build delete user REST API
@DeleteMapping("{id}") @DeleteMapping("{id}")
public ResponseEntity<String> deleteUser(@PathVariable("id") Integer userId){ public ResponseEntity<String> deleteUser(@PathVariable("id") Integer userId) {
userService.deleteUser(userId); userService.deleteUser(userId);
return new ResponseEntity<String>("User deleted succesfully!", HttpStatus.OK); return new ResponseEntity<String>("User deleted succesfully!", HttpStatus.OK);
} }
//build delete favorite REST API
@DeleteMapping("/{userId}/favorites/{recipeId}")
public ResponseEntity<String> deleteFavorite( @PathVariable Integer userId, @PathVariable Integer recipeId) {
userService.deleteFavorite(userId, recipeId); // build delete favorite REST API
return new ResponseEntity<String>("Favorite deleted succesfully!", HttpStatus.OK); @DeleteMapping("/{userId}/favorites/{recipeId}")
} public ResponseEntity<String> deleteFavorite(@PathVariable Integer userId, @PathVariable Integer recipeId) {
userService.deleteFavorite(userId, recipeId);
return new ResponseEntity<String>("Favorite deleted succesfully!", HttpStatus.OK);
}
} }
@@ -2,9 +2,7 @@ package com.example.demo.dto;
public class ImageDto { public class ImageDto {
String imageUrl; String imageUrl;
public ImageDto() { public ImageDto() {
super(); super();
} }
@@ -21,6 +19,5 @@ public class ImageDto {
public void setImageUrl(String imageUrl) { public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl; this.imageUrl = imageUrl;
} }
} }
@@ -5,27 +5,25 @@ import java.util.List;
import com.example.demo.entity.Recipe; import com.example.demo.entity.Recipe;
public class RecipeDto { public class RecipeDto {
private String title; private String title;
private String description; private String description;
private Integer prepTimeMinutes; private Integer prepTimeMinutes;
private Integer cookTimeMinutes; private Integer cookTimeMinutes;
private Integer servings; private Integer servings;
private UserDto userDto; private UserDto userDto;
private String status; private String status;
private List<RecipeIngredientDto> ingredients; private List<RecipeIngredientDto> ingredients;
private List<StepDto> steps; private List<StepDto> steps;
private List<ImageDto> images; private List<ImageDto> images;
private List<TagDto> tags; private List<TagDto> tags;
public RecipeDto() {
public RecipeDto() {
super(); super();
} }
public RecipeDto(String title, String description, Integer prepTimeMinutes, Integer cookTimeMinutes, public RecipeDto(String title, String description, Integer prepTimeMinutes, Integer cookTimeMinutes,
Integer servings, UserDto userDto, String status, List<RecipeIngredientDto> ingredients, List<StepDto> steps, List<ImageDto> images, List<TagDto> tags) { Integer servings, UserDto userDto, String status, List<RecipeIngredientDto> ingredients,
List<StepDto> steps, List<ImageDto> images, List<TagDto> tags) {
super(); super();
this.title = title; this.title = title;
this.description = description; this.description = description;
@@ -39,48 +37,61 @@ public class RecipeDto {
this.images = images; this.images = images;
this.tags = tags; this.tags = tags;
} }
// getters and setters // getters and setters
public String getTitle() { public String getTitle() {
return title; return title;
} }
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
public Integer getPrepTimeMinutes() { public Integer getPrepTimeMinutes() {
return prepTimeMinutes; return prepTimeMinutes;
} }
public void setPrepTimeMinutes(Integer prepTimeMinutes) { public void setPrepTimeMinutes(Integer prepTimeMinutes) {
this.prepTimeMinutes = prepTimeMinutes; this.prepTimeMinutes = prepTimeMinutes;
} }
public Integer getCookTimeMinutes() { public Integer getCookTimeMinutes() {
return cookTimeMinutes; return cookTimeMinutes;
} }
public void setCookTimeMinutes(Integer cookTimeMinutes) { public void setCookTimeMinutes(Integer cookTimeMinutes) {
this.cookTimeMinutes = cookTimeMinutes; this.cookTimeMinutes = cookTimeMinutes;
} }
public Integer getServings() { public Integer getServings() {
return servings; return servings;
} }
public void setServings(Integer servings) { public void setServings(Integer servings) {
this.servings = servings; this.servings = servings;
} }
public String getStatus() { public String getStatus() {
return status; return status;
} }
public void setStatus(String status) { public void setStatus(String status) {
this.status = status; this.status = status;
} }
public List<RecipeIngredientDto> getIngredients() { public List<RecipeIngredientDto> getIngredients() {
return ingredients; return ingredients;
} }
public void setIngredients(List<RecipeIngredientDto> ingredients) { public void setIngredients(List<RecipeIngredientDto> ingredients) {
this.ingredients = ingredients; this.ingredients = ingredients;
} }
@@ -92,7 +103,6 @@ public class RecipeDto {
public void setSteps(List<StepDto> steps) { public void setSteps(List<StepDto> steps) {
this.steps = steps; this.steps = steps;
} }
public List<ImageDto> getImages() { public List<ImageDto> getImages() {
return images; return images;
@@ -101,7 +111,6 @@ public class RecipeDto {
public void setImages(List<ImageDto> images) { public void setImages(List<ImageDto> images) {
this.images = images; this.images = images;
} }
public List<TagDto> getTags() { public List<TagDto> getTags() {
return tags; return tags;
@@ -118,6 +127,5 @@ public class RecipeDto {
public void setUserDto(UserDto userDto) { public void setUserDto(UserDto userDto) {
this.userDto = userDto; this.userDto = userDto;
} }
} }
@@ -3,18 +3,14 @@ package com.example.demo.dto;
import java.math.BigDecimal; import java.math.BigDecimal;
public class RecipeIngredientDto { public class RecipeIngredientDto {
private String ingredientName; private String ingredientName;
private BigDecimal quantity; private BigDecimal quantity;
private String unit; private String unit;
private String notes; private String notes;
public RecipeIngredientDto() {
public RecipeIngredientDto() { super();
super(); }
}
public RecipeIngredientDto(String ingredientName, BigDecimal quantity, String unit, String notes) { public RecipeIngredientDto(String ingredientName, BigDecimal quantity, String unit, String notes) {
super(); super();
@@ -23,31 +19,38 @@ public class RecipeIngredientDto {
this.unit = unit; this.unit = unit;
this.notes = notes; this.notes = notes;
} }
// getters and setters // getters and setters
public String getIngredientName() { public String getIngredientName() {
return ingredientName; return ingredientName;
} }
public void setIngredientName(String ingredientName) { public void setIngredientName(String ingredientName) {
this.ingredientName = ingredientName; this.ingredientName = ingredientName;
} }
public BigDecimal getQuantity() { public BigDecimal getQuantity() {
return quantity; return quantity;
} }
public void setQuantity(BigDecimal quantity) { public void setQuantity(BigDecimal quantity) {
this.quantity = quantity; this.quantity = quantity;
} }
public String getUnit() { public String getUnit() {
return unit; return unit;
} }
public void setUnit(String unit) { public void setUnit(String unit) {
this.unit = unit; this.unit = unit;
} }
public String getNotes() { public String getNotes() {
return notes; return notes;
} }
public void setNotes(String notes) { public void setNotes(String notes) {
this.notes = notes; this.notes = notes;
} }
} }
@@ -1,29 +1,30 @@
package com.example.demo.dto; package com.example.demo.dto;
public class StepDto { public class StepDto {
private Integer stepNumber; private Integer stepNumber;
private String instruction; private String instruction;
public StepDto() {} public StepDto() {
}
public StepDto(Integer stepNumber, String instruction) { public StepDto(Integer stepNumber, String instruction) {
this.stepNumber = stepNumber; this.stepNumber = stepNumber;
this.instruction = instruction; this.instruction = instruction;
} }
public Integer getStepNumber() { public Integer getStepNumber() {
return stepNumber; return stepNumber;
} }
public void setStepNumber(Integer stepNumber) { public void setStepNumber(Integer stepNumber) {
this.stepNumber = stepNumber; this.stepNumber = stepNumber;
} }
public String getInstruction() { public String getInstruction() {
return instruction; return instruction;
} }
public void setInstruction(String instruction) { public void setInstruction(String instruction) {
this.instruction = instruction; this.instruction = instruction;
} }
} }
@@ -1,28 +1,22 @@
package com.example.demo.dto; package com.example.demo.dto;
public class TagDto { public class TagDto {
private String name; private String name;
public TagDto() { public TagDto() {
super(); super();
} }
public TagDto(String name) { public TagDto(String name) {
super(); super();
this.name = name; this.name = name;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
} }
@@ -1,25 +1,26 @@
package com.example.demo.dto; package com.example.demo.dto;
public class UserDto { public class UserDto {
private Integer id; private Integer id;
private String username; private String username;
private String email; private String email;
public UserDto() {} public UserDto() {
}
public UserDto(Integer id, String username, String email) { public UserDto(Integer id, String username, String email) {
this.id = id; this.id = id;
this.username = username; this.username = username;
this.email = email; this.email = email;
} }
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public String getUsername() { public String getUsername() {
return username; return username;
@@ -36,6 +37,5 @@ public class UserDto {
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
} }
@@ -6,37 +6,43 @@ import lombok.EqualsAndHashCode;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@Entity @Entity
@Table(name = "recipe_images") // keep table name the same @Table(name = "recipe_images")
public class Image { public class Image {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "recipe_id", nullable = false) @JoinColumn(name = "recipe_id", nullable = false)
@EqualsAndHashCode.Include @EqualsAndHashCode.Include
private Recipe recipe; private Recipe recipe;
@Column(name = "image_url", nullable = false) @Column(name = "image_url", nullable = false)
private String imageUrl; private String imageUrl;
@Column(name = "created_at") @Column(name = "created_at")
private LocalDateTime createdAt; private LocalDateTime createdAt;
public Image() {} public Image() {
}
public Image(Recipe recipe, String imageUrl) { public Image(Recipe recipe, String imageUrl) {
this.recipe = recipe; this.recipe = recipe;
this.imageUrl = imageUrl; this.imageUrl = imageUrl;
this.createdAt = LocalDateTime.now(); this.createdAt = LocalDateTime.now();
} }
// Getters and setters // Getters and setters
public Integer getId() { return id; } public Integer getId() {
public void setId(Integer id) { this.id = id; } return id;
}
public Recipe getRecipe() { public void setId(Integer id) {
this.id = id;
}
public Recipe getRecipe() {
return recipe; return recipe;
} }
@@ -44,9 +50,19 @@ public class Image {
this.recipe = recipe; this.recipe = recipe;
} }
public String getImageUrl() { return imageUrl; } public String getImageUrl() {
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } return imageUrl;
}
public LocalDateTime getCreatedAt() { return createdAt; } public void setImageUrl(String imageUrl) {
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } this.imageUrl = imageUrl;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
} }
@@ -16,38 +16,44 @@ import jakarta.persistence.CascadeType;
import jakarta.persistence.Column; import jakarta.persistence.Column;
@Entity @Entity
@Table(name = "ingredients", uniqueConstraints = { @Table(name = "ingredients", uniqueConstraints = { @UniqueConstraint(columnNames = "name") })
@UniqueConstraint(columnNames = "name")
})
public class Ingredient { public class Ingredient {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@Column(nullable = false, unique = true) @Column(nullable = false, unique = true)
private String name; private String name;
@OneToMany(mappedBy = "ingredient")
private Set<RecipeIngredient> recipeIngredients = new HashSet<>();
// Default constructor required by JPA @OneToMany(mappedBy = "ingredient")
public Ingredient() {} private Set<RecipeIngredient> recipeIngredients = new HashSet<>();
// Convenience constructor public Ingredient() {
public Ingredient(String name) { }
this.name = name;
}
// Getters and setters public Ingredient(String name) {
public Integer getId() { return id; } this.name = name;
public void setId(Integer id) { this.id = id; } }
public String getName() { return name; } // Getters and setters
public void setName(String name) { this.name = name; } public Integer getId() {
return id;
public Set<RecipeIngredient> getRecipeIngredients() { }
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<RecipeIngredient> getRecipeIngredients() {
return recipeIngredients; return recipeIngredients;
} }
@@ -1,6 +1,7 @@
package com.example.demo.entity; package com.example.demo.entity;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import java.math.BigDecimal; import java.math.BigDecimal;
@@ -12,101 +13,78 @@ import java.util.Set;
@Table(name = "recipes") @Table(name = "recipes")
public class Recipe { public class Recipe {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
private String title; @NotBlank(message = "Please provide a recipe title")
private String title;
@Column(columnDefinition = "TEXT") @Column(columnDefinition = "TEXT")
private String description; private String description;
private Integer prepTimeMinutes; private Integer prepTimeMinutes;
private Integer cookTimeMinutes; private Integer cookTimeMinutes;
private Integer servings; private Integer servings;
private String status; private String status;
private LocalDateTime createdAt; private LocalDateTime createdAt;
private LocalDateTime updatedAt; private LocalDateTime updatedAt;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
@EqualsAndHashCode.Include
private User user;
// Recipe ingredients relationship
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<RecipeIngredient> recipeIngredients = new HashSet<>();
// Recipe Steps relationship
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<Step> steps = new HashSet<>();
// Recipe Images relationship
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<Image> images = new HashSet<>();
// Recipe Tag relationship and also junction table
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "recipe_tags",
joinColumns = {@JoinColumn(name = "recipe_id")},
inverseJoinColumns = {@JoinColumn(name = "tag_id")})
private Set<Tag> tags = new HashSet<>();
// User is the manager for this relationship
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "FavRecipes")
private Set<User> users = new HashSet<>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
@EqualsAndHashCode.Include
private User user;
// Default constructor // Recipe ingredients relationship
public Recipe() {} @OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<RecipeIngredient> recipeIngredients = new HashSet<>();
// Convenience constructor // Recipe Steps relationship
public Recipe(String title, String description, Integer prepTimeMinutes, Integer cookTimeMinutes, @OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
Integer servings, User user, String status) { private Set<Step> steps = new HashSet<>();
this.title = title;
this.description = description;
this.prepTimeMinutes = prepTimeMinutes;
this.cookTimeMinutes = cookTimeMinutes;
this.servings = servings;
this.user = user;
this.status = status;
this.createdAt = LocalDateTime.now();
this.updatedAt = LocalDateTime.now();
}
// Helper method to add an ingredient // Recipe Images relationship
public void addIngredient(Ingredient ingredient, BigDecimal quantity, String unit, String notes) { @OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
RecipeIngredient recipeIngredient = new RecipeIngredient(this, ingredient, quantity, unit, notes); private Set<Image> images = new HashSet<>();
recipeIngredients.add(recipeIngredient);
ingredient.getRecipeIngredients().add(recipeIngredient);
}
public void removeIngredient(Ingredient ingredient) {
RecipeIngredient remove = null;
for (RecipeIngredient recipeIngredient : recipeIngredients) {
if (recipeIngredient.getIngredient().equals(ingredient)) {
remove = recipeIngredient;
break;
}
}
if (remove != null) {
recipeIngredients.remove(remove);
ingredient.getRecipeIngredients().remove(remove);
remove.setRecipe(null);
remove.setIngredient(null);
}
}
// Recipe Tag relationship and also junction table
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "recipe_tags", joinColumns = { @JoinColumn(name = "recipe_id") }, inverseJoinColumns = {
@JoinColumn(name = "tag_id") })
private Set<Tag> tags = new HashSet<>();
// Getters and setters // User is the manager for this relationship
public Integer getId() { return id; } @ManyToMany(fetch = FetchType.LAZY, mappedBy = "FavRecipes")
public void setId(Integer id) { this.id = id; } private Set<User> users = new HashSet<>();
public User getUser() { public Recipe() {
}
public Recipe(String title, String description, Integer prepTimeMinutes, Integer cookTimeMinutes, Integer servings,
User user, String status) {
this.title = title;
this.description = description;
this.prepTimeMinutes = prepTimeMinutes;
this.cookTimeMinutes = cookTimeMinutes;
this.servings = servings;
this.user = user;
this.status = status;
this.createdAt = LocalDateTime.now();
this.updatedAt = LocalDateTime.now();
}
// Getters and setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return user; return user;
} }
@@ -114,33 +92,77 @@ public class Recipe {
this.user = user; this.user = user;
} }
public String getTitle() { return title; } public String getTitle() {
public void setTitle(String title) { this.title = title; } return title;
}
public String getDescription() { return description; } public void setTitle(String title) {
public void setDescription(String description) { this.description = description; } this.title = title;
}
public Integer getPrepTimeMinutes() { return prepTimeMinutes; } public String getDescription() {
public void setPrepTimeMinutes(Integer prepTimeMinutes) { this.prepTimeMinutes = prepTimeMinutes; } return description;
}
public Integer getCookTimeMinutes() { return cookTimeMinutes; } public void setDescription(String description) {
public void setCookTimeMinutes(Integer cookTimeMinutes) { this.cookTimeMinutes = cookTimeMinutes; } this.description = description;
}
public Integer getServings() { return servings; } public Integer getPrepTimeMinutes() {
public void setServings(Integer servings) { this.servings = servings; } return prepTimeMinutes;
}
public String getStatus() { return status; } public void setPrepTimeMinutes(Integer prepTimeMinutes) {
public void setStatus(String status) { this.status = status; } this.prepTimeMinutes = prepTimeMinutes;
}
public LocalDateTime getCreatedAt() { return createdAt; } public Integer getCookTimeMinutes() {
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } return cookTimeMinutes;
}
public LocalDateTime getUpdatedAt() { return updatedAt; } public void setCookTimeMinutes(Integer cookTimeMinutes) {
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } this.cookTimeMinutes = cookTimeMinutes;
}
public Set<RecipeIngredient> getRecipeIngredients() { return recipeIngredients; } public Integer getServings() {
public void setRecipeIngredients(Set<RecipeIngredient> recipeIngredients) { this.recipeIngredients = recipeIngredients; } return servings;
}
public void setServings(Integer servings) {
this.servings = servings;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public Set<RecipeIngredient> getRecipeIngredients() {
return recipeIngredients;
}
public void setRecipeIngredients(Set<RecipeIngredient> recipeIngredients) {
this.recipeIngredients = recipeIngredients;
}
public Set<Step> getSteps() { public Set<Step> getSteps() {
return steps; return steps;
@@ -173,7 +195,4 @@ public class Recipe {
public void setUsers(Set<User> users) { public void setUsers(Set<User> users) {
this.users = users; this.users = users;
} }
} }
@@ -5,59 +5,88 @@ import java.math.BigDecimal;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
@Entity @Entity
@Table(name = "recipe_ingredient_junction", @Table(name = "recipe_ingredient_junction", uniqueConstraints = {
uniqueConstraints = {@UniqueConstraint(columnNames = {"recipe_id", "ingredient_id"})}) @UniqueConstraint(columnNames = { "recipe_id", "ingredient_id" }) })
@EqualsAndHashCode( @EqualsAndHashCode(onlyExplicitlyIncluded = true)
onlyExplicitlyIncluded = true
)
public class RecipeIngredient { public class RecipeIngredient {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "recipe_id", nullable = false) @JoinColumn(name = "recipe_id", nullable = false)
@EqualsAndHashCode.Include @EqualsAndHashCode.Include
private Recipe recipe; private Recipe recipe;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ingredient_id", nullable = false) @JoinColumn(name = "ingredient_id", nullable = false)
@EqualsAndHashCode.Include @EqualsAndHashCode.Include
private Ingredient ingredient; private Ingredient ingredient;
private BigDecimal quantity; private BigDecimal quantity;
private String unit; private String unit;
private String notes; private String notes;
public RecipeIngredient() {} public RecipeIngredient() {
}
public RecipeIngredient(Recipe recipe, Ingredient ingredient, BigDecimal quantity, String unit, String notes) { public RecipeIngredient(Recipe recipe, Ingredient ingredient, BigDecimal quantity, String unit, String notes) {
this.recipe = recipe; this.recipe = recipe;
this.ingredient = ingredient; this.ingredient = ingredient;
this.quantity = quantity; this.quantity = quantity;
this.unit = unit; this.unit = unit;
this.notes = notes; this.notes = notes;
} }
// Getters and setters // Getters and setters
public Integer getId() { return id; } public Integer getId() {
public void setId(Integer id) { this.id = id; } return id;
}
public Recipe getRecipe() { return recipe; } public void setId(Integer id) {
public void setRecipe(Recipe recipe) { this.recipe = recipe; } this.id = id;
}
public Ingredient getIngredient() { return ingredient; } public Recipe getRecipe() {
public void setIngredient(Ingredient ingredient) { this.ingredient = ingredient; } return recipe;
}
public BigDecimal getQuantity() { return quantity; } public void setRecipe(Recipe recipe) {
public void setQuantity(BigDecimal quantity) { this.quantity = quantity; } this.recipe = recipe;
}
public String getUnit() { return unit; } public Ingredient getIngredient() {
public void setUnit(String unit) { this.unit = unit; } return ingredient;
}
public String getNotes() { return notes; } public void setIngredient(Ingredient ingredient) {
public void setNotes(String notes) { this.notes = notes; } this.ingredient = ingredient;
}
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
} }
@@ -8,49 +8,50 @@ import java.util.Objects;
@Embeddable @Embeddable
public class RecipeTagId implements Serializable { public class RecipeTagId implements Serializable {
private static final long serialVersionUID = 5272431101708393749L; private static final long serialVersionUID = 5272431101708393749L;
@Column(name = "recipe_id") @Column(name = "recipe_id")
private Integer recipeId; private Integer recipeId;
@Column(name = "tag_id") @Column(name = "tag_id")
private Integer tagId; private Integer tagId;
public RecipeTagId() {} public RecipeTagId() {
}
public RecipeTagId(Integer recipeId, Integer tagId) { public RecipeTagId(Integer recipeId, Integer tagId) {
this.recipeId = recipeId; this.recipeId = recipeId;
this.tagId = tagId; this.tagId = tagId;
} }
public Integer getRecipeId() { public Integer getRecipeId() {
return recipeId; return recipeId;
} }
public void setRecipeId(Integer recipeId) { public void setRecipeId(Integer recipeId) {
this.recipeId = recipeId; this.recipeId = recipeId;
} }
public Integer getTagId() { public Integer getTagId() {
return tagId; return tagId;
} }
public void setTagId(Integer tagId) { public void setTagId(Integer tagId) {
this.tagId = tagId; this.tagId = tagId;
} }
// REQUIRED for composite keys @Override
@Override public boolean equals(Object o) {
public boolean equals(Object o) { if (this == o)
if (this == o) return true; return true;
if (!(o instanceof RecipeTagId)) return false; if (!(o instanceof RecipeTagId))
RecipeTagId that = (RecipeTagId) o; return false;
return Objects.equals(recipeId, that.recipeId) && RecipeTagId that = (RecipeTagId) o;
Objects.equals(tagId, that.tagId); return Objects.equals(recipeId, that.recipeId) && Objects.equals(tagId, that.tagId);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(recipeId, tagId); return Objects.hash(recipeId, tagId);
} }
} }
@@ -7,34 +7,40 @@ import lombok.EqualsAndHashCode;
@Table(name = "steps") @Table(name = "steps")
public class Step { public class Step {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@Column(name = "step_number", nullable = false) @Column(name = "step_number", nullable = false)
private Integer stepNumber; private Integer stepNumber;
@Column(name = "instruction", nullable = false, columnDefinition = "TEXT") @Column(name = "instruction", nullable = false, columnDefinition = "TEXT")
private String instruction; private String instruction;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "recipe_id", nullable = false) @JoinColumn(name = "recipe_id", nullable = false)
@EqualsAndHashCode.Include @EqualsAndHashCode.Include
private Recipe recipe; private Recipe recipe;
public Step() {}
public Step(Recipe recipe, Integer stepNumber, String instruction) { public Step() {
this.recipe = recipe; }
this.stepNumber = stepNumber;
this.instruction = instruction;
}
// Getters and setters public Step(Recipe recipe, Integer stepNumber, String instruction) {
public Integer getId() { return id; } this.recipe = recipe;
public void setId(Integer id) { this.id = id; } this.stepNumber = stepNumber;
this.instruction = instruction;
}
public Recipe getRecipe() { // Getters and setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Recipe getRecipe() {
return recipe; return recipe;
} }
@@ -42,9 +48,19 @@ public class Step {
this.recipe = recipe; this.recipe = recipe;
} }
public Integer getStepNumber() { return stepNumber; } public Integer getStepNumber() {
public void setStepNumber(Integer stepNumber) { this.stepNumber = stepNumber; } return stepNumber;
}
public String getInstruction() { return instruction; } public void setStepNumber(Integer stepNumber) {
public void setInstruction(String instruction) { this.instruction = instruction; } this.stepNumber = stepNumber;
}
public String getInstruction() {
return instruction;
}
public void setInstruction(String instruction) {
this.instruction = instruction;
}
} }
@@ -9,40 +9,40 @@ import jakarta.persistence.*;
@Table(name = "tags") @Table(name = "tags")
public class Tag { public class Tag {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@Column(nullable = false, unique = true) @Column(nullable = false, unique = true)
private String name; private String name;
// Recipe is the manager for this relationship
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "tags")
private Set<Recipe> recipes = new HashSet<>();
// Required by JPA // Recipe is the manager for this relationship
public Tag() {} @ManyToMany(fetch = FetchType.LAZY, mappedBy = "tags")
private Set<Recipe> recipes = new HashSet<>();
public Tag(String name) { public Tag() {
this.name = name; }
}
// Getters and setters public Tag(String name) {
public Integer getId() { this.name = name;
return id; }
}
public void setId(Integer id) { // Getters and setters
this.id = id; public Integer getId() {
} return id;
}
public String getName() { public void setId(Integer id) {
return name; this.id = id;
} }
public void setName(String name) { public String getName() {
this.name = name; return name;
} }
public void setName(String name) {
this.name = name;
}
public Set<Recipe> getRecipes() { public Set<Recipe> getRecipes() {
return recipes; return recipes;
@@ -51,6 +51,5 @@ public class Tag {
public void setRecipes(Set<Recipe> recipes) { public void setRecipes(Set<Recipe> recipes) {
this.recipes = recipes; this.recipes = recipes;
} }
} }
@@ -20,63 +20,91 @@ import java.util.Set;
@Table(name = "users") @Table(name = "users")
public class User { public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@Column(nullable = false, unique = true) @Column(nullable = false, unique = true)
private String username; private String username;
private String role; private String role;
@Column(unique = true) @Column(unique = true)
private String email; private String email;
private String hashedpassword; private String hashedpassword;
@Column(name = "created_at") @Column(name = "created_at")
private LocalDateTime createdAt; private LocalDateTime createdAt;
// User Recipe relationship
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<Recipe> recipes = new HashSet<>();
// Favorite relationship and also junction table
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "favorites",
joinColumns = {@JoinColumn(name = "userId")},
inverseJoinColumns = {@JoinColumn(name = "recipeId")})
private Set<Recipe> FavRecipes = new HashSet<>();
// Constructors // User Recipe relationship
public User() {} @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<Recipe> recipes = new HashSet<>();
public User(String username, String role, String email, String hashedpassword, LocalDateTime createdAt) { // Favorite relationship and also junction table
this.username = username; @ManyToMany(fetch = FetchType.LAZY)
this.role = role; @JoinTable(name = "favorites", joinColumns = { @JoinColumn(name = "userId") }, inverseJoinColumns = {
this.email = email; @JoinColumn(name = "recipeId") })
this.hashedpassword = hashedpassword; private Set<Recipe> FavRecipes = new HashSet<>();
this.createdAt = createdAt;
}
public User() {
public Integer getId() { return id; } }
public void setId(Integer id) { this.id = id; }
public String getUsername() { return username; } public User(String username, String role, String email, String hashedpassword, LocalDateTime createdAt) {
public void setUsername(String username) { this.username = username; } this.username = username;
this.role = role;
this.email = email;
this.hashedpassword = hashedpassword;
this.createdAt = createdAt;
}
public String getRole() { return role; } public Integer getId() {
public void setRole(String role) { this.role = role; } return id;
}
public String getEmail() { return email; } public void setId(Integer id) {
public void setEmail(String email) { this.email = email; } this.id = id;
}
public String getHashedpassword() { return hashedpassword; } public String getUsername() {
public void setHashedpassword(String hashedpassword) { this.hashedpassword = hashedpassword; } return username;
}
public LocalDateTime getCreatedAt() { return createdAt; } public void setUsername(String username) {
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } this.username = username;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHashedpassword() {
return hashedpassword;
}
public void setHashedpassword(String hashedpassword) {
this.hashedpassword = hashedpassword;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public Set<Recipe> getFavRecipes() { public Set<Recipe> getFavRecipes() {
return FavRecipes; return FavRecipes;
@@ -85,6 +113,5 @@ public class User {
public void setFavRecipes(Set<Recipe> favRecipes) { public void setFavRecipes(Set<Recipe> favRecipes) {
FavRecipes = favRecipes; FavRecipes = favRecipes;
} }
} }
@@ -3,14 +3,14 @@ package com.example.demo.exception;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus (value = HttpStatus.NOT_FOUND) @ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{ public class NotFoundException extends RuntimeException {
private static final long serialVersionUID = 1l; private static final long serialVersionUID = 1l;
private String resourceName; private String resourceName;
private String fieldName; private String fieldName;
private Object fieldValue; private Object fieldValue;
public NotFoundException(String resourceName, String fieldName, Object fieldValue) { public NotFoundException(String resourceName, String fieldName, Object fieldValue) {
super(String.format("%s not found with %s : %s", resourceName, fieldName, fieldValue)); super(String.format("%s not found with %s : %s", resourceName, fieldName, fieldValue));
this.resourceName = resourceName; this.resourceName = resourceName;
@@ -26,7 +26,6 @@ public class NotFoundException extends RuntimeException{
return fieldName; return fieldName;
} }
public Object getFieldValue() { public Object getFieldValue() {
return fieldValue; return fieldValue;
} }
@@ -7,5 +7,5 @@ import com.example.demo.entity.FavoriteId;
import java.util.List; import java.util.List;
public interface FavoriteRepo extends JpaRepository<Favorite, FavoriteId> { public interface FavoriteRepo extends JpaRepository<Favorite, FavoriteId> {
} }
@@ -5,7 +5,6 @@ import com.example.demo.entity.Image;
import java.util.List; import java.util.List;
public interface ImageRepo extends JpaRepository<Image, Integer> { public interface ImageRepo extends JpaRepository<Image, Integer> {
} }
@@ -5,7 +5,6 @@ import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.Ingredient; import com.example.demo.entity.Ingredient;
public interface IngredientRepo extends JpaRepository<Ingredient, Integer> { public interface IngredientRepo extends JpaRepository<Ingredient, Integer> {
Optional<Ingredient> findByName(String name); Optional<Ingredient> findByName(String name);
} }
@@ -6,6 +6,6 @@ import com.example.demo.entity.Recipe;
import com.example.demo.entity.RecipeIngredient; import com.example.demo.entity.RecipeIngredient;
public interface RecipeIngredientRepo extends JpaRepository<RecipeIngredient, Integer> { public interface RecipeIngredientRepo extends JpaRepository<RecipeIngredient, Integer> {
// Custom query: find all ingredients for a recipe // Custom query: find all ingredients for a recipe
void deleteByRecipe(Recipe recipe); void deleteByRecipe(Recipe recipe);
} }
@@ -3,7 +3,6 @@ package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.Recipe; import com.example.demo.entity.Recipe;
public interface RecipeRepo extends JpaRepository<Recipe, Integer> { public interface RecipeRepo extends JpaRepository<Recipe, Integer> {
} }
@@ -1,6 +1,5 @@
package com.example.demo.repository; package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.RecipeTag; import com.example.demo.entity.RecipeTag;
import com.example.demo.entity.RecipeTagId; import com.example.demo.entity.RecipeTagId;
@@ -8,5 +8,4 @@ import java.util.List;
public interface StepRepo extends JpaRepository<Step, Integer> { public interface StepRepo extends JpaRepository<Step, Integer> {
} }
@@ -5,5 +5,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.User; import com.example.demo.entity.User;
public interface UserRepo extends JpaRepository<User, Integer> { public interface UserRepo extends JpaRepository<User, Integer> {
} }
@@ -31,18 +31,19 @@ import com.example.demo.service.RecipeService;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
@Service @Service
public class RecipeServiceImpl implements RecipeService{ public class RecipeServiceImpl implements RecipeService {
private RecipeRepo recipeRepository;
private RecipeRepo recipeRepository; private IngredientRepo ingredientRepository;
private IngredientRepo ingredientRepository; private RecipeIngredientRepo recipeIngredientRepository;
private RecipeIngredientRepo recipeIngredientRepository; private UserRepo userRepository;
private UserRepo userRepository; private StepRepo stepRepository;
private StepRepo stepRepository; private ImageRepo imageRepository;
private ImageRepo imageRepository; private TagRepo tagRepository;
private TagRepo tagRepository;
public RecipeServiceImpl(RecipeRepo recipeRepository, IngredientRepo ingredientRepository,
public RecipeServiceImpl(RecipeRepo recipeRepository, IngredientRepo ingredientRepository, RecipeIngredientRepo recipeIngredientRepository, UserRepo userRepository, StepRepo stepRepository, ImageRepo imageRepository, TagRepo tagRepository) { RecipeIngredientRepo recipeIngredientRepository, UserRepo userRepository, StepRepo stepRepository,
ImageRepo imageRepository, TagRepo tagRepository) {
super(); super();
this.recipeRepository = recipeRepository; this.recipeRepository = recipeRepository;
this.ingredientRepository = ingredientRepository; this.ingredientRepository = ingredientRepository;
@@ -52,335 +53,267 @@ private TagRepo tagRepository;
this.imageRepository = imageRepository; this.imageRepository = imageRepository;
this.tagRepository = tagRepository; this.tagRepository = tagRepository;
} }
public RecipeDto convertToDto(Recipe recipe) { public RecipeDto convertToDto(Recipe recipe) {
List<RecipeIngredientDto> ingredientDtos = recipe.getRecipeIngredients().stream() List<RecipeIngredientDto> ingredientDtos = recipe.getRecipeIngredients().stream()
.map(ri -> new RecipeIngredientDto( .map(ri -> new RecipeIngredientDto(ri.getIngredient().getName(), ri.getQuantity(), ri.getUnit(),
ri.getIngredient().getName(), ri.getNotes()))
ri.getQuantity(), .toList();
ri.getUnit(),
ri.getNotes() List<StepDto> stepDtos = recipe.getSteps().stream()
)) .map(ri -> new StepDto(ri.getStepNumber(), ri.getInstruction())).toList();
.toList();
List<ImageDto> imageDtos = recipe.getImages().stream().map(ri -> new ImageDto(ri.getImageUrl())).toList();
List<StepDto> stepDtos = recipe.getSteps().stream()
.map(ri -> new StepDto( List<TagDto> tagDtos = recipe.getTags().stream().map(ri -> new TagDto(ri.getName())).toList();
ri.getStepNumber(),
ri.getInstruction() UserDto userDto = new UserDto(recipe.getUser().getId(), recipe.getUser().getUsername(),
)) recipe.getUser().getEmail());
.toList();
return new RecipeDto(recipe.getTitle(), recipe.getDescription(), recipe.getPrepTimeMinutes(),
List<ImageDto> imageDtos = recipe.getImages().stream() recipe.getCookTimeMinutes(), recipe.getServings(), userDto, recipe.getStatus(), ingredientDtos,
.map(ri -> new ImageDto( stepDtos, imageDtos, tagDtos);
ri.getImageUrl()
))
.toList();
List<TagDto> tagDtos = recipe.getTags().stream()
.map(ri -> new TagDto(
ri.getName()
))
.toList();
UserDto userDto = new UserDto(recipe.getUser().getId(), recipe.getUser().getUsername(), recipe.getUser().getEmail());
return new RecipeDto(
recipe.getTitle(),
recipe.getDescription(),
recipe.getPrepTimeMinutes(),
recipe.getCookTimeMinutes(),
recipe.getServings(),
userDto,
recipe.getStatus(),
ingredientDtos,
stepDtos,
imageDtos,
tagDtos
);
} }
@Override @Override
public RecipeDto saveRecipe(RecipeDto dto) { public RecipeDto saveRecipe(RecipeDto dto) {
User user = userRepository.findById(dto.getUserDto().getId()) User user = userRepository.findById(dto.getUserDto().getId())
.orElseThrow(() -> new NotFoundException("User", "id", dto.getUserDto().getId())); .orElseThrow(() -> new NotFoundException("User", "id", dto.getUserDto().getId()));
Recipe recipe = new Recipe( Recipe recipe = new Recipe(dto.getTitle(), dto.getDescription(), dto.getPrepTimeMinutes(),
dto.getTitle(), dto.getCookTimeMinutes(), dto.getServings(), user, dto.getStatus());
dto.getDescription(),
dto.getPrepTimeMinutes(),
dto.getCookTimeMinutes(),
dto.getServings(),
user,
dto.getStatus()
);
for (RecipeIngredientDto riDto : dto.getIngredients()) {
for (RecipeIngredientDto riDto : dto.getIngredients()) {
Ingredient ingredient = ingredientRepository.findByName(riDto.getIngredientName())
Ingredient ingredient = ingredientRepository.findByName(riDto.getIngredientName()) .orElseGet(() -> new Ingredient(riDto.getIngredientName()));
.orElseGet(() -> new Ingredient(riDto.getIngredientName()));
if (ingredient.getId() == null) {
if (ingredient.getId() == null) { ingredientRepository.save(ingredient);
ingredientRepository.save(ingredient); }
}
RecipeIngredient ri = new RecipeIngredient( RecipeIngredient ri = new RecipeIngredient(recipe, ingredient, riDto.getQuantity(), riDto.getUnit(),
recipe, riDto.getNotes());
ingredient,
riDto.getQuantity(),
riDto.getUnit(),
riDto.getNotes()
);
recipe.getRecipeIngredients().add(ri); recipe.getRecipeIngredients().add(ri);
} }
if (dto.getSteps() != null) {
for (StepDto stepDto : dto.getSteps()) {
Step step = new Step(recipe, stepDto.getStepNumber(), stepDto.getInstruction());
recipe.getSteps().add(step);
}
}
if (dto.getImages() != null) {
for (ImageDto imageDto : dto.getImages()) {
Image image = new Image(recipe, imageDto.getImageUrl());
recipe.getImages().add(image);
}
}
// if (dto.getTags() != null) {
// for (TagDto tagDto : dto.getTags()) {
// Tag tag = new Tag(tagDto.getName());
// tagRepository.save(tag);
// recipe.getTags().add(tag);
// }
// }
for (TagDto tDto : dto.getTags()) {
if (dto.getSteps() != null) {
Tag tag = tagRepository.findByName(tDto.getName()) for (StepDto stepDto : dto.getSteps()) {
.orElseGet(() -> new Tag(tDto.getName())); Step step = new Step(recipe, stepDto.getStepNumber(), stepDto.getInstruction());
recipe.getSteps().add(step);
}
}
if (dto.getImages() != null) {
if (tag.getId() == null) { for (ImageDto imageDto : dto.getImages()) {
tagRepository.save(tag); Image image = new Image(recipe, imageDto.getImageUrl());
} recipe.getImages().add(image);
recipe.getTags().add(tag); }
} }
Recipe saved = recipeRepository.save(recipe); for (TagDto tDto : dto.getTags()) {
return convertToDto(saved); Tag tag = tagRepository.findByName(tDto.getName()).orElseGet(() -> new Tag(tDto.getName()));
}
if (tag.getId() == null) {
tagRepository.save(tag);
}
recipe.getTags().add(tag);
}
Recipe saved = recipeRepository.save(recipe);
return convertToDto(saved);
}
@Override @Override
@Transactional @Transactional
public List<RecipeDto> getAllRecipes() { public List<RecipeDto> getAllRecipes() {
List<RecipeDto> list = new ArrayList<>(); List<RecipeDto> list = new ArrayList<>();
for (Recipe recipe : recipeRepository.findAll()) { for (Recipe recipe : recipeRepository.findAll()) {
RecipeDto recipeDto = convertToDto(recipe); RecipeDto recipeDto = convertToDto(recipe);
list.add(recipeDto); list.add(recipeDto);
} }
return list; return list;
} }
@Override @Override
@Transactional @Transactional
public RecipeDto getRecipeById(Integer Id) { public RecipeDto getRecipeById(Integer Id) {
return convertToDto(recipeRepository.findById(Id).orElseThrow(() -> return convertToDto(recipeRepository.findById(Id).orElseThrow(() -> new NotFoundException("Recipe", "id", Id)));
new NotFoundException("Recipe", "id", Id)));
} }
@Override @Override
@Transactional @Transactional
public RecipeDto updateRecipe(RecipeDto recipeDto, Integer id) { public RecipeDto updateRecipe(RecipeDto recipeDto, Integer id) {
Recipe existingRecipe = recipeRepository.findById(id) Recipe existingRecipe = recipeRepository.findById(id)
.orElseThrow(() -> new NotFoundException("Recipe", "id", id)); .orElseThrow(() -> new NotFoundException("Recipe", "id", id));
existingRecipe.setTitle(recipeDto.getTitle()); existingRecipe.setTitle(recipeDto.getTitle());
existingRecipe.setDescription(recipeDto.getDescription()); existingRecipe.setDescription(recipeDto.getDescription());
existingRecipe.setPrepTimeMinutes(recipeDto.getPrepTimeMinutes()); existingRecipe.setPrepTimeMinutes(recipeDto.getPrepTimeMinutes());
existingRecipe.setCookTimeMinutes(recipeDto.getCookTimeMinutes()); existingRecipe.setCookTimeMinutes(recipeDto.getCookTimeMinutes());
existingRecipe.setServings(recipeDto.getServings()); existingRecipe.setServings(recipeDto.getServings());
existingRecipe.setStatus(recipeDto.getStatus()); existingRecipe.setStatus(recipeDto.getStatus());
List<RecipeIngredientDto> updatedIngredients = recipeDto.getIngredients(); List<RecipeIngredientDto> updatedIngredients = recipeDto.getIngredients();
List<RecipeIngredient> ingredientsToRemove = new ArrayList<>(); List<RecipeIngredient> ingredientsToRemove = new ArrayList<>();
List<StepDto> updatedSteps = recipeDto.getSteps();
List<Step> stepsToRemove = new ArrayList<>();
List<ImageDto> updatedImages = recipeDto.getImages();
List<Image> imagesToRemove = new ArrayList<>();
List<TagDto> updatedTags = recipeDto.getTags();
List<Tag> tagsToRemove = new ArrayList<>();
for (RecipeIngredient ri : existingRecipe.getRecipeIngredients()) { List<StepDto> updatedSteps = recipeDto.getSteps();
List<Step> stepsToRemove = new ArrayList<>();
boolean existsInUpdatedList = false; List<ImageDto> updatedImages = recipeDto.getImages();
for (RecipeIngredientDto dto : updatedIngredients) { List<Image> imagesToRemove = new ArrayList<>();
String updatedName = dto.getIngredientName();
String existingName = ri.getIngredient().getName();
if (updatedName.equals(existingName)) { List<TagDto> updatedTags = recipeDto.getTags();
existsInUpdatedList = true; List<Tag> tagsToRemove = new ArrayList<>();
break;
}
}
if (!existsInUpdatedList) { for (RecipeIngredient ri : existingRecipe.getRecipeIngredients()) {
ingredientsToRemove.add(ri);
}
}
existingRecipe.getRecipeIngredients().removeAll(ingredientsToRemove);
for (RecipeIngredientDto riDto : updatedIngredients) { boolean existsInUpdatedList = false;
for (RecipeIngredientDto dto : updatedIngredients) {
// go through the old list of ingredients until we find a match with updated list String updatedName = dto.getIngredientName();
RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream() String existingName = ri.getIngredient().getName();
.filter(ri -> ri.getIngredient().getName().equals(riDto.getIngredientName()))
.findFirst()
.orElse(null);
// if old ingredient just update parameters
if (existingRI != null) {
existingRI.setQuantity(riDto.getQuantity());
existingRI.setUnit(riDto.getUnit());
existingRI.setNotes(riDto.getNotes());
}
// if new ingredient, have to make a whole new thing
else {
Ingredient ingredient = ingredientRepository.findByName(riDto.getIngredientName())
.orElseGet(() -> new Ingredient(riDto.getIngredientName()));
if (ingredient.getId() == null) { if (updatedName.equals(existingName)) {
ingredientRepository.save(ingredient); existsInUpdatedList = true;
} break;
}
}
RecipeIngredient newRI = new RecipeIngredient( if (!existsInUpdatedList) {
existingRecipe, ingredientsToRemove.add(ri);
ingredient, }
riDto.getQuantity(), }
riDto.getUnit(),
riDto.getNotes()
);
existingRecipe.getRecipeIngredients().add(newRI); existingRecipe.getRecipeIngredients().removeAll(ingredientsToRemove);
}
}
if(updatedSteps != null) {
// find steps that weren't included
for (Step step : existingRecipe.getSteps()) {
boolean existsInUpdatedList = updatedSteps.stream()
.anyMatch(dto -> dto.getStepNumber().equals(step.getStepNumber()));
if (!existsInUpdatedList) stepsToRemove.add(step);
}
// delete those steps
existingRecipe.getSteps().removeAll(stepsToRemove);
// go through updated steps
for (StepDto stepDto : updatedSteps) {
// find matching step by step number
Step existingStep = existingRecipe.getSteps().stream()
.filter(s -> s.getStepNumber().equals(stepDto.getStepNumber()))
.findFirst()
.orElse(null);
// if there's a match update the instruction string
if (existingStep != null) {
existingStep.setInstruction(stepDto.getInstruction());
}
// if no match then make a whole new step
else {
Step newStep = new Step(existingRecipe, stepDto.getStepNumber(), stepDto.getInstruction());
existingRecipe.getSteps().add(newStep);
}
}
}
//same process as above just with images instead
if (updatedImages != null) {
for (Image image : existingRecipe.getImages()) {
boolean existsInUpdatedList = updatedImages.stream()
.anyMatch(dto -> dto.getImageUrl().equals(image.getImageUrl()));
if (!existsInUpdatedList) imagesToRemove.add(image);
}
existingRecipe.getImages().removeAll(imagesToRemove); for (RecipeIngredientDto riDto : updatedIngredients) {
for (ImageDto imageDto : updatedImages) { // go through the old list of ingredients until we find a match with updated
Image existingImage = existingRecipe.getImages().stream() // list
.filter(img -> img.getImageUrl().equals(imageDto.getImageUrl())) RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream()
.findFirst() .filter(ri -> ri.getIngredient().getName().equals(riDto.getIngredientName())).findFirst()
.orElse(null); .orElse(null);
if (existingImage != null) { // if old ingredient just update parameters
existingImage.setImageUrl(imageDto.getImageUrl()); if (existingRI != null) {
}
else {
Image newImage = new Image(existingRecipe, imageDto.getImageUrl());
existingRecipe.getImages().add(newImage);
}
}
}
//same process as above just with tags instead, except for saving the tag
// since the relationship for this one was slightly different
if (updatedTags != null) {
for (Tag tag : existingRecipe.getTags()) {
boolean existsInUpdatedList = updatedTags.stream()
.anyMatch(dto -> dto.getName().equals(tag.getName()));
if (!existsInUpdatedList) tagsToRemove.add(tag);
}
existingRecipe.getTags().removeAll(tagsToRemove); existingRI.setQuantity(riDto.getQuantity());
existingRI.setUnit(riDto.getUnit());
existingRI.setNotes(riDto.getNotes());
}
for (TagDto tagDto : updatedTags) { // if new ingredient, have to make a whole new thing
Tag existingTag = existingRecipe.getTags().stream() else {
.filter(tag -> tag.getName().equals(tagDto.getName()))
.findFirst()
.orElse(null);
if (existingTag != null) { Ingredient ingredient = ingredientRepository.findByName(riDto.getIngredientName())
existingTag.setName(tagDto.getName()); .orElseGet(() -> new Ingredient(riDto.getIngredientName()));
}
else {
Tag newTag = tagRepository.findByName(tagDto.getName())
.orElseGet(() -> tagRepository.save(new Tag(tagDto.getName())));
existingRecipe.getTags().add(newTag); if (ingredient.getId() == null) {
} ingredientRepository.save(ingredient);
} }
}
recipeRepository.save(existingRecipe); RecipeIngredient newRI = new RecipeIngredient(existingRecipe, ingredient, riDto.getQuantity(),
return convertToDto(existingRecipe); riDto.getUnit(), riDto.getNotes());
existingRecipe.getRecipeIngredients().add(newRI);
}
}
if (updatedSteps != null) {
// find steps that weren't included
for (Step step : existingRecipe.getSteps()) {
boolean existsInUpdatedList = updatedSteps.stream()
.anyMatch(dto -> dto.getStepNumber().equals(step.getStepNumber()));
if (!existsInUpdatedList)
stepsToRemove.add(step);
}
// delete those steps
existingRecipe.getSteps().removeAll(stepsToRemove);
// go through updated steps
for (StepDto stepDto : updatedSteps) {
// find matching step by step number
Step existingStep = existingRecipe.getSteps().stream()
.filter(s -> s.getStepNumber().equals(stepDto.getStepNumber())).findFirst().orElse(null);
// if there's a match update the instruction string
if (existingStep != null) {
existingStep.setInstruction(stepDto.getInstruction());
}
// if no match then make a whole new step
else {
Step newStep = new Step(existingRecipe, stepDto.getStepNumber(), stepDto.getInstruction());
existingRecipe.getSteps().add(newStep);
}
}
}
// same process as above just with images instead
if (updatedImages != null) {
for (Image image : existingRecipe.getImages()) {
boolean existsInUpdatedList = updatedImages.stream()
.anyMatch(dto -> dto.getImageUrl().equals(image.getImageUrl()));
if (!existsInUpdatedList)
imagesToRemove.add(image);
}
existingRecipe.getImages().removeAll(imagesToRemove);
for (ImageDto imageDto : updatedImages) {
Image existingImage = existingRecipe.getImages().stream()
.filter(img -> img.getImageUrl().equals(imageDto.getImageUrl())).findFirst().orElse(null);
if (existingImage != null) {
existingImage.setImageUrl(imageDto.getImageUrl());
} else {
Image newImage = new Image(existingRecipe, imageDto.getImageUrl());
existingRecipe.getImages().add(newImage);
}
}
}
// same process as above just with tags instead, except for saving the tag
// since the relationship for this one was slightly different
if (updatedTags != null) {
for (Tag tag : existingRecipe.getTags()) {
boolean existsInUpdatedList = updatedTags.stream().anyMatch(dto -> dto.getName().equals(tag.getName()));
if (!existsInUpdatedList)
tagsToRemove.add(tag);
}
existingRecipe.getTags().removeAll(tagsToRemove);
for (TagDto tagDto : updatedTags) {
Tag existingTag = existingRecipe.getTags().stream()
.filter(tag -> tag.getName().equals(tagDto.getName())).findFirst().orElse(null);
if (existingTag != null) {
existingTag.setName(tagDto.getName());
} else {
Tag newTag = tagRepository.findByName(tagDto.getName())
.orElseGet(() -> tagRepository.save(new Tag(tagDto.getName())));
existingRecipe.getTags().add(newTag);
}
}
}
recipeRepository.save(existingRecipe);
return convertToDto(existingRecipe);
} }
@Override @Override
public void deleteRecipe(Integer Id) { public void deleteRecipe(Integer Id) {
recipeRepository.findById(Id) recipeRepository.findById(Id).orElseThrow(() -> new NotFoundException("Recipe", "id", Id));
.orElseThrow(() -> new NotFoundException("Recipe", "id", Id));
recipeRepository.deleteById(Id); recipeRepository.deleteById(Id);
} }
} }
@@ -22,25 +22,21 @@ import com.example.demo.service.UserService;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
@Service @Service
public class UserServiceImpl implements UserService{ public class UserServiceImpl implements UserService {
private UserRepo userRepository; private UserRepo userRepository;
private RecipeRepo recipeRepository; private RecipeRepo recipeRepository;
public UserServiceImpl(UserRepo userRepository, RecipeRepo recipeRepository) { public UserServiceImpl(UserRepo userRepository, RecipeRepo recipeRepository) {
super(); super();
this.userRepository = userRepository; this.userRepository = userRepository;
this.recipeRepository = recipeRepository; this.recipeRepository = recipeRepository;
} }
public UserDto convertToDto(User user) { public UserDto convertToDto(User user) {
return new UserDto( return new UserDto(user.getId(), user.getUsername(), user.getEmail());
user.getId(),
user.getUsername(),
user.getEmail()
);
} }
@Override @Override
public User saveUser(User user) { public User saveUser(User user) {
return userRepository.save(user); return userRepository.save(user);
@@ -48,74 +44,68 @@ public class UserServiceImpl implements UserService{
@Override @Override
public List<UserDto> getAllUsers() { public List<UserDto> getAllUsers() {
List<UserDto> list = new ArrayList<>(); List<UserDto> list = new ArrayList<>();
for (User user : userRepository.findAll()) { for (User user : userRepository.findAll()) {
UserDto userDto = convertToDto(user); UserDto userDto = convertToDto(user);
list.add(userDto); list.add(userDto);
} }
return list; return list;
} }
@Override @Override
public UserDto getUserById(Integer Id) { public UserDto getUserById(Integer Id) {
return convertToDto(userRepository.findById(Id).orElseThrow(() -> return convertToDto(userRepository.findById(Id).orElseThrow(() -> new NotFoundException("User", "id", Id)));
new NotFoundException("User", "id", Id)));
} }
@Override @Override
@Transactional @Transactional
public UserDto saveFavorite(Integer userId, Integer recipeId) { public UserDto saveFavorite(Integer userId, Integer recipeId) {
User existingUser = userRepository.findById(userId).orElseThrow( User existingUser = userRepository.findById(userId)
() -> new NotFoundException("User", "id", userId)); .orElseThrow(() -> new NotFoundException("User", "id", userId));
Recipe existingRecipe = recipeRepository.findById(recipeId).orElseThrow( Recipe existingRecipe = recipeRepository.findById(recipeId)
() -> new NotFoundException("Recipe", "id", recipeId)); .orElseThrow(() -> new NotFoundException("Recipe", "id", recipeId));
existingUser.getFavRecipes().add(existingRecipe); existingUser.getFavRecipes().add(existingRecipe);
userRepository.save(existingUser); userRepository.save(existingUser);
return convertToDto(existingUser); return convertToDto(existingUser);
} }
@Override @Override
public UserDto updateUser(User user, Integer Id) { public UserDto updateUser(User user, Integer Id) {
User existingUser = userRepository.findById(Id).orElseThrow( User existingUser = userRepository.findById(Id).orElseThrow(() -> new NotFoundException("User", "id", Id));
() -> new NotFoundException("User", "id", Id));
existingUser.setUsername(user.getUsername()); existingUser.setUsername(user.getUsername());
existingUser.setEmail(user.getEmail()); existingUser.setEmail(user.getEmail());
userRepository.save(existingUser); userRepository.save(existingUser);
return convertToDto(existingUser); return convertToDto(existingUser);
} }
@Override @Override
public void deleteUser(Integer Id) { public void deleteUser(Integer Id) {
userRepository.findById(Id).orElseThrow( userRepository.findById(Id).orElseThrow(() -> new NotFoundException("User", "id", Id));
() -> new NotFoundException("User", "id", Id));
userRepository.deleteById(Id); userRepository.deleteById(Id);
} }
@Override @Override
@Transactional @Transactional
public void deleteFavorite(Integer userId, Integer recipeId) { public void deleteFavorite(Integer userId, Integer recipeId) {
User existingUser = userRepository.findById(userId).orElseThrow( User existingUser = userRepository.findById(userId)
() -> new NotFoundException("User", "id", userId)); .orElseThrow(() -> new NotFoundException("User", "id", userId));
Recipe existingRecipe = recipeRepository.findById(recipeId).orElseThrow( Recipe existingRecipe = recipeRepository.findById(recipeId)
() -> new NotFoundException("Recipe", "id", recipeId)); .orElseThrow(() -> new NotFoundException("Recipe", "id", recipeId));
userRepository.save(existingUser); userRepository.save(existingUser);
existingUser.getFavRecipes().remove(existingRecipe); existingUser.getFavRecipes().remove(existingRecipe);
} }
} }
@@ -9,11 +9,16 @@ import com.example.demo.entity.Recipe;
import com.example.demo.entity.User; import com.example.demo.entity.User;
public interface RecipeService { public interface RecipeService {
RecipeDto convertToDto(Recipe recipe) ; RecipeDto convertToDto(Recipe recipe);
RecipeDto saveRecipe(RecipeDto recipe); RecipeDto saveRecipe(RecipeDto recipe);
List<RecipeDto> getAllRecipes(); List<RecipeDto> getAllRecipes();
RecipeDto getRecipeById(Integer recipeId); RecipeDto getRecipeById(Integer recipeId);
RecipeDto updateRecipe(RecipeDto recipedto, Integer Id); RecipeDto updateRecipe(RecipeDto recipedto, Integer Id);
void deleteRecipe(Integer Id); void deleteRecipe(Integer Id);
} }
@@ -7,11 +7,18 @@ import com.example.demo.entity.User;
public interface UserService { public interface UserService {
UserDto convertToDto(User user); UserDto convertToDto(User user);
User saveUser(User user); User saveUser(User user);
List<UserDto> getAllUsers(); List<UserDto> getAllUsers();
UserDto getUserById(Integer Id); UserDto getUserById(Integer Id);
UserDto saveFavorite(Integer userId, Integer recipeId); UserDto saveFavorite(Integer userId, Integer recipeId);
UserDto updateUser(User user, Integer Id); UserDto updateUser(User user, Integer Id);
void deleteUser(Integer Id); void deleteUser(Integer Id);
void deleteFavorite(Integer userId, Integer recipeId); void deleteFavorite(Integer userId, Integer recipeId);
} }