From f9b0f72ecc66f320dae4df94a844b709fb535321 Mon Sep 17 00:00:00 2001 From: George Hatzigeorgio Date: Wed, 31 Mar 2021 14:20:05 -0400 Subject: [PATCH 1/4] commit --- .../com/lambdaschool/foundation/SeedData.java | 94 +----- .../controllers/OpenController.java | 11 +- .../controllers/ProductController.java | 9 + .../controllers/UserController.java | 2 +- .../controllers/UseremailController.java | 130 -------- .../foundation/models/Product.java | 44 +++ .../foundation/models/ProductId.java | 63 ++++ .../lambdaschool/foundation/models/User.java | 132 ++++---- .../foundation/models/UserMinimum.java | 58 ++-- .../foundation/models/UserRoles.java | 4 +- .../foundation/models/UserRolesId.java | 4 +- .../foundation/models/Useremail.java | 128 -------- .../repository/ProductRepository.java | 7 + .../foundation/repository/RoleRepository.java | 14 +- .../foundation/repository/UserRepository.java | 2 + .../repository/UseremailRepository.java | 12 - .../services/SecurityUserServiceImpl.java | 2 +- .../foundation/services/UserServiceImpl.java | 44 +-- .../foundation/services/UseremailService.java | 58 ---- .../services/UseremailServiceImpl.java | 127 -------- .../com/lambdaschool/foundation/SeedData.java | 1 - .../UserControllerUnitNoDBTest.java | 3 +- .../services/UserServiceImplNoDBTest.java | 303 +----------------- .../services/UserServiceImplWithDBTest.java | 232 -------------- 24 files changed, 281 insertions(+), 1203 deletions(-) create mode 100644 foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java delete mode 100644 foundation/src/main/java/com/lambdaschool/foundation/controllers/UseremailController.java create mode 100644 foundation/src/main/java/com/lambdaschool/foundation/models/Product.java create mode 100644 foundation/src/main/java/com/lambdaschool/foundation/models/ProductId.java delete mode 100644 foundation/src/main/java/com/lambdaschool/foundation/models/Useremail.java create mode 100644 foundation/src/main/java/com/lambdaschool/foundation/repository/ProductRepository.java delete mode 100644 foundation/src/main/java/com/lambdaschool/foundation/repository/UseremailRepository.java delete mode 100644 foundation/src/main/java/com/lambdaschool/foundation/services/UseremailService.java delete mode 100644 foundation/src/main/java/com/lambdaschool/foundation/services/UseremailServiceImpl.java diff --git a/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java b/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java index 5aa71e98d..0964146ea 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java @@ -6,7 +6,6 @@ import com.lambdaschool.foundation.models.Role; import com.lambdaschool.foundation.models.User; import com.lambdaschool.foundation.models.UserRoles; -import com.lambdaschool.foundation.models.Useremail; import com.lambdaschool.foundation.services.RoleService; import com.lambdaschool.foundation.services.UserService; import org.springframework.beans.factory.annotation.Autowired; @@ -61,113 +60,44 @@ public void run(String[] args) throws { userService.deleteAll(); roleService.deleteAll(); - Role r1 = new Role("admin"); - Role r2 = new Role("user"); - Role r3 = new Role("data"); + Role r1 = new Role("owner"); + Role r2 = new Role("renter"); + r1 = roleService.save(r1); r2 = roleService.save(r2); - r3 = roleService.save(r3); + // admin, data, user - User u1 = new User("admin", - "password", - "admin@lambdaschool.local"); + User u1 = new User("John","Malango", + "admin@lambdaschool.local","password"); u1.getRoles() .add(new UserRoles(u1, r1)); u1.getRoles() .add(new UserRoles(u1, r2)); - u1.getRoles() - .add(new UserRoles(u1, - r3)); - u1.getUseremails() - .add(new Useremail(u1, - "admin@email.local")); - u1.getUseremails() - .add(new Useremail(u1, - "admin@mymail.local")); + + userService.save(u1); // data, user - User u2 = new User("cinnamon", + User u2 = new User("Marley","Copper", "1234567", "cinnamon@lambdaschool.local"); u2.getRoles() .add(new UserRoles(u2, r2)); - u2.getRoles() - .add(new UserRoles(u2, - r3)); - u2.getUseremails() - .add(new Useremail(u2, - "cinnamon@mymail.local")); - u2.getUseremails() - .add(new Useremail(u2, - "hops@mymail.local")); - u2.getUseremails() - .add(new Useremail(u2, - "bunny@email.local")); - userService.save(u2); - // user - User u3 = new User("barnbarn", - "ILuvM4th!", - "barnbarn@lambdaschool.local"); - u3.getRoles() - .add(new UserRoles(u3, - r2)); - u3.getUseremails() - .add(new Useremail(u3, - "barnbarn@email.local")); - userService.save(u3); - - User u4 = new User("puttat", - "password", - "puttat@school.lambda"); - u4.getRoles() - .add(new UserRoles(u4, - r2)); - userService.save(u4); - User u5 = new User("misskitty", - "password", - "misskitty@school.lambda"); - u5.getRoles() - .add(new UserRoles(u5, - r2)); - userService.save(u5); + userService.save(u2); + - if (false) - { // using JavaFaker create a bunch of regular users // https://www.baeldung.com/java-faker // https://www.baeldung.com/regular-expressions-java - FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-US"), - new RandomService()); - Faker nameFaker = new Faker(new Locale("en-US")); - - for (int i = 0; i < 25; i++) - { - new User(); - User fakeUser; - - fakeUser = new User(nameFaker.name() - .username(), - "password", - nameFaker.internet() - .emailAddress()); - fakeUser.getRoles() - .add(new UserRoles(fakeUser, - r2)); - fakeUser.getUseremails() - .add(new Useremail(fakeUser, - fakeValuesService.bothify("????##@gmail.com"))); - userService.save(fakeUser); - } + } } -} \ No newline at end of file diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/OpenController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/OpenController.java index ae14d8ee7..7a7bc848a 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/OpenController.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/OpenController.java @@ -53,7 +53,7 @@ public class OpenController * @return The token access and other relevent data to token access. Status of CREATED. The location header to look up the new user. * @throws URISyntaxException we create some URIs during this method. If anything goes wrong with that creation, an exception is thrown. */ - @PostMapping(value = "/createnewuser", + @PostMapping(value = "/users/register", consumes = {"application/json"}, produces = {"application/json"}) public ResponseEntity addSelf( @@ -66,10 +66,11 @@ public ResponseEntity addSelf( { // Create the user User newuser = new User(); - - newuser.setUsername(newminuser.getUsername()); + newuser.setFirstname(newminuser.getFirstname()); + newuser.setLastname((newminuser.getLastname())); + newuser.setEmail(newminuser.getEmail()); newuser.setPassword(newminuser.getPassword()); - newuser.setPrimaryemail(newminuser.getPrimaryemail()); + // add the default role of user Set newRoles = new HashSet<>(); @@ -107,7 +108,7 @@ public ResponseEntity addSelf( map.add("scope", "read write trust"); map.add("username", - newminuser.getUsername()); + newminuser.getEmail()); map.add("password", newminuser.getPassword()); diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java new file mode 100644 index 000000000..0e7a4d9bc --- /dev/null +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java @@ -0,0 +1,9 @@ +package com.lambdaschool.foundation.controllers; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/products") +public class ProductController { +} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java index caa8547ad..9333bf67d 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java @@ -57,7 +57,7 @@ public ResponseEntity listAllUsers() */ @GetMapping(value = "/user/{userId}", produces = "application/json") - public ResponseEntity getUserById( + public ResponseEntity getProductById( @PathVariable Long userId) { diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/UseremailController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/UseremailController.java deleted file mode 100644 index 2c85b845a..000000000 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/UseremailController.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.lambdaschool.foundation.controllers; - -import com.lambdaschool.foundation.models.Useremail; -import com.lambdaschool.foundation.services.UseremailService; -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 org.springframework.web.servlet.support.ServletUriComponentsBuilder; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - -/** - * The entry point for client to access user, email combinations - */ -@RestController -@RequestMapping("/useremails") -public class UseremailController -{ - /** - * Using the Useremail service to process user, email combinations data - */ - @Autowired - UseremailService useremailService; - - /** - * List of all users emails - *
Example: http://localhost:2019/useremails/useremails - * - * @return JSON list of all users emails - */ - @GetMapping(value = "/useremails", - produces = "application/json") - public ResponseEntity listAllUseremails() - { - List allUserEmails = useremailService.findAll(); - return new ResponseEntity<>(allUserEmails, - HttpStatus.OK); - } - - /** - * Return the user email combination referenced by the given primary key - *
Example: http://localhost:2019/useremails/useremail/8 - * - * @param useremailId the primary key of the user email combination you seek - * @return JSON object of the user email combination you seek with a status of OK - */ - @GetMapping(value = "/useremail/{useremailId}", - produces = "application/json") - public ResponseEntity getUserEmailById( - @PathVariable - Long useremailId) - { - Useremail ue = useremailService.findUseremailById(useremailId); - return new ResponseEntity<>(ue, - HttpStatus.OK); - } - - /** - * Removes the given user email combination - *
Example: http://localhost:2019/useremails/useremail/8 - * - * @param useremailid the primary key of the user email combination you wish to remove - * @return Status of OK - */ - @DeleteMapping(value = "/useremail/{useremailid}") - public ResponseEntity deleteUserEmailById( - @PathVariable - long useremailid) - { - useremailService.delete(useremailid); - return new ResponseEntity<>(HttpStatus.OK); - } - - /** - * Change the email associated with the given user email combination - *
Example: http://localhost:2019/useremails/useremail/9/email/favbun@hops.local - * - * @param useremailid The primary key of the user email combination you wish to change - * @param emailaddress The new email (String) - * @return Status of OK - */ - @PutMapping("/useremail/{useremailid}/email/{emailaddress}") - public ResponseEntity updateUserEmail( - @PathVariable - long useremailid, - @PathVariable - String emailaddress) - { - useremailService.update(useremailid, - emailaddress); - return new ResponseEntity<>(HttpStatus.OK); - } - - /** - * Adds a new user email combination - * - * @param userid the user id of the new user email combination - * @param emailaddress the email address of the new user eamil combination - * @return A location header with the URI to the newly created user email combination and a status of CREATED - * @throws URISyntaxException Exception if something does not work in creating the location header - * @see UseremailService#save(long, String) UseremailService.save(long, String) - */ - @PostMapping(value = "/user/{userid}/email/{emailaddress}") - public ResponseEntity addNewUserEmail( - @PathVariable - long userid, - @PathVariable - String emailaddress) throws - URISyntaxException - { - Useremail newUserEmail = useremailService.save(userid, - emailaddress); - - // set the location header for the newly created resource - HttpHeaders responseHeaders = new HttpHeaders(); - URI newUserEmailURI = ServletUriComponentsBuilder.fromCurrentServletMapping() - .path("/useremails/useremail/{useremailid}") - .buildAndExpand(newUserEmail.getUseremailid()) - .toUri(); - responseHeaders.setLocation(newUserEmailURI); - - return new ResponseEntity<>(null, - responseHeaders, - HttpStatus.CREATED); - } -} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java b/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java new file mode 100644 index 000000000..c9c2e7dd1 --- /dev/null +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java @@ -0,0 +1,44 @@ +package com.lambdaschool.foundation.models; + +import net.bytebuddy.dynamic.loading.InjectionClassLoader; +import org.springframework.boot.autoconfigure.web.ResourceProperties; + +import javax.persistence.*; + +@Entity +@Table(name = "products") +public class Product { + + private String product; + @Id + @GeneratedValue (strategy = GenerationType.AUTO) + private String productid; + + + + + + public Product() { + } + + public Product(String product, String productid) { + this.product = product; + this.productid = productid; + } + + public String getProduct() { + return product; + } + + public void setProduct(String product) { + this.product = product; + } + + public String getProductid() { + return productid; + } + + public void setProductid(String productid) { + this.productid = productid; + } +} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/ProductId.java b/foundation/src/main/java/com/lambdaschool/foundation/models/ProductId.java new file mode 100644 index 000000000..bae1d2585 --- /dev/null +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/ProductId.java @@ -0,0 +1,63 @@ +package com.lambdaschool.foundation.models; + +import java.io.Serializable; +import java.util.Objects; + +public class ProductId implements Serializable { + private long user; + + private long product; + + public ProductId() { + } + + public ProductId(long user, long product) { + this.user = user; + this.product = product; + } + + public long getUser() { + return user; + } + + public void setUser(long user) { + this.user = user; + } + + public long getProduct() { + return product; + } + + public void setProduct(long product) { + this.product = product; + } + + @Override + public boolean equals(Object o) + { + if(this == o) + { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProductId that = (ProductId) o; + return this.user == that.user && + this.product == that.product; + + + + + + + + + + } + + @Override + public int hashCode() { + return 37; + } +} \ No newline at end of file diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/User.java b/foundation/src/main/java/com/lambdaschool/foundation/models/User.java index da5d4671e..d000a3d18 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/User.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/User.java @@ -38,27 +38,29 @@ public class User /** * The password (String) for this user. Cannot be null. Never get displayed */ - @Column(nullable = false) - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) - private String password; /** * Primary email account of user. Could be used as the userid. Cannot be null and must be unique. */ + + + @Column(nullable = false,unique = true) + private String firstname; + + @Column(nullable = false,unique=true) + private String lastname; + @Column(nullable = false, - unique = true) + unique = true) @Email - private String primaryemail; + private String email; + @Column(nullable = false) + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + private String password; /** * A list of emails for this user - */ - @OneToMany(mappedBy = "user", - cascade = CascadeType.ALL, - orphanRemoval = true) - @JsonIgnoreProperties(value = "user", - allowSetters = true) - private List useremails = new ArrayList<>(); + /** * Part of the join relationship between user and role @@ -71,6 +73,11 @@ public class User allowSetters = true) private Set roles = new HashSet<>(); + + @OneToMany(mappedBy = "user",cascade = CascadeType.ALL,orphanRemoval = true) + @JsonIgnoreProperties(value = "user", allowSetters = true) + private Set products = new HashSet<>(); + /** * Default constructor used primarily by the JPA. */ @@ -78,6 +85,18 @@ public User() { } + public User( String firstname, String lastname, @Email String email, String password, Set roles, Set products) { + this.firstname = firstname; + this.lastname = lastname; + this.email = email; + this.password = password; + + } + + public User(String firstname, String lastname, String email, String password) { + super(); + } + /** * Given the params, create a new user object *

@@ -86,86 +105,91 @@ public User() * @param username The username (String) of the user * @param password The password (String) of the user * @param primaryemail The primary email (String) of the user - */ - public User( - String username, - String password, - String primaryemail) - { - setUsername(username); - setPassword(password); - this.primaryemail = primaryemail; - } + /** * Getter for userid * * @return the userid (long) of the user */ - public long getUserid() - { - return userid; - } /** * Setter for userid. Used primary for seeding data * * @param userid the new userid (long) of the user */ - public void setUserid(long userid) - { + public long getUserid() { + return userid; + } + + public void setUserid(long userid) { this.userid = userid; } + public Set getProducts() { + return products; + } + + public void setProducts(Set products) { + this.products = products; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + /** * Getter for username * * @return the username (String) lowercase - */ - public String getUsername() - { - return username; - } /** * setter for username * * @param username the new username (String) converted to lowercase */ - public void setUsername(String username) - { - this.username = username.toLowerCase(); - } /** * getter for primary email * * @return the primary email (String) for the user converted to lowercase */ - public String getPrimaryemail() - { - return primaryemail; - } /** * setter for primary email * * @param primaryemail the new primary email (String) for the user converted to lowercase */ - public void setPrimaryemail(String primaryemail) - { - this.primaryemail = primaryemail.toLowerCase(); - } /** * Getter for the password * * @return the password (String) of the user */ - public String getPassword() - { - return password; - } /** * Setter for password to be used internally, after the password has already been encrypted @@ -186,25 +210,17 @@ public void setPassword(String password) this.password = passwordEncoder.encode(password); } - /** +/** * Getter for the list of useremails for this user * * @return the list of useremails (List(Useremail)) for this user */ - public List getUseremails() - { - return useremails; - } /** * Setter for list of useremails for this user * * @param useremails the new list of useremails (List(Useremail)) for this user */ - public void setUseremails(List useremails) - { - this.useremails = useremails; - } /** * Getter for user role combinations diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/UserMinimum.java b/foundation/src/main/java/com/lambdaschool/foundation/models/UserMinimum.java index 83c49ca71..860ce9394 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/UserMinimum.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/UserMinimum.java @@ -6,12 +6,11 @@ * A model used to create a new user. The minimum information needed to create a user. * Note the role will default to USER. */ -public class UserMinimum -{ +public class UserMinimum { /** * The username (String) */ - private String username; + private String firstname; /** * The user's password (String) @@ -22,35 +21,53 @@ public class UserMinimum * The user's primary email address (String) */ @Email - private String primaryemail; + private String email; + + + private String lastname; + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + + + + public String getLastname() { + return lastname; + } + + + + + + public void setLastname(String lastname) { + this.lastname = lastname; + } /** * Getter for the username * * @return the username (String) associated with this user */ - public String getUsername() - { - return username; - } + /** * Setter for the username * * @param username the new username (String) associated with this user */ - public void setUsername(String username) - { - this.username = username; - } /** * Getter for the password of this user * * @return the password (String) for this user */ - public String getPassword() - { + public String getPassword() { return password; } @@ -60,8 +77,7 @@ public String getPassword() * * @param password the new password (String in clear texts) for this user */ - public void setPassword(String password) - { + public void setPassword(String password) { this.password = password; } @@ -70,9 +86,8 @@ public void setPassword(String password) * * @return the email address (String) for this user */ - public String getPrimaryemail() - { - return primaryemail; + public String getEmail() { + return email; } /** @@ -80,8 +95,7 @@ public String getPrimaryemail() * * @param primaryemail the new email address (String) for this user. */ - public void setPrimaryemail(String primaryemail) - { - this.primaryemail = primaryemail; + public void setEmail(String email) { + this.email = email; } } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/UserRoles.java b/foundation/src/main/java/com/lambdaschool/foundation/models/UserRoles.java index dfb9cb4ee..8aeb4bf6c 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/UserRoles.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/UserRoles.java @@ -117,8 +117,8 @@ public boolean equals(Object o) return false; } UserRoles that = (UserRoles) o; - return ((user == null) ? 0 : user.getUserid()) == ((that.user == null) ? 0 : that.user.getUserid()) && - ((role == null) ? 0 : role.getRoleid()) == ((that.role == null) ? 0 : that.role.getRoleid()); + return ((this.user == null) ? 0 : this.user.getUserid()) == ((that.user == null) ? 0 : that.user.getUserid()) && + ((this.role == null) ? 0 : this.role.getRoleid()) == ((that.role == null) ? 0 : that.role.getRoleid()); } @Override diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/UserRolesId.java b/foundation/src/main/java/com/lambdaschool/foundation/models/UserRolesId.java index 093b4956a..73ed016ed 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/UserRolesId.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/UserRolesId.java @@ -79,8 +79,8 @@ public boolean equals(Object o) return false; } UserRolesId that = (UserRolesId) o; - return user == that.user && - role == that.role; + return this.user == that.user && + this.role == that.role; } @Override diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/Useremail.java b/foundation/src/main/java/com/lambdaschool/foundation/models/Useremail.java deleted file mode 100644 index 4ae16bfd9..000000000 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/Useremail.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.lambdaschool.foundation.models; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import javax.persistence.*; -import javax.validation.constraints.Email; - -/** - * The entity allowing interaction with the useremails table - *

- * requires each combination of user and useremail to be unique. The same email cannot be assigned to the same user more than once. - */ -@Entity -@Table(name = "useremails") -public class Useremail - extends Auditable -{ - /** - * The primary key (long) of the useremails table - */ - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long useremailid; - - /** - * Email (String) for this user. Cannot be nullable. - * Must be in the format userid@domain.upperLevelDomain - */ - @Column(nullable = false) - @Email - private String useremail; - - /** - * The userid of the user assigned to this email is what is stored in the database. - * This is the entire user object! - *

- * Forms a Many to One relationship between useremails and users. - * A user can have many emails. - */ - @ManyToOne - @JoinColumn(name = "userid", - nullable = false) - @JsonIgnoreProperties(value = "useremails", - allowSetters = true) - private User user; - - /** - * The default controller is required by JPA - */ - public Useremail() - { - } - - /** - * Given the parameters, create a new useremail object - * - * @param user the user (User) assigned to the email - * @param useremail useremail (String) for the given user - */ - public Useremail( - User user, - String useremail) - { - this.useremail = useremail; - this.user = user; - } - - /** - * Getter for useremailid - * - * @return the primary key (long) of this useremail object - */ - public long getUseremailid() - { - return useremailid; - } - - /** - * Setter for useremailid. Used for seeding data - * - * @param useremailid the new primary key (long) of this useremail object - */ - public void setUseremailid(long useremailid) - { - this.useremailid = useremailid; - } - - /** - * Getter for useremail - * - * @return the email (String) associated with this useremail object in lowercase - */ - public String getUseremail() - { - return useremail; - } - - /** - * Setter for useremail - * - * @param useremail the email (String) to replace the one currently assigned to this useremail object, in lowercase - */ - public void setUseremail(String useremail) - { - this.useremail = useremail.toLowerCase(); - } - - - /** - * Getter for user - * - * @return the user object associated with this useremail. - */ - public User getUser() - { - return user; - } - - /** - * Setter for user - * - * @param user the user object to replace the one currently assigned to this useremail object - */ - public void setUser(User user) - { - this.user = user; - } -} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/repository/ProductRepository.java b/foundation/src/main/java/com/lambdaschool/foundation/repository/ProductRepository.java new file mode 100644 index 000000000..2967f8c68 --- /dev/null +++ b/foundation/src/main/java/com/lambdaschool/foundation/repository/ProductRepository.java @@ -0,0 +1,7 @@ +package com.lambdaschool.foundation.repository; + +import com.lambdaschool.foundation.models.Product; +import org.springframework.data.repository.CrudRepository; + +public interface ProductRepository extends CrudRepository { +} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/repository/RoleRepository.java b/foundation/src/main/java/com/lambdaschool/foundation/repository/RoleRepository.java index f3286e73b..f87348675 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/repository/RoleRepository.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/repository/RoleRepository.java @@ -27,13 +27,13 @@ public interface RoleRepository * @param roleid The primary key (long) of the role to change * @param name The new name (String) of the role */ - @Transactional - @Modifying - @Query(value = "UPDATE roles SET name = :name, lastmodifiedby = :uname, lastmodifieddate = CURRENT_TIMESTAMP WHERE roleid = :roleid", + @Transactional + @Modifying + @Query(value = "UPDATE roles SET name = :name, lastmodifiedby = :uname, lastmodifieddate = CURRENT_TIMESTAMP WHERE roleid = :roleid", nativeQuery = true) - void updateRoleName( - String uname, - long roleid, - String name); + void updateRoleName( + String uname, + long roleid, + String name); } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/repository/UserRepository.java b/foundation/src/main/java/com/lambdaschool/foundation/repository/UserRepository.java index 4360e93d2..6b5dc90be 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/repository/UserRepository.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/repository/UserRepository.java @@ -26,4 +26,6 @@ public interface UserRepository * @return List of users whose name contain the given substring ignoring case */ List findByUsernameContainingIgnoreCase(String name); + + User findByEmail(String email); } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/repository/UseremailRepository.java b/foundation/src/main/java/com/lambdaschool/foundation/repository/UseremailRepository.java deleted file mode 100644 index 2aa7de208..000000000 --- a/foundation/src/main/java/com/lambdaschool/foundation/repository/UseremailRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.lambdaschool.foundation.repository; - -import com.lambdaschool.foundation.models.Useremail; -import org.springframework.data.repository.CrudRepository; - -/** - * The CRUD Repository connecting Useremail to the rest of the application - */ -public interface UseremailRepository - extends CrudRepository -{ -} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/SecurityUserServiceImpl.java b/foundation/src/main/java/com/lambdaschool/foundation/services/SecurityUserServiceImpl.java index aab1fdd19..a86eb6c50 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/SecurityUserServiceImpl.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/SecurityUserServiceImpl.java @@ -43,7 +43,7 @@ public UserDetails loadUserByUsername(String s) { throw new ResourceNotFoundException("Invalid username or password."); } - return new org.springframework.security.core.userdetails.User(user.getUsername(), + return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.getAuthority()); } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/UserServiceImpl.java b/foundation/src/main/java/com/lambdaschool/foundation/services/UserServiceImpl.java index e83864e40..ea54d9cbe 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/UserServiceImpl.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/UserServiceImpl.java @@ -4,7 +4,6 @@ import com.lambdaschool.foundation.models.Role; import com.lambdaschool.foundation.models.User; import com.lambdaschool.foundation.models.UserRoles; -import com.lambdaschool.foundation.models.Useremail; import com.lambdaschool.foundation.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException; @@ -77,7 +76,7 @@ public void delete(long id) @Override public User findByName(String name) { - User uu = userrepos.findByUsername(name.toLowerCase()); + User uu = userrepos.findByEmail(name.toLowerCase()); if (uu == null) { throw new ResourceNotFoundException("User name " + name + " not found!"); @@ -97,12 +96,12 @@ public User save(User user) .orElseThrow(() -> new ResourceNotFoundException("User id " + user.getUserid() + " not found!")); newUser.setUserid(user.getUserid()); } - - newUser.setUsername(user.getUsername() - .toLowerCase()); + newUser.setFirstname(user.getFirstname()); + newUser.setLastname(user.getLastname()); newUser.setPasswordNoEncrypt(user.getPassword()); - newUser.setPrimaryemail(user.getPrimaryemail() - .toLowerCase()); + newUser.setEmail(user.getEmail()); + + newUser.getRoles() .clear(); @@ -115,14 +114,6 @@ public User save(User user) addRole)); } - newUser.getUseremails() - .clear(); - for (Useremail ue : user.getUseremails()) - { - newUser.getUseremails() - .add(new Useremail(newUser, - ue.getUseremail())); - } return userrepos.save(newUser); } @@ -135,11 +126,11 @@ public User update( { User currentUser = findUserById(id); - if (helperFunctions.isAuthorizedToMakeChange(currentUser.getUsername())) + if (helperFunctions.isAuthorizedToMakeChange(currentUser.getEmail())) { - if (user.getUsername() != null) + if (user.getEmail() != null) { - currentUser.setUsername(user.getUsername() + currentUser.setEmail(user.getEmail() .toLowerCase()); } @@ -148,11 +139,6 @@ public User update( currentUser.setPasswordNoEncrypt(user.getPassword()); } - if (user.getPrimaryemail() != null) - { - currentUser.setPrimaryemail(user.getPrimaryemail() - .toLowerCase()); - } if (user.getRoles() .size() > 0) @@ -170,18 +156,6 @@ public User update( } } - if (user.getUseremails() - .size() > 0) - { - currentUser.getUseremails() - .clear(); - for (Useremail ue : user.getUseremails()) - { - currentUser.getUseremails() - .add(new Useremail(currentUser, - ue.getUseremail())); - } - } return userrepos.save(currentUser); } else diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/UseremailService.java b/foundation/src/main/java/com/lambdaschool/foundation/services/UseremailService.java deleted file mode 100644 index c3391d466..000000000 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/UseremailService.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.lambdaschool.foundation.services; - -import com.lambdaschool.foundation.models.Useremail; - -import java.util.List; - - -/** - * The Service that works with the Useremail Model - *

- * Note: Emails are added through the add user process - */ -public interface UseremailService -{ - /** - * Returns a list of all users and their emails - * - * @return List of users and their emails - */ - List findAll(); - - /** - * Returns the user email combination associated with the given id - * - * @param id The primary key (long) of the user email combination you seek - * @return The user email combination (Useremail) you seek - */ - Useremail findUseremailById(long id); - - /** - * Remove the user email combination referenced by the given id - * - * @param id The primary key (long) of the user email combination you seek - */ - void delete(long id); - - /** - * Replaces the email of the user email combination you seek - * - * @param useremailid The primary key (long) of the user email combination you seek - * @param emailaddress The new email address (String) for this user email combination - * @return The Useremail object that you updated including the new email address - */ - Useremail update( - long useremailid, - String emailaddress); - - /** - * Add a new User Email combination - * - * @param userid the userid of the new user email combination - * @param emailaddress the email address of the new user email combination - * @return the new user email combination - */ - Useremail save( - long userid, - String emailaddress); -} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/UseremailServiceImpl.java b/foundation/src/main/java/com/lambdaschool/foundation/services/UseremailServiceImpl.java deleted file mode 100644 index 4b4bb6487..000000000 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/UseremailServiceImpl.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.lambdaschool.foundation.services; - -import com.lambdaschool.foundation.exceptions.ResourceNotFoundException; -import com.lambdaschool.foundation.models.User; -import com.lambdaschool.foundation.models.Useremail; -import com.lambdaschool.foundation.repository.UseremailRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.ArrayList; -import java.util.List; - -/** - * Implements the UseremailService Interface - */ -@Transactional -@Service(value = "useremailService") -public class UseremailServiceImpl - implements UseremailService -{ - /** - * Connects this service to the Useremail model - */ - @Autowired - private UseremailRepository useremailrepos; - - /** - * Connects this servive to the User Service - */ - @Autowired - private UserService userService; - - @Autowired - private HelperFunctions helperFunctions; - - @Override - public List findAll() - { - List list = new ArrayList<>(); - /* - * findAll returns an iterator set. - * iterate over the iterator set and add each element to an array list. - */ - useremailrepos.findAll() - .iterator() - .forEachRemaining(list::add); - return list; - } - - @Override - public Useremail findUseremailById(long id) - { - return useremailrepos.findById(id) - .orElseThrow(() -> new ResourceNotFoundException("Useremail with id " + id + " Not Found!")); - } - - @Transactional - @Override - public void delete(long id) - { - if (useremailrepos.findById(id) - .isPresent()) - { - if (helperFunctions.isAuthorizedToMakeChange(useremailrepos.findById(id) - .get() - .getUser() - .getUsername())) - { - useremailrepos.deleteById(id); - } - } else - { - throw new ResourceNotFoundException("Useremail with id " + id + " Not Found!"); - } - } - - @Transactional - @Override - public Useremail update( - long useremailid, - String emailaddress) - { - if (useremailrepos.findById(useremailid) - .isPresent()) - { - if (helperFunctions.isAuthorizedToMakeChange(useremailrepos.findById(useremailid) - .get() - .getUser() - .getUsername())) - { - Useremail useremail = findUseremailById(useremailid); - useremail.setUseremail(emailaddress.toLowerCase()); - return useremailrepos.save(useremail); - } else - { - // note we should never get to this line but is needed for the compiler - // to recognize that this exception can be thrown - throw new ResourceNotFoundException("This user is not authorized to make change"); - } - } else - { - throw new ResourceNotFoundException("Useremail with id " + useremailid + " Not Found!"); - } - } - - @Transactional - @Override - public Useremail save( - long userid, - String emailaddress) - { - User currentUser = userService.findUserById(userid); - - if (helperFunctions.isAuthorizedToMakeChange(currentUser.getUsername())) - { - Useremail newUserEmail = new Useremail(currentUser, - emailaddress); - return useremailrepos.save(newUserEmail); - } else - { - // note we should never get to this line but is needed for the compiler - // to recognize that this exception can be thrown - throw new ResourceNotFoundException("This user is not authorized to make change"); - } - } -} diff --git a/foundation/src/test/java/com/lambdaschool/foundation/SeedData.java b/foundation/src/test/java/com/lambdaschool/foundation/SeedData.java index d5840a254..89918d9f9 100755 --- a/foundation/src/test/java/com/lambdaschool/foundation/SeedData.java +++ b/foundation/src/test/java/com/lambdaschool/foundation/SeedData.java @@ -6,7 +6,6 @@ import com.lambdaschool.foundation.models.Role; import com.lambdaschool.foundation.models.User; import com.lambdaschool.foundation.models.UserRoles; -import com.lambdaschool.foundation.models.Useremail; import com.lambdaschool.foundation.services.RoleService; import com.lambdaschool.foundation.services.UserService; import org.springframework.beans.factory.annotation.Autowired; diff --git a/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerUnitNoDBTest.java b/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerUnitNoDBTest.java index 3b10c2fdb..00aff2d3b 100644 --- a/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerUnitNoDBTest.java +++ b/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerUnitNoDBTest.java @@ -5,7 +5,6 @@ import com.lambdaschool.foundation.models.Role; import com.lambdaschool.foundation.models.User; import com.lambdaschool.foundation.models.UserRoles; -import com.lambdaschool.foundation.models.Useremail; import com.lambdaschool.foundation.services.UserService; import io.restassured.module.mockmvc.RestAssuredMockMvc; import org.junit.After; @@ -74,7 +73,7 @@ public void setUp() throws Exception r3.setRoleid(3); // admin, data, user - User u1 = new User("admin", + User u1 = new User("George","Hatzigeorgio", "ILuvM4th!", "admin@lambdaschool.test"); u1.getRoles() diff --git a/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplNoDBTest.java b/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplNoDBTest.java index 0c8293042..e2a23cdce 100644 --- a/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplNoDBTest.java +++ b/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplNoDBTest.java @@ -5,7 +5,6 @@ import com.lambdaschool.foundation.models.Role; import com.lambdaschool.foundation.models.User; import com.lambdaschool.foundation.models.UserRoles; -import com.lambdaschool.foundation.models.Useremail; import com.lambdaschool.foundation.repository.UserRepository; import org.junit.Before; import org.junit.Test; @@ -50,14 +49,13 @@ public void setUp() throws Exception { userList = new ArrayList<>(); - Role r1 = new Role("admin"); + Role r1 = new Role("renter"); r1.setRoleid(1); - Role r2 = new Role("user"); + Role r2 = new Role("owner"); r2.setRoleid(2); - Role r3 = new Role("data"); - r3.setRoleid(3); - // admin, data, user + + // User u1 = new User("admin", "ILuvM4th!", "admin@lambdaschool.test"); @@ -125,296 +123,5 @@ public void setUp() throws Exception userList.add(u2); // user - User u3 = new User("testingbarn", - "ILuvM4th!", - "testingbarn@school.lambda"); - u3.getRoles() - .add(new UserRoles(u3, - r1)); - - u3.getUseremails() - .add(new Useremail(u3, - "barnbarn@email.test")); - u3.getUseremails() - .get(0) - .setUseremailid(30); - - u3.setUserid(103); - userList.add(u3); - - User u4 = new User("testingcat", - "password", - "testingcat@school.lambda"); - u4.getRoles() - .add(new UserRoles(u4, - r2)); - - u4.setUserid(104); - userList.add(u4); - - User u5 = new User("testingdog", - "password", - "testingdog@school.lambda"); - u4.getRoles() - .add(new UserRoles(u5, - r2)); - - u5.setUserid(105); - userList.add(u5); - - MockitoAnnotations.initMocks(this); - } - - @Test - public void findUserById() - { - Mockito.when(userrepos.findById(101L)) - .thenReturn(Optional.of(userList.get(0))); - - assertEquals("admin", - userService.findUserById(101L) - .getUsername()); - } - - @Test(expected = ResourceNotFoundException.class) - public void findUserByIdNotFound() - { - Mockito.when(userrepos.findById(10L)) - .thenReturn(Optional.empty()); - - assertEquals("admin", - userService.findUserById(10L) - .getUsername()); - } - - @Test - public void findAll() - { - Mockito.when(userrepos.findAll()) - .thenReturn(userList); - - assertEquals(5, - userService.findAll() - .size()); - } - - @Test - public void delete() - { - Mockito.when(userrepos.findById(103L)) - .thenReturn(Optional.of(userList.get(0))); - - Mockito.doNothing() - .when(userrepos) - .deleteById(103L); - - userService.delete(103L); - assertEquals(5, - userList.size()); - } - - @Test(expected = ResourceNotFoundException.class) - public void notFoundDelete() - { - Mockito.when(userrepos.findById(10L)) - .thenReturn(Optional.empty()); - - Mockito.doNothing() - .when(userrepos) - .deleteById(10L); - - userService.delete(10L); - assertEquals(5, - userList.size()); - } - - @Test - public void findByUsername() - { - Mockito.when(userrepos.findByUsername("admin")) - .thenReturn(userList.get(0)); - - assertEquals("admin", - userService.findByName("admin") - .getUsername()); - } - - @Test(expected = ResourceNotFoundException.class) - public void findByUsernameNotfound() - { - Mockito.when(userrepos.findByUsername("nonsense")) - .thenReturn(null); - - assertEquals("nonsense", - userService.findByName("nonsense") - .getUsername()); - } - - @Test - public void findByNameContaining() - { - Mockito.when(userrepos.findByUsernameContainingIgnoreCase("a")) - .thenReturn(userList); - - assertEquals(5, - userService.findByNameContaining("a") - .size()); - } - - @Test - public void save() - { - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("tiger", - "ILuvMath!", - "tiger@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - u2.getUseremails() - .add(new Useremail(u2, - "tiger@tiger.local")); - - Mockito.when(userrepos.save(any(User.class))) - .thenReturn(u2); - - Mockito.when(roleService.findRoleById(2)) - .thenReturn(r2); - - assertEquals("tiger", - userService.save(u2) - .getUsername()); - } - - @Test - public void savePut() - { - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("tiger", - "ILuvMath!", - "tiger@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - u2.getUseremails() - .add(new Useremail(u2, - "tiger@tiger.local")); - u2.setUserid(103L); - - Mockito.when(roleService.findRoleById(2)) - .thenReturn(r2); - - Mockito.when(userrepos.findById(103L)) - .thenReturn(Optional.of(u2)); - - Mockito.when(userrepos.save(any(User.class))) - .thenReturn(u2); - - assertEquals(103L, - userService.save(u2) - .getUserid()); - } - - @Test - public void update() - { - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("cinnamon", - "password", - "cinnamon@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - - u2.getUseremails() - .add(new Useremail(u2, - "cinnamon@mymail.thump")); - u2.getUseremails() - .add(new Useremail(u2, - "hops@mymail.thump")); - u2.getUseremails() - .add(new Useremail(u2, - "bunny@email.thump")); - - Mockito.when(roleService.findRoleById(2)) - .thenReturn(r2); - - Mockito.when(userrepos.findById(103L)) - .thenReturn(Optional.of(userList.get(2))); - - Mockito.when(userrepos.save(any(User.class))) - .thenReturn(u2); - - Mockito.when(helperFunctions.isAuthorizedToMakeChange(anyString())) - .thenReturn(true); - - assertEquals("bunny@email.thump", - userService.update(u2, - 103L) - .getUseremails() - .get(2) - .getUseremail()); - } - - @Test(expected = ResourceNotFoundException.class) - public void updateNotFound() - { - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("cinnamon", - "password", - "cinnamon@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - - u2.getUseremails() - .add(new Useremail(u2, - "cinnamon@mymail.thump")); - u2.getUseremails() - .add(new Useremail(u2, - "hops@mymail.thump")); - u2.getUseremails() - .add(new Useremail(u2, - "bunny@email.thump")); - - Mockito.when(roleService.findRoleById(2)) - .thenReturn(r2); - - Mockito.when(userrepos.findById(103L)) - .thenReturn(Optional.empty()); - - Mockito.when(userrepos.save(any(User.class))) - .thenReturn(u2); - - Mockito.when(helperFunctions.isAuthorizedToMakeChange(anyString())) - .thenReturn(false); - - assertEquals("bunny@email.thump", - userService.update(u2, - 103L) - .getUseremails() - .get(2) - .getUseremail()); - } - - @Test - public void deleteAll() - { - Mockito.doNothing() - .when(userrepos) - .deleteAll(); - - userService.deleteAll(); - assertEquals(5, - userList.size()); - - } + } \ No newline at end of file diff --git a/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplWithDBTest.java b/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplWithDBTest.java index 6a1af816c..2675c0152 100644 --- a/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplWithDBTest.java +++ b/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplWithDBTest.java @@ -5,7 +5,6 @@ import com.lambdaschool.foundation.models.Role; import com.lambdaschool.foundation.models.User; import com.lambdaschool.foundation.models.UserRoles; -import com.lambdaschool.foundation.models.Useremail; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; @@ -44,236 +43,5 @@ public void tearDown() throws Exception { } - @Test - public void B_findUserById() - { - assertEquals("admin", - userService.findUserById(4) - .getUsername()); - } - - @Test(expected = ResourceNotFoundException.class) - public void BA_findUserByIdNotFound() - { - assertEquals("admin", - userService.findUserById(10) - .getUsername()); - } - - @Test - public void C_findAll() - { - assertEquals(5, - userService.findAll() - .size()); - } - - @Test - public void D_delete() - { - userService.delete(13); - assertEquals(4, - userService.findAll() - .size()); - } - - @Test(expected = ResourceNotFoundException.class) - public void DA_notFoundDelete() - { - userService.delete(100); - assertEquals(4, - userService.findAll() - .size()); - } - - @Test - public void E_findByUsername() - { - assertEquals("admin", - userService.findByName("admin") - .getUsername()); - } - - @Test(expected = ResourceNotFoundException.class) - public void AA_findByUsernameNotfound() - { - assertEquals("admin", - userService.findByName("turtle") - .getUsername()); - } - - @Test - public void AB_findByNameContaining() - { - assertEquals(4, - userService.findByNameContaining("a") - .size()); - } - - @Test - public void F_save() - { - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("tiger", - "ILuvMath!", - "tiger@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - u2.getUseremails() - .add(new Useremail(u2, - "tiger@tiger.local")); - - User saveU2 = userService.save(u2); - - System.out.println("*** DATA ***"); - System.out.println(saveU2); - System.out.println("*** DATA ***"); - - assertEquals("tiger@tiger.local", - saveU2.getUseremails() - .get(0) - .getUseremail()); - } - @Test(expected = ResourceNotFoundException.class) - public void FA_saveputnotfound() - { - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("tiger", - "ILuvMath!", - "tiger@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - u2.getUseremails() - .add(new Useremail(u2, - "tiger@tiger.local")); - u2.setUserid(777); - - User saveU2 = userService.save(u2); - - System.out.println("*** DATA ***"); - System.out.println(saveU2); - System.out.println("*** DATA ***"); - - assertEquals("tiger@tiger.local", - saveU2.getUseremails() - .get(0) - .getUseremail()); - } - - @Test - public void FA_saveputfound() - { - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("mojo", - "ILuvMath!", - "mojo@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - u2.getUseremails() - .add(new Useremail(u2, - "mojo@corgi.local")); - u2.setUserid(4); - - User saveU2 = userService.save(u2); - - System.out.println("*** DATA ***"); - System.out.println(saveU2); - System.out.println("*** DATA ***"); - - assertEquals("mojo@corgi.local", - saveU2.getUseremails() - .get(0) - .getUseremail()); - } - - @Test - public void G_update() - { - Mockito.when(helperFunctions.isAuthorizedToMakeChange(anyString())) - .thenReturn(true); - - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("cinnamon", - "password", - "cinnamon@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - - u2.getUseremails() - .add(new Useremail(u2, - "cinnamon@mymail.thump")); - u2.getUseremails() - .add(new Useremail(u2, - "hops@mymail.thump")); - u2.getUseremails() - .add(new Useremail(u2, - "bunny@email.thump")); - - User updatedu2 = userService.update(u2, - 7); - - System.out.println("*** DATA ***"); - System.out.println(updatedu2); - System.out.println("*** DATA ***"); - - int checking = updatedu2.getUseremails() - .size() - 1; - assertEquals("bunny@email.thump", - updatedu2.getUseremails() - .get(checking) - .getUseremail()); - } - - @Test(expected = ResourceNotFoundException.class) - public void GB_updateNotCurrentUserNorAdmin() - { - Role r2 = new Role("user"); - r2.setRoleid(2); - - User u2 = new User("cinnamon", - "password", - "cinnamon@school.lambda"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - u2.getUseremails() - .add(new Useremail(u2, - "cinnamon@mymail.thump")); - u2.getUseremails() - .add(new Useremail(u2, - "hops@mymail.thump")); - u2.getUseremails() - .add(new Useremail(u2, - "bunny@email.thump")); - - Mockito.when(helperFunctions.isAuthorizedToMakeChange(anyString())) - .thenReturn(false); - - User updatedu2 = userService.update(u2, - 8); - - System.out.println("*** DATA ***"); - System.out.println(updatedu2); - System.out.println("*** DATA ***"); - - int checking = updatedu2.getUseremails() - .size() - 1; - assertEquals("bunny@email.thump", - updatedu2.getUseremails() - .get(checking) - .getUseremail()); - } } \ No newline at end of file From e0e9bc25c5f6969c831beaabcf78077b1fe1e475 Mon Sep 17 00:00:00 2001 From: George Hatzigeorgio Date: Fri, 2 Apr 2021 06:42:46 -0400 Subject: [PATCH 2/4] having some hiccups --- .../foundation/FoundationApplication.java | 2 +- .../com/lambdaschool/foundation/SeedData.java | 24 +- .../config/ResourceServerConfig.java | 11 +- .../controllers/OpenController.java | 2 +- .../controllers/ProductController.java | 59 +- .../controllers/UserController.java | 6 +- .../foundation/models/Product.java | 22 +- .../lambdaschool/foundation/models/User.java | 18 +- .../foundation/models/UserProduct.java | 68 ++ .../repository/ProductRepository.java | 1 + .../foundation/services/ProductService.java | 30 + .../services/ProductServiceImpl.java | 58 ++ .../services/SecurityUserServiceImpl.java | 2 +- .../foundation/services/UserServiceImpl.java | 2 +- .../src/main/resources/application.properties | 6 +- .../com/lambdaschool/foundation/SeedData.java | 262 +++--- .../UserControllerIntegrationTest.java | 332 ++++---- .../UserControllerUnitNoDBTest.java | 747 +++++++++--------- .../services/UserServiceImplNoDBTest.java | 79 -- 19 files changed, 936 insertions(+), 795 deletions(-) create mode 100644 foundation/src/main/java/com/lambdaschool/foundation/models/UserProduct.java create mode 100644 foundation/src/main/java/com/lambdaschool/foundation/services/ProductService.java create mode 100644 foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java diff --git a/foundation/src/main/java/com/lambdaschool/foundation/FoundationApplication.java b/foundation/src/main/java/com/lambdaschool/foundation/FoundationApplication.java index 843ffebfe..bf4b16908 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/FoundationApplication.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/FoundationApplication.java @@ -12,7 +12,7 @@ */ @EnableJpaAuditing @SpringBootApplication -@PropertySource(value = "file:/Users/lambdajohn/foundationconf.properties", ignoreResourceNotFound = true) +//@PropertySource(value = "file:/Users/lambdajohn/foundationconf.properties", ignoreResourceNotFound = true) public class FoundationApplication { /** diff --git a/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java b/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java index 0964146ea..b94eb7011 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java @@ -3,9 +3,11 @@ import com.github.javafaker.Faker; import com.github.javafaker.service.FakeValuesService; import com.github.javafaker.service.RandomService; +import com.lambdaschool.foundation.models.Product; import com.lambdaschool.foundation.models.Role; import com.lambdaschool.foundation.models.User; import com.lambdaschool.foundation.models.UserRoles; +import com.lambdaschool.foundation.services.ProductService; import com.lambdaschool.foundation.services.RoleService; import com.lambdaschool.foundation.services.UserService; import org.springframework.beans.factory.annotation.Autowired; @@ -44,6 +46,9 @@ public class SeedData @Autowired UserService userService; + @Autowired + ProductService productService; + /** * Generates test, seed data for our application * First a set of known data is seeded into our database. @@ -62,14 +67,17 @@ public void run(String[] args) throws roleService.deleteAll(); Role r1 = new Role("owner"); Role r2 = new Role("renter"); - + Product p1 = new Product("hpLaptop"); + Product p2 = new Product("digital camera") r1 = roleService.save(r1); r2 = roleService.save(r2); + p1 = productService.save(p1); + p2 = productService.save(p2); // admin, data, user - User u1 = new User("John","Malango", + User u1 = new User("Johnnie","John","Malango", "admin@lambdaschool.local","password"); u1.getRoles() .add(new UserRoles(u1, @@ -77,19 +85,21 @@ public void run(String[] args) throws u1.getRoles() .add(new UserRoles(u1, r2)); - + u1.getProducts() + .add(new Product(u1,p1)); userService.save(u1); // data, user - User u2 = new User("Marley","Copper", - "1234567", - "cinnamon@lambdaschool.local"); + User u2 = new User("Marley","Marley","Copper", + "cinnamon@lambdaschool.local", "1234567" + ); u2.getRoles() .add(new UserRoles(u2, r2)); - + u2.getProducts() + .add(new Product(u2,p2)); userService.save(u2); diff --git a/foundation/src/main/java/com/lambdaschool/foundation/config/ResourceServerConfig.java b/foundation/src/main/java/com/lambdaschool/foundation/config/ResourceServerConfig.java index cf3e5ec7d..ff6c52508 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/config/ResourceServerConfig.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/config/ResourceServerConfig.java @@ -51,26 +51,23 @@ public void configure(HttpSecurity http) "/swagger-ui.html", "/v2/api-docs", "/webjars/**", - "/createnewuser") + "/createnewuser", + "/users/login/" + ) .permitAll() - .antMatchers(HttpMethod.POST, - "/users/**") - .hasAnyRole("ADMIN") .antMatchers(HttpMethod.DELETE, "/users/**") .hasAnyRole("ADMIN") .antMatchers(HttpMethod.PUT, "/users/**") .hasAnyRole("ADMIN") - .antMatchers("/users/**", + .antMatchers( "/useremails/**", "/oauth/revoke-token", "/logout") .authenticated() .antMatchers("/roles/**") .hasAnyRole("ADMIN") - .anyRequest() - .denyAll() .and() .exceptionHandling() .accessDeniedHandler(new OAuth2AccessDeniedHandler()); diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/OpenController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/OpenController.java index 7a7bc848a..392a76059 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/OpenController.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/OpenController.java @@ -75,7 +75,7 @@ public ResponseEntity addSelf( // add the default role of user Set newRoles = new HashSet<>(); newRoles.add(new UserRoles(newuser, - roleService.findByName("user"))); + roleService.findByName("renter"))); newuser.setRoles(newRoles); newuser = userService.save(newuser); diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java index 0e7a4d9bc..692603e7c 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java @@ -1,9 +1,62 @@ package com.lambdaschool.foundation.controllers; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import com.lambdaschool.foundation.models.Product; +import com.lambdaschool.foundation.models.User; +import com.lambdaschool.foundation.services.ProductService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.List; @RestController -@RequestMapping("/products") public class ProductController { + @Autowired + private ProductService productService; + + @GetMapping(value = "/products", + produces = "application/json") + public ResponseEntity listAllProducts() { + List myProducts= productService.findAllProducts(); + return new ResponseEntity<>(myProducts, + HttpStatus.OK); + } + @GetMapping(value = "/products/{productId}", + produces = "application/json") + public ResponseEntity getProductById( + @PathVariable + Long productId) { + Product p = productService.findProductById(productId); + return new ResponseEntity<>(p, + HttpStatus.OK); + + + + } + @PutMapping(value = "/products/{productid}", + consumes = "application/json") + public ResponseEntity updateProduct( + @Valid + @RequestBody + Product updateProduct, + @PathVariable + long productid) + { + updateProduct.setProductid(productid); + productService.save(updateProduct); + + return new ResponseEntity<>(HttpStatus.OK); + } + + @DeleteMapping(value = "/products/{id}") + public ResponseEntity deleteUserById( + @PathVariable + long id) + { + productService.delete(id); + return new ResponseEntity<>(HttpStatus.OK); + } + } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java index 9333bf67d..51c0f4786 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java @@ -37,7 +37,7 @@ public class UserController * @return JSON list of all users with a status of OK * @see UserService#findAll() UserService.findAll() */ - @PreAuthorize("hasAnyRole('ADMIN')") + @PreAuthorize("hasAnyRole('owner','renter')") @GetMapping(value = "/users", produces = "application/json") public ResponseEntity listAllUsers() @@ -57,7 +57,7 @@ public ResponseEntity listAllUsers() */ @GetMapping(value = "/user/{userId}", produces = "application/json") - public ResponseEntity getProductById( + public ResponseEntity getUserById( @PathVariable Long userId) { @@ -116,7 +116,7 @@ public ResponseEntity getUserLikeName( * @throws URISyntaxException Exception if something does not work in creating the location header * @see UserService#save(User) UserService.save(User) */ - @PostMapping(value = "/user", + @PostMapping(value = "/user/register", consumes = "application/json") public ResponseEntity addNewUser( @Valid diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java b/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java index c9c2e7dd1..d1b33ac59 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java @@ -12,20 +12,26 @@ public class Product { private String product; @Id @GeneratedValue (strategy = GenerationType.AUTO) - private String productid; + private long productid; +@ManyToOne +@JoinColumn(name="userid",nullable = false) +private User user; public Product() { } - public Product(String product, String productid) { + public Product(String product, long productid, User user) { this.product = product; this.productid = productid; + this.user = user; } + + public String getProduct() { return product; } @@ -34,11 +40,19 @@ public void setProduct(String product) { this.product = product; } - public String getProductid() { + public long getProductid() { return productid; } - public void setProductid(String productid) { + public void setProductid(long productid) { this.productid = productid; } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/User.java b/foundation/src/main/java/com/lambdaschool/foundation/models/User.java index d000a3d18..cc6b20b32 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/User.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/User.java @@ -85,17 +85,16 @@ public User() { } - public User( String firstname, String lastname, @Email String email, String password, Set roles, Set products) { + public User( String username,String firstname, String lastname, @Email String email, String password) { + this.setUsername(username); this.firstname = firstname; this.lastname = lastname; this.email = email; - this.password = password; + this.setPassword(password); } - public User(String firstname, String lastname, String email, String password) { - super(); - } + /** * Given the params, create a new user object @@ -162,7 +161,14 @@ public String getPassword() { return password; } - /** + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } +/** * Getter for username * * @return the username (String) lowercase diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/UserProduct.java b/foundation/src/main/java/com/lambdaschool/foundation/models/UserProduct.java new file mode 100644 index 000000000..e23ece5ee --- /dev/null +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/UserProduct.java @@ -0,0 +1,68 @@ +package com.lambdaschool.foundation.models; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Objects; + +@Entity +@Table(name= "userproduct") +public class UserProduct extends Auditable implements Serializable { + + @Id + @ManyToOne + @JoinColumn(name = "userid") + @JsonIgnoreProperties(value = "product", allowSetters = true) + private User user; + + + @Id + @ManyToOne + @JoinColumn(name = "productid") + @JsonIgnoreProperties(value = "users", allowSetters = true) + private Product product; + + public UserProduct() { + } + + public UserProduct(User user, Product product) { + this.user = user; + this.product = product; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } + + @Override + public boolean equals(Object o) { + + if (this == o) { + return true; + } + if (!(o instanceof UserProduct)) { + return false; + } + UserProduct that = (UserProduct) o; + return ((this.user == null) ? 0 : this.user.getUserid()) == ((that.user == null) ? 0 : that.user.getUserid()) && + ((this.product == null) ? 0 : this.product.getProductid()) == ((that.product == null) ? 0 : that.product.getRoleid()); + } + + @Override + public int hashCode() { + return 37; + } +} \ No newline at end of file diff --git a/foundation/src/main/java/com/lambdaschool/foundation/repository/ProductRepository.java b/foundation/src/main/java/com/lambdaschool/foundation/repository/ProductRepository.java index 2967f8c68..373dcf4fe 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/repository/ProductRepository.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/repository/ProductRepository.java @@ -4,4 +4,5 @@ import org.springframework.data.repository.CrudRepository; public interface ProductRepository extends CrudRepository { + } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/ProductService.java b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductService.java new file mode 100644 index 000000000..89025894b --- /dev/null +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductService.java @@ -0,0 +1,30 @@ +package com.lambdaschool.foundation.services; + +import com.lambdaschool.foundation.models.Product; +import com.lambdaschool.foundation.models.Role; +import com.lambdaschool.foundation.models.User; +import com.lambdaschool.foundation.repository.ProductRepository; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; +import java.util.Set; + + +public interface ProductService { + + + Product save(Product product); + + Product findProductById(long id) ; + + + + void delete(long id); + + Product update( + Product updateProduct, + long id); + + List findAllProducts(); + +} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java new file mode 100644 index 000000000..ab11f80ae --- /dev/null +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java @@ -0,0 +1,58 @@ +package com.lambdaschool.foundation.services; + +import com.lambdaschool.foundation.models.Product; +import com.lambdaschool.foundation.repository.ProductRepository; +import com.lambdaschool.foundation.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +import javax.persistence.EntityNotFoundException; +import javax.transaction.Transactional; +import java.util.ArrayList; +import java.util.List; + +@Transactional +@Service(value = "productService") +public class ProductServiceImpl implements ProductService { + + @Autowired + private ProductRepository productrepos; + + @Override + public Product save(Product product) { + return productrepos.save(product); + } + + @Override + public Product findProductById(long id) { + return productrepos.findById(id) + .orElseThrow(() -> new EntityNotFoundException("Product " + id + " Not Found")); + } + + @Transactional + @Override + public void delete(long productid) { + if (productrepos.findById(productid).isPresent()) { + productrepos.deleteById(productid); + throw new EntityNotFoundException("product" + productid + "not found!"); + } else { + throw new EntityNotFoundException("product" + productid + "not found!"); + } + } + + @Override + public Product update(Product updateProduct, long id) { + return null; + } + + @Override + public List findAllProducts() { + List list = new ArrayList<>(); + productrepos.findAll() + .iterator() + .forEachRemaining(list::add); + return list; + } + +} diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/SecurityUserServiceImpl.java b/foundation/src/main/java/com/lambdaschool/foundation/services/SecurityUserServiceImpl.java index a86eb6c50..1bc729f36 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/SecurityUserServiceImpl.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/SecurityUserServiceImpl.java @@ -38,7 +38,7 @@ public UserDetails loadUserByUsername(String s) throws ResourceNotFoundException { - User user = userrepos.findByUsername(s.toLowerCase()); + User user = userrepos.findByUsername(s); if (user == null) { throw new ResourceNotFoundException("Invalid username or password."); diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/UserServiceImpl.java b/foundation/src/main/java/com/lambdaschool/foundation/services/UserServiceImpl.java index ea54d9cbe..76dcbc38d 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/UserServiceImpl.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/UserServiceImpl.java @@ -100,7 +100,7 @@ public User save(User user) newUser.setLastname(user.getLastname()); newUser.setPasswordNoEncrypt(user.getPassword()); newUser.setEmail(user.getEmail()); - + newUser.setUsername(user.getUsername()); newUser.getRoles() diff --git a/foundation/src/main/resources/application.properties b/foundation/src/main/resources/application.properties index d34128def..f1d6362ae 100644 --- a/foundation/src/main/resources/application.properties +++ b/foundation/src/main/resources/application.properties @@ -1,6 +1,6 @@ # Which DB to run -# local.run.db=H2 -local.run.db=POSTGRESQL +local.run.db=H2 +#local.run.db=POSTGRESQL # # Configurations useful for working with H2 # Configuration file for H2 console is in your home directory @@ -24,7 +24,7 @@ spring.jpa.open-in-view=true # What do with the schema # drop n create table again, good for testing spring.jpa.hibernate.ddl-auto=create -spring.datasource.initialization-mode=always +spring.datasource.initialization-mode=never command.line.runner.enabled=true # # Good for production! diff --git a/foundation/src/test/java/com/lambdaschool/foundation/SeedData.java b/foundation/src/test/java/com/lambdaschool/foundation/SeedData.java index 89918d9f9..f998e510d 100755 --- a/foundation/src/test/java/com/lambdaschool/foundation/SeedData.java +++ b/foundation/src/test/java/com/lambdaschool/foundation/SeedData.java @@ -30,143 +30,135 @@ matchIfMissing = true) @Component public class SeedData - implements CommandLineRunner { /** * Connects the Role Service to this process */ - @Autowired - RoleService roleService; - - /** - * Connects the user service to this process - */ - @Autowired - UserService userService; - - /** - * Generates test, seed data for our application - * First a set of known data is seeded into our database. - * Second a random set of data using Java Faker is seeded into our database. - * Note this process does not remove data from the database. So if data exists in the database - * prior to running this process, that data remains in the database. - * - * @param args The parameter is required by the parent interface but is not used in this process. - */ - @Transactional - @Override - public void run(String[] args) throws - Exception - { - userService.deleteAll(); - roleService.deleteAll(); - Role r1 = new Role("admin"); - Role r2 = new Role("user"); - Role r3 = new Role("data"); - - r1 = roleService.save(r1); - r2 = roleService.save(r2); - r3 = roleService.save(r3); - - // admin, data, user - User u1 = new User("admin", - "password", - "admin@lambdaschool.test"); - u1.getRoles() - .add(new UserRoles(u1, - r1)); - u1.getRoles() - .add(new UserRoles(u1, - r2)); - u1.getRoles() - .add(new UserRoles(u1, - r3)); - u1.getUseremails() - .add(new Useremail(u1, - "admin@email.test")); - u1.getUseremails() - .add(new Useremail(u1, - "admin@mymail.test")); - - userService.save(u1); - - // data, user - User u2 = new User("cinnamon", - "1234567", - "cinnamon@lambdaschool.test"); - u2.getRoles() - .add(new UserRoles(u2, - r2)); - u2.getRoles() - .add(new UserRoles(u2, - r3)); - u2.getUseremails() - .add(new Useremail(u2, - "cinnamon@mymail.test")); - u2.getUseremails() - .add(new Useremail(u2, - "hops@mymail.test")); - u2.getUseremails() - .add(new Useremail(u2, - "bunny@email.test")); - userService.save(u2); - - // user - User u3 = new User("barnbarn", - "ILuvM4th!", - "barnbarn@lambdaschool.test"); - u3.getRoles() - .add(new UserRoles(u3, - r2)); - u3.getUseremails() - .add(new Useremail(u3, - "barnbarn@email.test")); - userService.save(u3); - - User u4 = new User("puttat", - "password", - "puttat@school.lambda"); - u4.getRoles() - .add(new UserRoles(u4, - r2)); - userService.save(u4); - - User u5 = new User("misskitty", - "password", - "misskitty@school.lambda"); - u5.getRoles() - .add(new UserRoles(u5, - r2)); - userService.save(u5); - - if (false) - { - // using JavaFaker create a bunch of regular users - // https://www.baeldung.com/java-faker - // https://www.baeldung.com/regular-expressions-java - - FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-US"), - new RandomService()); - Faker nameFaker = new Faker(new Locale("en-US")); - - for (int i = 0; i < 25; i++) - { - new User(); - User fakeUser; - - fakeUser = new User(nameFaker.name() - .username(), - "password", - nameFaker.internet() - .emailAddress()); - fakeUser.getRoles() - .add(new UserRoles(fakeUser, - r2)); - fakeUser.getUseremails() - .add(new Useremail(fakeUser, - fakeValuesService.bothify("????##@gmail.com"))); - userService.save(fakeUser); - } - } - } +// @Autowired +// RoleService roleService; +// +// /** +// * Connects the user service to this process +// */ +// @Autowired +// UserService userService; +// +// /** +// * Generates test, seed data for our application +// * First a set of known data is seeded into our database. +// * Second a random set of data using Java Faker is seeded into our database. +// * Note this process does not remove data from the database. So if data exists in the database +// * prior to running this process, that data remains in the database. +// * +// * @param args The parameter is required by the parent interface but is not used in this process. +// */ +// @Transactional +// @Override +// public void run(String[] args) throws +// Exception +// { +// userService.deleteAll(); +// roleService.deleteAll(); +// Role r1 = new Role("renter"); +// Role r2 = new Role("owner"); +// +// +// r1 = roleService.save(r1); +// r2 = roleService.save(r2); +// +// +// // admin, data, user +// User u1 = new User("admin", +// "password", +// "admin@lambdaschool.test"); +// u1.getRoles() +// .add(new UserRoles(u1, +// r1)); +// +// u1.getEmail() +// .add(new email(u1, +// "admin@email.test")); +// +// +// userService.save(u1); +// +// // data, user +// User u2 = new User("cinnamon", +// "1234567", +// "cinnamon@lambdaschool.test"); +// u2.getRoles() +// .add(new UserRoles(u2, +// r2)); +// u2.getRoles() +// .add(new UserRoles(u2, +// r3)); +// u2.getUseremails() +// .add(new Useremail(u2, +// "cinnamon@mymail.test")); +// u2.getUseremails() +// .add(new Useremail(u2, +// "hops@mymail.test")); +// u2.getUseremails() +// .add(new Useremail(u2, +// "bunny@email.test")); +// userService.save(u2); +// +// // user +// User u3 = new User("barnbarn", +// "ILuvM4th!", +// "barnbarn@lambdaschool.test"); +// u3.getRoles() +// .add(new UserRoles(u3, +// r2)); +// u3.getUseremails() +// .add(new Useremail(u3, +// "barnbarn@email.test")); +// userService.save(u3); +// +// User u4 = new User("puttat", +// "password", +// "puttat@school.lambda"); +// u4.getRoles() +// .add(new UserRoles(u4, +// r2)); +// userService.save(u4); +// +// User u5 = new User("misskitty", +// "password", +// "misskitty@school.lambda"); +// u5.getRoles() +// .add(new UserRoles(u5, +// r2)); +// userService.save(u5); +// +// if (false) +// { +// // using JavaFaker create a bunch of regular users +// // https://www.baeldung.com/java-faker +// // https://www.baeldung.com/regular-expressions-java +// +// FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-US"), +// new RandomService()); +// Faker nameFaker = new Faker(new Locale("en-US")); +// +// for (int i = 0; i < 25; i++) +// { +// new User(); +// User fakeUser; +// +// fakeUser = new User(nameFaker.name() +// .username(), +// "password", +// nameFaker.internet() +// .emailAddress()); +// fakeUser.getRoles() +// .add(new UserRoles(fakeUser, +// r2)); +// fakeUser.getUseremails() +// .add(new Useremail(fakeUser, +// fakeValuesService.bothify("????##@gmail.com"))); +// userService.save(fakeUser); +// } +// } +// } } \ No newline at end of file diff --git a/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerIntegrationTest.java b/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerIntegrationTest.java index 0af49c2af..610e64565 100644 --- a/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerIntegrationTest.java +++ b/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerIntegrationTest.java @@ -33,170 +33,170 @@ @AutoConfigureMockMvc public class UserControllerIntegrationTest { - @Autowired - private WebApplicationContext webApplicationContext; - - private MockMvc mockMvc; - - - @Before - public void setUp() throws Exception - { - RestAssuredMockMvc.webAppContextSetup(webApplicationContext); - - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .apply(SecurityMockMvcConfigurers.springSecurity()) - .build(); - } - - @After - public void tearDown() throws Exception - { - } - - @Test - public void whenMeasuredResponseTime() throws - Exception - { - long time = System.currentTimeMillis(); - this.mockMvc.perform(get("/users/users")) - .andDo(print()); - long responseTime = (System.currentTimeMillis() - time); - - assertTrue("timestamp", - (responseTime < 5000L)); - } - - @Test - public void getAllUsers() throws - Exception - { - this.mockMvc.perform(get("/users/users")) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("cinnamon"))); - } - - @Test - public void getUserLikeName() throws - Exception - { - this.mockMvc.perform(get("/users/user/name/like/{userName}", - "kitty")) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("misskitty"))); - } - - @Test - public void getUserById() throws - Exception - { - this.mockMvc.perform(get("/users/user/{userid}", - 4)) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("admin"))); - } - - @Test - public void getUserByIdNotFound() throws - Exception - { - this.mockMvc.perform(get("/users/user/{userid}", - 100)) - .andDo(print()) - .andExpect(status().is4xxClientError()) - .andExpect(content().string(containsString("ResourceNotFoundException"))); - } - - @Test - public void getUserByName() throws - Exception - { - this.mockMvc.perform(get("/users/user/name/{userName}", - "admin")) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("admin"))); - } - - @Test - public void getUserByNameNotFound() throws - Exception - { - this.mockMvc.perform(get("/users/user/name/{userName}", - "rabbit")) - .andDo(print()) - .andExpect(status().is4xxClientError()) - .andExpect(content().string(containsString("ResourceNotFoundException"))); - } - - @Test - public void givenPostAUser() throws - Exception - { - mockMvc.perform(MockMvcRequestBuilders.post("/users/user") - .content("{\"username\": \"Ginger\", \"password\": \"EATEATEAT\", \"primaryemail\" : \"ginger@home.local\"}") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isCreated()) - .andExpect(MockMvcResultMatchers.header() - .exists("location")); - } - - @Test - public void givenPutAUser() throws - Exception - { - mockMvc.perform(MockMvcRequestBuilders.put("/users/user/11") - .content("{\"username\": \"stumps\", \"password\": \"EATEATEAT\", \"primaryemail\" : \"stumps@home.local\"}") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()); - } - - @Test - public void deleteUserById() throws - Exception - { - mockMvc.perform(MockMvcRequestBuilders.delete("/users/user/{id}", - 13)) - .andDo(print()) - .andExpect(status().is2xxSuccessful()); - } - - @Test - public void deleteUserByIdNotFound() throws - Exception - { - mockMvc.perform(MockMvcRequestBuilders.delete("/users/user/{id}", - 100)) - .andDo(print()) - .andExpect(status().is4xxClientError()); - } - - @Test - public void UpdateUser() throws - Exception - { - mockMvc.perform(MockMvcRequestBuilders.patch("/users/user/{userid}", - 7) - .content("{\"password\": \"EATEATEAT\"}") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()); - } - - @Test - public void getCurrentUserInfo() throws Exception - { - this.mockMvc.perform(get("/users/getuserinfo")) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("admin"))); - } +// @Autowired +// private WebApplicationContext webApplicationContext; +// +// private MockMvc mockMvc; +// +// +// @Before +// public void setUp() throws Exception +// { +// RestAssuredMockMvc.webAppContextSetup(webApplicationContext); +// +// mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) +// .apply(SecurityMockMvcConfigurers.springSecurity()) +// .build(); +// } +// +// @After +// public void tearDown() throws Exception +// { +// } +// +// @Test +// public void whenMeasuredResponseTime() throws +// Exception +// { +// long time = System.currentTimeMillis(); +// this.mockMvc.perform(get("/users/users")) +// .andDo(print()); +// long responseTime = (System.currentTimeMillis() - time); +// +// assertTrue("timestamp", +// (responseTime < 5000L)); +// } +// +// @Test +// public void getAllUsers() throws +// Exception +// { +// this.mockMvc.perform(get("/users/users")) +// .andDo(print()) +// .andExpect(status().isOk()) +// .andExpect(content().string(containsString("cinnamon"))); +// } +// +// @Test +// public void getUserLikeName() throws +// Exception +// { +// this.mockMvc.perform(get("/users/user/name/like/{userName}", +// "kitty")) +// .andDo(print()) +// .andExpect(status().isOk()) +// .andExpect(content().string(containsString("misskitty"))); +// } +// +// @Test +// public void getUserById() throws +// Exception +// { +// this.mockMvc.perform(get("/users/user/{userid}", +// 4)) +// .andDo(print()) +// .andExpect(status().isOk()) +// .andExpect(content().string(containsString("admin"))); +// } +// +// @Test +// public void getUserByIdNotFound() throws +// Exception +// { +// this.mockMvc.perform(get("/users/user/{userid}", +// 100)) +// .andDo(print()) +// .andExpect(status().is4xxClientError()) +// .andExpect(content().string(containsString("ResourceNotFoundException"))); +// } +// +// @Test +// public void getUserByName() throws +// Exception +// { +// this.mockMvc.perform(get("/users/user/name/{userName}", +// "admin")) +// .andDo(print()) +// .andExpect(status().isOk()) +// .andExpect(content().string(containsString("admin"))); +// } +// +// @Test +// public void getUserByNameNotFound() throws +// Exception +// { +// this.mockMvc.perform(get("/users/user/name/{userName}", +// "rabbit")) +// .andDo(print()) +// .andExpect(status().is4xxClientError()) +// .andExpect(content().string(containsString("ResourceNotFoundException"))); +// } +// +// @Test +// public void givenPostAUser() throws +// Exception +// { +// mockMvc.perform(MockMvcRequestBuilders.post("/users/user") +// .content("{\"username\": \"Ginger\", \"password\": \"EATEATEAT\", \"primaryemail\" : \"ginger@home.local\"}") +// .contentType(MediaType.APPLICATION_JSON) +// .accept(MediaType.APPLICATION_JSON)) +// .andDo(print()) +// .andExpect(status().isCreated()) +// .andExpect(MockMvcResultMatchers.header() +// .exists("location")); +// } +// +// @Test +// public void givenPutAUser() throws +// Exception +// { +// mockMvc.perform(MockMvcRequestBuilders.put("/users/user/11") +// .content("{\"username\": \"stumps\", \"password\": \"EATEATEAT\", \"primaryemail\" : \"stumps@home.local\"}") +// .contentType(MediaType.APPLICATION_JSON) +// .accept(MediaType.APPLICATION_JSON)) +// .andDo(print()) +// .andExpect(status().isOk()); +// } +// +// @Test +// public void deleteUserById() throws +// Exception +// { +// mockMvc.perform(MockMvcRequestBuilders.delete("/users/user/{id}", +// 13)) +// .andDo(print()) +// .andExpect(status().is2xxSuccessful()); +// } +// +// @Test +// public void deleteUserByIdNotFound() throws +// Exception +// { +// mockMvc.perform(MockMvcRequestBuilders.delete("/users/user/{id}", +// 100)) +// .andDo(print()) +// .andExpect(status().is4xxClientError()); +// } +// +// @Test +// public void UpdateUser() throws +// Exception +// { +// mockMvc.perform(MockMvcRequestBuilders.patch("/users/user/{userid}", +// 7) +// .content("{\"password\": \"EATEATEAT\"}") +// .contentType(MediaType.APPLICATION_JSON) +// .accept(MediaType.APPLICATION_JSON)) +// .andDo(print()) +// .andExpect(status().isOk()); +// } +// +// @Test +// public void getCurrentUserInfo() throws Exception +// { +// this.mockMvc.perform(get("/users/getuserinfo")) +// .andDo(print()) +// .andExpect(status().isOk()) +// .andExpect(content().string(containsString("admin"))); +// } } \ No newline at end of file diff --git a/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerUnitNoDBTest.java b/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerUnitNoDBTest.java index 00aff2d3b..fd2b1c6a6 100644 --- a/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerUnitNoDBTest.java +++ b/foundation/src/test/java/com/lambdaschool/foundation/controllers/UserControllerUnitNoDBTest.java @@ -50,382 +50,373 @@ @AutoConfigureMockMvc public class UserControllerUnitNoDBTest { - @Autowired - private WebApplicationContext webApplicationContext; - - private MockMvc mockMvc; - - @MockBean - private UserService userService; - - private List userList; - - @Before - public void setUp() throws Exception - { - userList = new ArrayList<>(); - - Role r1 = new Role("admin"); - r1.setRoleid(1); - Role r2 = new Role("user"); - r2.setRoleid(2); - Role r3 = new Role("data"); - r3.setRoleid(3); - - // admin, data, user - User u1 = new User("George","Hatzigeorgio", - "ILuvM4th!", - "admin@lambdaschool.test"); - u1.getRoles() - .add(new UserRoles(u1, - r1)); - u1.getRoles() - .add(new UserRoles(u1, - r2)); - u1.getRoles() - .add(new UserRoles(u1, - r3)); - - u1.getUseremails() - .add(new Useremail(u1, - "admin@email.test")); - u1.getUseremails() - .get(0) - .setUseremailid(10); - - u1.getUseremails() - .add(new Useremail(u1, - "admin@mymail.test")); - u1.getUseremails() - .get(1) - .setUseremailid(11); - - u1.setUserid(101); - userList.add(u1); - - // data, user - ArrayList datas = new ArrayList<>(); - User u2 = new User("cinnamon", - "1234567", - "cinnamon@lambdaschool.test"); - u1.getRoles() - .add(new UserRoles(u2, - r2)); - u1.getRoles() - .add(new UserRoles(u2, - r3)); - - u2.getUseremails() - .add(new Useremail(u2, - "cinnamon@mymail.test")); - u2.getUseremails() - .get(0) - .setUseremailid(20); - - u2.getUseremails() - .add(new Useremail(u2, - "hops@mymail.test")); - u2.getUseremails() - .get(1) - .setUseremailid(21); - - u2.getUseremails() - .add(new Useremail(u2, - "bunny@email.test")); - u2.getUseremails() - .get(2) - .setUseremailid(22); - - u2.setUserid(102); - userList.add(u2); - - // user - User u3 = new User("testingbarn", - "ILuvM4th!", - "testingbarn@school.lambda"); - u3.getRoles() - .add(new UserRoles(u3, - r1)); - - u3.getUseremails() - .add(new Useremail(u3, - "barnbarn@email.test")); - u3.getUseremails() - .get(0) - .setUseremailid(30); - - u3.setUserid(103); - userList.add(u3); - - User u4 = new User("testingcat", - "password", - "testingcat@school.lambda"); - u4.getRoles() - .add(new UserRoles(u4, - r2)); - - u4.setUserid(104); - userList.add(u4); - - User u5 = new User("testingdog", - "password", - "testingdog@school.lambda"); - u4.getRoles() - .add(new UserRoles(u5, - r2)); - - u5.setUserid(105); - userList.add(u5); - - RestAssuredMockMvc.webAppContextSetup(webApplicationContext); - - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .apply(SecurityMockMvcConfigurers.springSecurity()) - .build(); - } - - @After - public void tearDown() throws Exception - { - } - - @Test - public void listAllUsers() throws - Exception - { - String apiUrl = "/users/users"; - - Mockito.when(userService.findAll()) - .thenReturn(userList); - - RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) - .accept(MediaType.APPLICATION_JSON); - - // the following actually performs a real controller call - MvcResult r = mockMvc.perform(rb) - .andReturn(); // this could throw an exception - String tr = r.getResponse() - .getContentAsString(); - - ObjectMapper mapper = new ObjectMapper(); - String er = mapper.writeValueAsString(userList); - - System.out.println("Expect: " + er); - System.out.println("Actual: " + tr); - - assertEquals("Rest API Returns List", - er, - tr); - } - - @Test - public void listUsersNameContaining() throws - Exception - { - String apiUrl = "/users/user/name/like/cin"; - - Mockito.when(userService.findByNameContaining(any(String.class))) - .thenReturn(userList); - - RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) - .accept(MediaType.APPLICATION_JSON); - - // the following actually performs a real controller call - MvcResult r = mockMvc.perform(rb) - .andReturn(); // this could throw an exception - String tr = r.getResponse() - .getContentAsString(); - - ObjectMapper mapper = new ObjectMapper(); - String er = mapper.writeValueAsString(userList); - - System.out.println("Expect: " + er); - System.out.println("Actual: " + tr); - - assertEquals("Rest API Returns List", - er, - tr); - } - - @Test - public void getUserById() throws - Exception - { - String apiUrl = "/users/user/12"; - - Mockito.when(userService.findUserById(12)) - .thenReturn(userList.get(1)); - - RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) - .accept(MediaType.APPLICATION_JSON); - MvcResult r = mockMvc.perform(rb) - .andReturn(); // this could throw an exception - String tr = r.getResponse() - .getContentAsString(); - - ObjectMapper mapper = new ObjectMapper(); - String er = mapper.writeValueAsString(userList.get(1)); - - System.out.println("Expect: " + er); - System.out.println("Actual: " + tr); - - assertEquals("Rest API Returns List", - er, - tr); - } - - @Test - public void getUserByIdNotFound() throws - Exception - { - String apiUrl = "/users/user/77"; - - Mockito.when(userService.findUserById(77)) - .thenReturn(null); - - RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) - .accept(MediaType.APPLICATION_JSON); - MvcResult r = mockMvc.perform(rb) - .andReturn(); // this could throw an exception - String tr = r.getResponse() - .getContentAsString(); - - String er = ""; - - System.out.println("Expect: " + er); - System.out.println("Actual: " + tr); - - assertEquals("Rest API Returns List", - er, - tr); - } - - @Test - public void getUserByName() throws - Exception - { - String apiUrl = "/users/user/name/testing"; - - Mockito.when(userService.findByName("testing")) - .thenReturn(userList.get(0)); - - RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) - .accept(MediaType.APPLICATION_JSON); - MvcResult r = mockMvc.perform(rb) - .andReturn(); // this could throw an exception - String tr = r.getResponse() - .getContentAsString(); - - ObjectMapper mapper = new ObjectMapper(); - String er = mapper.writeValueAsString(userList.get(0)); - - System.out.println("Expect: " + er); - System.out.println("Actual: " + tr); - - assertEquals("Rest API Returns List", - er, - tr); - } - - @Test - public void addNewUser() throws - Exception - { - String apiUrl = "/users/user"; - - Mockito.when(userService.save(any(User.class))) - .thenReturn(userList.get(0)); - - RequestBuilder rb = MockMvcRequestBuilders.post(apiUrl) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .content("{\"username\": \"tiger\", \"password\": \"ILuvM4th!\", \"primaryemail\" : \"tiger@home.local\"}"); - - mockMvc.perform(rb) - .andExpect(status().isCreated()) - .andDo(MockMvcResultHandlers.print()); - } - - @Test - public void updateUser() throws - Exception - { - String apiUrl = "/users/user/{userid}"; - - Mockito.when(userService.update(any(User.class), - any(Long.class))) - .thenReturn(userList.get(0)); - - RequestBuilder rb = MockMvcRequestBuilders.put(apiUrl, - 100L) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .content("{\"username\": \"tigerUpdated\", \"password\": \"EATEATEAT\", \"primaryemail\" : \"ginger@home.local\"}"); - - mockMvc.perform(rb) - .andExpect(status().is2xxSuccessful()) - .andDo(MockMvcResultHandlers.print()); - } - - @Test - public void updateUserPatch() throws - Exception - { - String apiUrl = "/users/user/{userid}"; - - Mockito.when(userService.update(any(User.class), - any(Long.class))) - .thenReturn(userList.get(0)); - - RequestBuilder rb = MockMvcRequestBuilders.patch(apiUrl, - 100L) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .content("{\"username\": \"tigerUpdated\", \"password\": \"EATEATEAT\", \"primaryemail\" : \"ginger@home.local\"}"); - - mockMvc.perform(rb) - .andExpect(status().is2xxSuccessful()) - .andDo(MockMvcResultHandlers.print()); - } - - @Test - public void deleteUserById() throws - Exception - { - String apiUrl = "/users/user/{userid}"; - - RequestBuilder rb = MockMvcRequestBuilders.delete(apiUrl, - "3") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON); - mockMvc.perform(rb) - .andExpect(status().is2xxSuccessful()) - .andDo(MockMvcResultHandlers.print()); - } - - @Test - public void getCurrentUserInfo() throws Exception - { - String apiUrl = "/users/getuserinfo"; - - Mockito.when(userService.findByName(anyString())) - .thenReturn(userList.get(0)); - - RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) - .accept(MediaType.APPLICATION_JSON); - MvcResult r = mockMvc.perform(rb) - .andReturn(); // this could throw an exception - String tr = r.getResponse() - .getContentAsString(); - - ObjectMapper mapper = new ObjectMapper(); - String er = mapper.writeValueAsString(userList.get(0)); - - System.out.println("Expect: " + er); - System.out.println("Actual: " + tr); - - assertEquals("Rest API Returns List", - er, - tr); - } +// @Autowired +// private WebApplicationContext webApplicationContext; +// +// private MockMvc mockMvc; +// +// @MockBean +// private UserService userService; +// +// private List userList; +// +// @Before +// public void setUp() throws Exception +// { +// userList = new ArrayList<>(); +// +// Role r1 = new Role("admin"); +// r1.setRoleid(1); +// Role r2 = new Role("user"); +// r2.setRoleid(2); +// Role r3 = new Role("data"); +// r3.setRoleid(3); +// +// // admin, data, user +// User u1 = new User("George","Hatzigeorgio", +// "ILuvM4th!", +// "admin@lambdaschool.test"); +// u1.getRoles() +// .add(new UserRoles(u1, +// r1)); +// u1.getRoles() +// .add(new UserRoles(u1, +// r2)); +// u1.getRoles() +// .add(new UserRoles(u1, +// r3)); +// +// u1.getEmail() +// .add(new email(u1, +// "admin@email.test")); +// +// +// u1.setUserid(101); +// userList.add(u1); +// +// // data, user +// ArrayList datas = new ArrayList<>(); +// User u2 = new User("cinnamon", +// "1234567", +// "cinnamon@lambdaschool.test"); +// u1.getRoles() +// .add(new UserRoles(u2, +// r2)); +// u1.getRoles() +// .add(new UserRoles(u2, +// r3)); +// +// u2.getUseremails() +// .add(new Useremail(u2, +// "cinnamon@mymail.test")); +// u2.getUseremails() +// .get(0) +// .setUseremailid(20); +// +// u2.getUseremails() +// .add(new Useremail(u2, +// "hops@mymail.test")); +// u2.getUseremails() +// .get(1) +// .setUseremailid(21); +// +// u2.getUseremails() +// .add(new Useremail(u2, +// "bunny@email.test")); +// u2.getUseremails() +// .get(2) +// .setUseremailid(22); +// +// u2.setUserid(102); +// userList.add(u2); +// +// // user +// User u3 = new User("testingbarn", +// "ILuvM4th!", +// "testingbarn@school.lambda"); +// u3.getRoles() +// .add(new UserRoles(u3, +// r1)); +// +// u3.getUseremails() +// .add(new Useremail(u3, +// "barnbarn@email.test")); +// u3.getUseremails() +// .get(0) +// .setUseremailid(30); +// +// u3.setUserid(103); +// userList.add(u3); +// +// User u4 = new User("testingcat", +// "password", +// "testingcat@school.lambda"); +// u4.getRoles() +// .add(new UserRoles(u4, +// r2)); +// +// u4.setUserid(104); +// userList.add(u4); +// +// User u5 = new User("testingdog", +// "password", +// "testingdog@school.lambda"); +// u4.getRoles() +// .add(new UserRoles(u5, +// r2)); +// +// u5.setUserid(105); +// userList.add(u5); +// +// RestAssuredMockMvc.webAppContextSetup(webApplicationContext); +// +// mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) +// .apply(SecurityMockMvcConfigurers.springSecurity()) +// .build(); +// } +// +// @After +// public void tearDown() throws Exception +// { +// } +// +// @Test +// public void listAllUsers() throws +// Exception +// { +// String apiUrl = "/users/users"; +// +// Mockito.when(userService.findAll()) +// .thenReturn(userList); +// +// RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) +// .accept(MediaType.APPLICATION_JSON); +// +// // the following actually performs a real controller call +// MvcResult r = mockMvc.perform(rb) +// .andReturn(); // this could throw an exception +// String tr = r.getResponse() +// .getContentAsString(); +// +// ObjectMapper mapper = new ObjectMapper(); +// String er = mapper.writeValueAsString(userList); +// +// System.out.println("Expect: " + er); +// System.out.println("Actual: " + tr); +// +// assertEquals("Rest API Returns List", +// er, +// tr); +// } +// +// @Test +// public void listUsersNameContaining() throws +// Exception +// { +// String apiUrl = "/users/user/name/like/cin"; +// +// Mockito.when(userService.findByNameContaining(any(String.class))) +// .thenReturn(userList); +// +// RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) +// .accept(MediaType.APPLICATION_JSON); +// +// // the following actually performs a real controller call +// MvcResult r = mockMvc.perform(rb) +// .andReturn(); // this could throw an exception +// String tr = r.getResponse() +// .getContentAsString(); +// +// ObjectMapper mapper = new ObjectMapper(); +// String er = mapper.writeValueAsString(userList); +// +// System.out.println("Expect: " + er); +// System.out.println("Actual: " + tr); +// +// assertEquals("Rest API Returns List", +// er, +// tr); +// } +// +// @Test +// public void getUserById() throws +// Exception +// { +// String apiUrl = "/users/user/12"; +// +// Mockito.when(userService.findUserById(12)) +// .thenReturn(userList.get(1)); +// +// RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) +// .accept(MediaType.APPLICATION_JSON); +// MvcResult r = mockMvc.perform(rb) +// .andReturn(); // this could throw an exception +// String tr = r.getResponse() +// .getContentAsString(); +// +// ObjectMapper mapper = new ObjectMapper(); +// String er = mapper.writeValueAsString(userList.get(1)); +// +// System.out.println("Expect: " + er); +// System.out.println("Actual: " + tr); +// +// assertEquals("Rest API Returns List", +// er, +// tr); +// } +// +// @Test +// public void getUserByIdNotFound() throws +// Exception +// { +// String apiUrl = "/users/user/77"; +// +// Mockito.when(userService.findUserById(77)) +// .thenReturn(null); +// +// RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) +// .accept(MediaType.APPLICATION_JSON); +// MvcResult r = mockMvc.perform(rb) +// .andReturn(); // this could throw an exception +// String tr = r.getResponse() +// .getContentAsString(); +// +// String er = ""; +// +// System.out.println("Expect: " + er); +// System.out.println("Actual: " + tr); +// +// assertEquals("Rest API Returns List", +// er, +// tr); +// } +// +// @Test +// public void getUserByName() throws +// Exception +// { +// String apiUrl = "/users/user/name/testing"; +// +// Mockito.when(userService.findByName("testing")) +// .thenReturn(userList.get(0)); +// +// RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) +// .accept(MediaType.APPLICATION_JSON); +// MvcResult r = mockMvc.perform(rb) +// .andReturn(); // this could throw an exception +// String tr = r.getResponse() +// .getContentAsString(); +// +// ObjectMapper mapper = new ObjectMapper(); +// String er = mapper.writeValueAsString(userList.get(0)); +// +// System.out.println("Expect: " + er); +// System.out.println("Actual: " + tr); +// +// assertEquals("Rest API Returns List", +// er, +// tr); +// } +// +// @Test +// public void addNewUser() throws +// Exception +// { +// String apiUrl = "/users/user"; +// +// Mockito.when(userService.save(any(User.class))) +// .thenReturn(userList.get(0)); +// +// RequestBuilder rb = MockMvcRequestBuilders.post(apiUrl) +// .contentType(MediaType.APPLICATION_JSON) +// .accept(MediaType.APPLICATION_JSON) +// .content("{\"username\": \"tiger\", \"password\": \"ILuvM4th!\", \"primaryemail\" : \"tiger@home.local\"}"); +// +// mockMvc.perform(rb) +// .andExpect(status().isCreated()) +// .andDo(MockMvcResultHandlers.print()); +// } +// +// @Test +// public void updateUser() throws +// Exception +// { +// String apiUrl = "/users/user/{userid}"; +// +// Mockito.when(userService.update(any(User.class), +// any(Long.class))) +// .thenReturn(userList.get(0)); +// +// RequestBuilder rb = MockMvcRequestBuilders.put(apiUrl, +// 100L) +// .contentType(MediaType.APPLICATION_JSON) +// .accept(MediaType.APPLICATION_JSON) +// .content("{\"username\": \"tigerUpdated\", \"password\": \"EATEATEAT\", \"primaryemail\" : \"ginger@home.local\"}"); +// +// mockMvc.perform(rb) +// .andExpect(status().is2xxSuccessful()) +// .andDo(MockMvcResultHandlers.print()); +// } +// +// @Test +// public void updateUserPatch() throws +// Exception +// { +// String apiUrl = "/users/user/{userid}"; +// +// Mockito.when(userService.update(any(User.class), +// any(Long.class))) +// .thenReturn(userList.get(0)); +// +// RequestBuilder rb = MockMvcRequestBuilders.patch(apiUrl, +// 100L) +// .contentType(MediaType.APPLICATION_JSON) +// .accept(MediaType.APPLICATION_JSON) +// .content("{\"username\": \"tigerUpdated\", \"password\": \"EATEATEAT\", \"primaryemail\" : \"ginger@home.local\"}"); +// +// mockMvc.perform(rb) +// .andExpect(status().is2xxSuccessful()) +// .andDo(MockMvcResultHandlers.print()); +// } +// +// @Test +// public void deleteUserById() throws +// Exception +// { +// String apiUrl = "/users/user/{userid}"; +// +// RequestBuilder rb = MockMvcRequestBuilders.delete(apiUrl, +// "3") +// .contentType(MediaType.APPLICATION_JSON) +// .accept(MediaType.APPLICATION_JSON); +// mockMvc.perform(rb) +// .andExpect(status().is2xxSuccessful()) +// .andDo(MockMvcResultHandlers.print()); +// } +// +// @Test +// public void getCurrentUserInfo() throws Exception +// { +// String apiUrl = "/users/getuserinfo"; +// +// Mockito.when(userService.findByName(anyString())) +// .thenReturn(userList.get(0)); +// +// RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) +// .accept(MediaType.APPLICATION_JSON); +// MvcResult r = mockMvc.perform(rb) +// .andReturn(); // this could throw an exception +// String tr = r.getResponse() +// .getContentAsString(); +// +// ObjectMapper mapper = new ObjectMapper(); +// String er = mapper.writeValueAsString(userList.get(0)); +// +// System.out.println("Expect: " + er); +// System.out.println("Actual: " + tr); +// +// assertEquals("Rest API Returns List", +// er, +// tr); +// } } \ No newline at end of file diff --git a/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplNoDBTest.java b/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplNoDBTest.java index e2a23cdce..7031797af 100644 --- a/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplNoDBTest.java +++ b/foundation/src/test/java/com/lambdaschool/foundation/services/UserServiceImplNoDBTest.java @@ -44,84 +44,5 @@ public class UserServiceImplNoDBTest private List userList; - @Before - public void setUp() throws Exception - { - userList = new ArrayList<>(); - Role r1 = new Role("renter"); - r1.setRoleid(1); - Role r2 = new Role("owner"); - r2.setRoleid(2); - - - // - User u1 = new User("admin", - "ILuvM4th!", - "admin@lambdaschool.test"); - u1.getRoles() - .add(new UserRoles(u1, - r1)); - u1.getRoles() - .add(new UserRoles(u1, - r2)); - u1.getRoles() - .add(new UserRoles(u1, - r3)); - - u1.getUseremails() - .add(new Useremail(u1, - "admin@email.test")); - u1.getUseremails() - .get(0) - .setUseremailid(10); - - u1.getUseremails() - .add(new Useremail(u1, - "admin@mymail.test")); - u1.getUseremails() - .get(1) - .setUseremailid(11); - - u1.setUserid(101); - userList.add(u1); - - // data, user - ArrayList datas = new ArrayList<>(); - User u2 = new User("cinnamon", - "1234567", - "cinnamon@lambdaschool.test"); - u1.getRoles() - .add(new UserRoles(u2, - r2)); - u1.getRoles() - .add(new UserRoles(u2, - r3)); - - u2.getUseremails() - .add(new Useremail(u2, - "cinnamon@mymail.test")); - u2.getUseremails() - .get(0) - .setUseremailid(20); - - u2.getUseremails() - .add(new Useremail(u2, - "hops@mymail.test")); - u2.getUseremails() - .get(1) - .setUseremailid(21); - - u2.getUseremails() - .add(new Useremail(u2, - "bunny@email.test")); - u2.getUseremails() - .get(2) - .setUseremailid(22); - - u2.setUserid(102); - userList.add(u2); - - // user - } \ No newline at end of file From f5f59648aa3f24f81a6b793fd26c1e3cb655095e Mon Sep 17 00:00:00 2001 From: George Hatzigeorgio Date: Fri, 2 Apr 2021 14:39:24 -0400 Subject: [PATCH 3/4] routes working except update and delete --- .../com/lambdaschool/foundation/SeedData.java | 27 +++--- .../controllers/ProductController.java | 9 +- .../controllers/UserController.java | 2 +- .../foundation/models/Product.java | 24 ++--- .../foundation/models/ProductId.java | 63 ------------- .../lambdaschool/foundation/models/User.java | 6 +- .../foundation/models/UserProduct.java | 3 +- .../foundation/models/UserProductId.java | 60 +++++++++++++ .../foundation/services/ProductService.java | 7 +- .../services/ProductServiceImpl.java | 90 ++++++++++++------- .../src/main/resources/application.properties | 2 +- 11 files changed, 155 insertions(+), 138 deletions(-) delete mode 100644 foundation/src/main/java/com/lambdaschool/foundation/models/ProductId.java create mode 100644 foundation/src/main/java/com/lambdaschool/foundation/models/UserProductId.java diff --git a/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java b/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java index b94eb7011..5f8a3f519 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/SeedData.java @@ -3,10 +3,7 @@ import com.github.javafaker.Faker; import com.github.javafaker.service.FakeValuesService; import com.github.javafaker.service.RandomService; -import com.lambdaschool.foundation.models.Product; -import com.lambdaschool.foundation.models.Role; -import com.lambdaschool.foundation.models.User; -import com.lambdaschool.foundation.models.UserRoles; +import com.lambdaschool.foundation.models.*; import com.lambdaschool.foundation.services.ProductService; import com.lambdaschool.foundation.services.RoleService; import com.lambdaschool.foundation.services.UserService; @@ -67,14 +64,12 @@ public void run(String[] args) throws roleService.deleteAll(); Role r1 = new Role("owner"); Role r2 = new Role("renter"); - Product p1 = new Product("hpLaptop"); - Product p2 = new Product("digital camera") r1 = roleService.save(r1); r2 = roleService.save(r2); - p1 = productService.save(p1); - p2 = productService.save(p2); + + // admin, data, user User u1 = new User("Johnnie","John","Malango", @@ -85,11 +80,9 @@ public void run(String[] args) throws u1.getRoles() .add(new UserRoles(u1, r2)); - u1.getProducts() - .add(new Product(u1,p1)); - userService.save(u1); + u1 = userService.save(u1); // data, user User u2 = new User("Marley","Marley","Copper", @@ -98,13 +91,17 @@ public void run(String[] args) throws u2.getRoles() .add(new UserRoles(u2, r2)); - u2.getProducts() - .add(new Product(u2,p2)); - userService.save(u2); + u2 = userService.save(u2); + Product p1 = new Product("hp laptop"); + Product p2 = new Product ("digital camera"); + p1.getUsers().add(new UserProduct(u1,p1)); + p1 = productService.save(p1); + p2.getUsers().add(new UserProduct(u2,p2)); + p2 = productService.save(p2); - // using JavaFaker create a bunch of regular users + // using JavaFaker create a bunch of regular users // https://www.baeldung.com/java-faker // https://www.baeldung.com/regular-expressions-java diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java index 692603e7c..ef1305642 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java @@ -12,6 +12,7 @@ import java.util.List; @RestController +@RequestMapping("/products") public class ProductController { @Autowired private ProductService productService; @@ -23,7 +24,7 @@ public ResponseEntity listAllProducts() { return new ResponseEntity<>(myProducts, HttpStatus.OK); } - @GetMapping(value = "/products/{productId}", + @GetMapping(value = "/product/{productId}", produces = "application/json") public ResponseEntity getProductById( @PathVariable @@ -35,7 +36,7 @@ public ResponseEntity getProductById( } - @PutMapping(value = "/products/{productid}", + @PutMapping(value = "/product/{productid}", consumes = "application/json") public ResponseEntity updateProduct( @Valid @@ -50,8 +51,8 @@ public ResponseEntity updateProduct( return new ResponseEntity<>(HttpStatus.OK); } - @DeleteMapping(value = "/products/{id}") - public ResponseEntity deleteUserById( + @DeleteMapping(value = "/product/{id}") + public ResponseEntity delete( @PathVariable long id) { diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java index 51c0f4786..67c750200 100755 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/UserController.java @@ -37,7 +37,7 @@ public class UserController * @return JSON list of all users with a status of OK * @see UserService#findAll() UserService.findAll() */ - @PreAuthorize("hasAnyRole('owner','renter')") +// @PreAuthorize("hasAnyRole('owner','renter')") @GetMapping(value = "/users", produces = "application/json") public ResponseEntity listAllUsers() diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java b/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java index d1b33ac59..43e73667f 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java @@ -1,9 +1,10 @@ package com.lambdaschool.foundation.models; -import net.bytebuddy.dynamic.loading.InjectionClassLoader; -import org.springframework.boot.autoconfigure.web.ResourceProperties; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; +import java.util.HashSet; +import java.util.Set; @Entity @Table(name = "products") @@ -15,19 +16,18 @@ public class Product { private long productid; -@ManyToOne -@JoinColumn(name="userid",nullable = false) -private User user; +@OneToMany(mappedBy="product",cascade = CascadeType.ALL,orphanRemoval = true) +@JsonIgnoreProperties(value = "products") +private Set users = new HashSet<>(); public Product() { } - public Product(String product, long productid, User user) { + public Product(String product ) { this.product = product; - this.productid = productid; - this.user = user; + } @@ -48,11 +48,11 @@ public void setProductid(long productid) { this.productid = productid; } - public User getUser() { - return user; + public Set getUsers() { + return users; } - public void setUser(User user) { - this.user = user; + public void setUsers(Set userproducts) { + this.users = userproducts; } } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/ProductId.java b/foundation/src/main/java/com/lambdaschool/foundation/models/ProductId.java deleted file mode 100644 index bae1d2585..000000000 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/ProductId.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.lambdaschool.foundation.models; - -import java.io.Serializable; -import java.util.Objects; - -public class ProductId implements Serializable { - private long user; - - private long product; - - public ProductId() { - } - - public ProductId(long user, long product) { - this.user = user; - this.product = product; - } - - public long getUser() { - return user; - } - - public void setUser(long user) { - this.user = user; - } - - public long getProduct() { - return product; - } - - public void setProduct(long product) { - this.product = product; - } - - @Override - public boolean equals(Object o) - { - if(this == o) - { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ProductId that = (ProductId) o; - return this.user == that.user && - this.product == that.product; - - - - - - - - - - } - - @Override - public int hashCode() { - return 37; - } -} \ No newline at end of file diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/User.java b/foundation/src/main/java/com/lambdaschool/foundation/models/User.java index cc6b20b32..46dbc3b22 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/User.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/User.java @@ -76,7 +76,7 @@ public class User @OneToMany(mappedBy = "user",cascade = CascadeType.ALL,orphanRemoval = true) @JsonIgnoreProperties(value = "user", allowSetters = true) - private Set products = new HashSet<>(); + private Set products = new HashSet<>(); /** * Default constructor used primarily by the JPA. @@ -125,11 +125,11 @@ public void setUserid(long userid) { this.userid = userid; } - public Set getProducts() { + public Set getProducts() { return products; } - public void setProducts(Set products) { + public void setProducts(Set products) { this.products = products; } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/UserProduct.java b/foundation/src/main/java/com/lambdaschool/foundation/models/UserProduct.java index e23ece5ee..f934d88d8 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/UserProduct.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/UserProduct.java @@ -8,6 +8,7 @@ @Entity @Table(name= "userproduct") +@IdClass(UserProductId.class) public class UserProduct extends Auditable implements Serializable { @Id @@ -58,7 +59,7 @@ public boolean equals(Object o) { } UserProduct that = (UserProduct) o; return ((this.user == null) ? 0 : this.user.getUserid()) == ((that.user == null) ? 0 : that.user.getUserid()) && - ((this.product == null) ? 0 : this.product.getProductid()) == ((that.product == null) ? 0 : that.product.getRoleid()); + ((this.product == null) ? 0 : this.product.getProductid()) == ((that.product == null) ? 0 : that.product.getProductid()); } @Override diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/UserProductId.java b/foundation/src/main/java/com/lambdaschool/foundation/models/UserProductId.java new file mode 100644 index 000000000..f6b8ce9e6 --- /dev/null +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/UserProductId.java @@ -0,0 +1,60 @@ +package com.lambdaschool.foundation.models; + +import javax.persistence.Embeddable; +import java.io.Serializable; +@Embeddable + public class UserProductId implements Serializable { + + private long user; + + private long product; + + + + + public long getUser() { + return user; + } + + public void setUser(long user) { + this.user = user; + } + + public long getProduct() { + return product; + } + + public void setProduct(long product) { + this.product = product; + } + + @Override + public boolean equals(Object o) + { + if(this == o) + { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + UserProductId that = (UserProductId) o; + return this.user == that.user && + this.product== that.product; + + + + + + + + + } + + @Override + public int hashCode() { + return 37; + } + + } diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/ProductService.java b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductService.java index 89025894b..ae37c3400 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/ProductService.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductService.java @@ -1,13 +1,8 @@ package com.lambdaschool.foundation.services; import com.lambdaschool.foundation.models.Product; -import com.lambdaschool.foundation.models.Role; -import com.lambdaschool.foundation.models.User; -import com.lambdaschool.foundation.repository.ProductRepository; -import org.springframework.beans.factory.annotation.Autowired; import java.util.List; -import java.util.Set; public interface ProductService { @@ -19,7 +14,7 @@ public interface ProductService { - void delete(long id); + Product delete(long id); Product update( Product updateProduct, diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java index ab11f80ae..1ea1aa617 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java @@ -1,8 +1,8 @@ package com.lambdaschool.foundation.services; -import com.lambdaschool.foundation.models.Product; +import com.lambdaschool.foundation.exceptions.ResourceNotFoundException; +import com.lambdaschool.foundation.models.*; import com.lambdaschool.foundation.repository.ProductRepository; -import com.lambdaschool.foundation.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -15,44 +15,70 @@ @Transactional @Service(value = "productService") public class ProductServiceImpl implements ProductService { - + @Autowired + private UserService userService; @Autowired private ProductRepository productrepos; + @Autowired + private ProductService productService; + @Override public Product save(Product product) { - return productrepos.save(product); - } - @Override - public Product findProductById(long id) { - return productrepos.findById(id) - .orElseThrow(() -> new EntityNotFoundException("Product " + id + " Not Found")); - } + Product newProduct = new Product(); - @Transactional - @Override - public void delete(long productid) { - if (productrepos.findById(productid).isPresent()) { - productrepos.deleteById(productid); - throw new EntityNotFoundException("product" + productid + "not found!"); - } else { - throw new EntityNotFoundException("product" + productid + "not found!"); + if (product.getProductid() != 0) { + productrepos.findById(product.getProductid()) + .orElseThrow(() -> new ResourceNotFoundException("User id " + product.getProductid() + " not found!")); + newProduct.setProductid(product.getProductid()); + } + newProduct.setProduct(product.getProduct()); + newProduct.setProductid(product.getProductid()); + + + newProduct.getUsers() + .clear(); + for (UserProduct ur : product.getUsers()) { + User user = ur.getUser(); + user = userService.findUserById(user.getUserid()); + newProduct.getUsers() + .add(new UserProduct(user, + newProduct)); + } + + + return productrepos.save(newProduct); + } + @Override + public Product findProductById ( long id){ + return productrepos.findById(id) + .orElseThrow(() -> new EntityNotFoundException("Product " + id + " Not Found")); } - } - @Override - public Product update(Product updateProduct, long id) { - return null; - } + @Transactional + @Override + public Product delete (long productid){ + if (productrepos.findById(productid).isPresent()) { + productrepos.deleteById(productid); + throw new EntityNotFoundException("product" + productid + "not found!"); + } else { + throw new EntityNotFoundException("product" + productid + "not found!"); + } + } - @Override - public List findAllProducts() { - List list = new ArrayList<>(); - productrepos.findAll() - .iterator() - .forEachRemaining(list::add); - return list; - } + @Override + public Product update (Product updateProduct,long id){ + return updateProduct; + } -} + @Override + public List findAllProducts () { + List list = new ArrayList<>(); + productrepos.findAll() + .iterator() + .forEachRemaining(list::add); + return list; + } + + } diff --git a/foundation/src/main/resources/application.properties b/foundation/src/main/resources/application.properties index f1d6362ae..faf2385cd 100644 --- a/foundation/src/main/resources/application.properties +++ b/foundation/src/main/resources/application.properties @@ -24,7 +24,7 @@ spring.jpa.open-in-view=true # What do with the schema # drop n create table again, good for testing spring.jpa.hibernate.ddl-auto=create -spring.datasource.initialization-mode=never +spring.datasource.initialization-mode=always command.line.runner.enabled=true # # Good for production! From 77d70ab192da7cebcd2a13c5d0a2b6a998d13f0f Mon Sep 17 00:00:00 2001 From: George Hatzigeorgio Date: Fri, 2 Apr 2021 17:59:19 -0400 Subject: [PATCH 4/4] still cant get delete and update to work --- .../controllers/ProductController.java | 2 +- .../foundation/models/Product.java | 8 +++-- .../services/ProductServiceImpl.java | 30 +++++++++++++++---- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java b/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java index ef1305642..d166310aa 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/controllers/ProductController.java @@ -52,7 +52,7 @@ public ResponseEntity updateProduct( } @DeleteMapping(value = "/product/{id}") - public ResponseEntity delete( + public ResponseEntity deleteProductById( @PathVariable long id) { diff --git a/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java b/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java index 43e73667f..4a508a8a3 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/models/Product.java @@ -7,7 +7,7 @@ import java.util.Set; @Entity -@Table(name = "products") +@Table(name = "product") public class Product { private String product; @@ -17,7 +17,7 @@ public class Product { @OneToMany(mappedBy="product",cascade = CascadeType.ALL,orphanRemoval = true) -@JsonIgnoreProperties(value = "products") +@JsonIgnoreProperties(value = "product") private Set users = new HashSet<>(); @@ -55,4 +55,6 @@ public Set getUsers() { public void setUsers(Set userproducts) { this.users = userproducts; } -} + + + diff --git a/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java index 1ea1aa617..e8fc7d3e3 100644 --- a/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java +++ b/foundation/src/main/java/com/lambdaschool/foundation/services/ProductServiceImpl.java @@ -3,6 +3,7 @@ import com.lambdaschool.foundation.exceptions.ResourceNotFoundException; import com.lambdaschool.foundation.models.*; import com.lambdaschool.foundation.repository.ProductRepository; +import com.lambdaschool.foundation.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -23,6 +24,9 @@ public class ProductServiceImpl implements ProductService { @Autowired private ProductService productService; + @Autowired + private UserRepository userrepos; + @Override public Product save(Product product) { @@ -66,13 +70,29 @@ public Product delete (long productid){ throw new EntityNotFoundException("product" + productid + "not found!"); } } - + @Transactional @Override - public Product update (Product updateProduct,long id){ - return updateProduct; - } + public Product update (Product updateProduct,long productid) { + Product currentProduct = productrepos.findById(productid) + .orElseThrow(() -> new EntityNotFoundException("Product"+ productid + "not found")); - @Override + + currentProduct.setProduct(updateProduct.setProduct()); + + + updateProduct.getUsers() + .clear(); + for (UserProduct up : updateProduct.getUsers()) { + User user = up.getUser(); + user = userService.findUserById(user.getUserid()); + updateProduct.getUsers() + .add(new UserProduct(user, + updateProduct)); + } + return productrepos.save(currentProduct); + + } + @Override public List findAllProducts () { List list = new ArrayList<>(); productrepos.findAll()