diff --git a/.gitignore b/.gitignore index f98b419fc..5b8fffabd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .idea/ /starter_code/target/ +/eCommerceApplication/target/ diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index eb46263eb..000000000 --- a/LICENSE.md +++ /dev/null @@ -1,15 +0,0 @@ - -Copyright © 2012 - 2020, Udacity, Inc. - -Udacity hereby grants you a license in and to the Educational Content, including but not limited to homework assignments, programming assignments, code samples, and other educational materials and tools (as further described in the Udacity Terms of Use), subject to, as modified herein, the terms and conditions of the Creative Commons Attribution-NonCommercial- NoDerivs 3.0 License located at http://creativecommons.org/licenses/by-nc-nd/4.0 and successor locations for such license (the "CC License") provided that, in each case, the Educational Content is specifically marked as being subject to the CC License. -Udacity expressly defines the following as falling outside the definition of "non-commercial": -(a) the sale or rental of (i) any part of the Educational Content, (ii) any derivative works based at least in part on the Educational Content, or (iii) any collective work that includes any part of the Educational Content; -(b) the sale of access or a link to any part of the Educational Content without first obtaining informed consent from the buyer (that the buyer is aware that the Educational Content, or such part thereof, is available at the Website free of charge); -(c) providing training, support, or editorial services that use or reference the Educational Content in exchange for a fee; -(d) the sale of advertisements, sponsorships, or promotions placed on the Educational Content, or any part thereof, or the sale of advertisements, sponsorships, or promotions on any website or blog containing any part of the Educational Material, including without limitation any "pop-up advertisements"; -(e) the use of Educational Content by a college, university, school, or other educational institution for instruction where tuition is charged; and -(f) the use of Educational Content by a for-profit corporation or non-profit entity for internal professional development or training. - - - -THE SERVICES AND ONLINE COURSES (INCLUDING ANY CONTENT) ARE PROVIDED "AS IS" AND "AS AVAILABLE" WITH NO REPRESENTATIONS OR WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. YOU ASSUME TOTAL RESPONSIBILITY AND THE ENTIRE RISK FOR YOUR USE OF THE SERVICES, ONLINE COURSES, AND CONTENT. WITHOUT LIMITING THE FOREGOING, WE DO NOT WARRANT THAT (A) THE SERVICES, WEBSITES, CONTENT, OR THE ONLINE COURSES WILL MEET YOUR REQUIREMENTS OR EXPECTATIONS OR ACHIEVE THE INTENDED PURPOSES, (B) THE WEBSITES OR THE ONLINE COURSES WILL NOT EXPERIENCE OUTAGES OR OTHERWISE BE UNINTERRUPTED, TIMELY, SECURE OR ERROR-FREE, (C) THE INFORMATION OR CONTENT OBTAINED THROUGH THE SERVICES, SUCH AS CHAT ROOM SERVICES, WILL BE ACCURATE, COMPLETE, CURRENT, ERROR- FREE, COMPLETELY SECURE OR RELIABLE, OR (D) THAT DEFECTS IN OR ON THE SERVICES OR CONTENT WILL BE CORRECTED. YOU ASSUME ALL RISK OF PERSONAL INJURY, INCLUDING DEATH AND DAMAGE TO PERSONAL PROPERTY, SUSTAINED FROM USE OF SERVICES. \ No newline at end of file diff --git a/Metrics_Splunk_Screenshots.zip b/Metrics_Splunk_Screenshots.zip new file mode 100644 index 000000000..db1d514f5 Binary files /dev/null and b/Metrics_Splunk_Screenshots.zip differ diff --git a/starter_code/auth-course.iml b/eCommerceApplication/eCommerceApplication.iml similarity index 100% rename from starter_code/auth-course.iml rename to eCommerceApplication/eCommerceApplication.iml diff --git a/starter_code/mvnw b/eCommerceApplication/mvnw similarity index 100% rename from starter_code/mvnw rename to eCommerceApplication/mvnw diff --git a/starter_code/mvnw.cmd b/eCommerceApplication/mvnw.cmd similarity index 100% rename from starter_code/mvnw.cmd rename to eCommerceApplication/mvnw.cmd diff --git a/eCommerceApplication/pom.xml b/eCommerceApplication/pom.xml new file mode 100644 index 000000000..16e9068fb --- /dev/null +++ b/eCommerceApplication/pom.xml @@ -0,0 +1,103 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.5.RELEASE + + + uz.jumanazar + eCommerceApplication + war + 0.0.1-SNAPSHOT + eCommerceApplication + Final project for Java Developer Nanodegree program using Spring Boot + + + 1.8 + 3.1.1 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-security + + + + com.auth0 + java-jwt + 3.10.3 + + + org.springframework.security + spring-security-test + test + + + org.springframework.security + spring-security-config + + + junit + junit + test + + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.codehaus.mojo + tomcat-maven-plugin + 1.1 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + + + diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/ECommerceApplication.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/ECommerceApplication.java new file mode 100644 index 000000000..02acdc474 --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/ECommerceApplication.java @@ -0,0 +1,31 @@ +package uz.jumanazar.ecommerceapp; + + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + + +@EnableJpaRepositories("uz.jumanazar.ecommerceapp.model.persistence.repositories") +@EntityScan("uz.jumanazar.ecommerceapp.model.persistence") +@SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) +public class ECommerceApplication { + private static final Logger log = LogManager.getLogger(ECommerceApplication.class); + + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder(){ + return new BCryptPasswordEncoder(); + } + + public static void main(String[] args) { + log.info("eCommerce Application started."); + SpringApplication.run(ECommerceApplication.class, args); + } + +} diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/CartController.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/CartController.java new file mode 100644 index 000000000..cc1852638 --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/CartController.java @@ -0,0 +1,93 @@ +package uz.jumanazar.ecommerceapp.controllers; + +import java.util.Optional; +import java.util.stream.IntStream; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import uz.jumanazar.ecommerceapp.model.persistence.Cart; +import uz.jumanazar.ecommerceapp.model.persistence.Item; +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.CartRepository; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.ItemRepository; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.UserRepository; +import uz.jumanazar.ecommerceapp.model.requests.ModifyCartRequest; + +@RestController +@RequestMapping("/api/cart") +public class CartController { + + private static final Logger log = LogManager.getLogger(CartController.class); + + @Autowired + private UserRepository userRepository; + + @Autowired + private CartRepository cartRepository; + + @Autowired + private ItemRepository itemRepository; + + @PostMapping("/addToCart") + public ResponseEntity addTocart(@RequestBody ModifyCartRequest request) { +// log.info("[addTocart] New request for adding an item to user's cart with request body {}", request); + try { + User user = userRepository.findByUsername(request.getUsername()); + if(user == null) { + log.error("[addTocart_failure] User not found with username {}", request.getUsername()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } + Optional item = itemRepository.findById(request.getItemId()); + if(!item.isPresent()) { + log.error("[addTocart_failure] Item not found with ID {}", request.getItemId()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } + Cart cart = user.getCart(); + IntStream.range(0, request.getQuantity()) + .forEach(i -> cart.addItem(item.get())); + cartRepository.save(cart); + log.info("[addTocart_success] New item was added to user's cart with item_id:{}, " + + "item_name:{}, item_price:{}", item.get().getId(), item.get().getName(), item.get().getPrice()); + return ResponseEntity.ok(cart); + }catch (Exception e){ + log.error("[addTocart_failure] Item add to cart failed. Error {} ", e.getMessage()); + return ResponseEntity.status(500).build(); + } + } + + @PostMapping("/removeFromCart") + public ResponseEntity removeFromcart(@RequestBody ModifyCartRequest request) { +// log.info("[removeFromcart] New request for removing an item from user's cart with request body {}", request); + try { + User user = userRepository.findByUsername(request.getUsername()); + if(user == null) { + log.error("[removeFromcart_failure] User not found with username {}", request.getUsername()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } + Optional item = itemRepository.findById(request.getItemId()); + if(!item.isPresent()) { + log.error("[removeFromcart_failure] Item not found with ID {}", request.getItemId()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } + Cart cart = user.getCart(); + IntStream.range(0, request.getQuantity()) + .forEach(i -> cart.removeItem(item.get())); + cartRepository.save(cart); + log.info("[removeFromcart_success] Item was removed from user's cart with item_id:{}, " + + "item_name:{}, item_price:{}", item.get().getId(), item.get().getName(), item.get().getPrice()); + return ResponseEntity.ok(cart); + }catch (Exception e){ + log.error("[removeFromcart_failure] Item remove from cart failed. Error {}", e.getMessage()); + return ResponseEntity.status(500).build(); + } + } + +} diff --git a/starter_code/src/main/java/com/example/demo/controllers/ItemController.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/ItemController.java similarity index 65% rename from starter_code/src/main/java/com/example/demo/controllers/ItemController.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/ItemController.java index e990c0abc..eeef3e789 100644 --- a/starter_code/src/main/java/com/example/demo/controllers/ItemController.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/ItemController.java @@ -1,7 +1,9 @@ -package com.example.demo.controllers; +package uz.jumanazar.ecommerceapp.controllers; import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -9,28 +11,33 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.example.demo.model.persistence.Item; -import com.example.demo.model.persistence.repositories.ItemRepository; +import uz.jumanazar.ecommerceapp.model.persistence.Item; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.ItemRepository; @RestController @RequestMapping("/api/item") public class ItemController { + private static final Logger log = LogManager.getLogger(ItemController.class); + @Autowired private ItemRepository itemRepository; @GetMapping public ResponseEntity> getItems() { + log.info("[getItems] New request for getting all items"); return ResponseEntity.ok(itemRepository.findAll()); } @GetMapping("/{id}") public ResponseEntity getItemById(@PathVariable Long id) { + log.info("[getItemById] New request for getting an item with ID {}", id); return ResponseEntity.of(itemRepository.findById(id)); } @GetMapping("/name/{name}") public ResponseEntity> getItemsByName(@PathVariable String name) { + log.info("[getItemsByName] New request for getting an item by its name {}", name); List items = itemRepository.findByName(name); return items == null || items.isEmpty() ? ResponseEntity.notFound().build() : ResponseEntity.ok(items); diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/OrderController.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/OrderController.java new file mode 100644 index 000000000..e52c5a677 --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/OrderController.java @@ -0,0 +1,64 @@ +package uz.jumanazar.ecommerceapp.controllers; + +import java.util.List; + + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.UserOrder; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.OrderRepository; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.UserRepository; + +@RestController +@RequestMapping("/api/order") +public class OrderController { + + private static final Logger log = LogManager.getLogger(OrderController.class); + + @Autowired + private UserRepository userRepository; + + @Autowired + private OrderRepository orderRepository; + + + @PostMapping("/submit/{username}") + public ResponseEntity submit(@PathVariable String username) { +// log.info("[order_submit] New request for order submissing for user {}", username); + try { + User user = userRepository.findByUsername(username); + if(user == null) { + log.error("[order_submit_failure] User not found with username {}", username); + return ResponseEntity.notFound().build(); + } + UserOrder order = UserOrder.createFromCart(user.getCart()); + orderRepository.save(order); + log.info("[order_submit_success] User {}'s order was successfully submitted with details {}", username, order); + return ResponseEntity.ok(order); + }catch (Exception e){ + log.error("[order_submit_failure] User not found with username {}, Error: {}", username, e.getMessage()); + return ResponseEntity.status(500).build(); + } + } + + @GetMapping("/history/{username}") + public ResponseEntity> getOrdersForUser(@PathVariable String username) { +// log.info("[getOrdersForUser] New request getting orders for user {}", username); + User user = userRepository.findByUsername(username); + if(user == null) { + log.error("[getOrdersForUser_failure] User not found with username {}", username); + return ResponseEntity.notFound().build(); + } + log.info("[getOrdersForUser_success] New request getting orders for user {}", username); + return ResponseEntity.ok(orderRepository.findByUser(user)); + } +} diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/UserController.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/UserController.java new file mode 100644 index 000000000..7066e59f4 --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/controllers/UserController.java @@ -0,0 +1,81 @@ +package uz.jumanazar.ecommerceapp.controllers; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import uz.jumanazar.ecommerceapp.model.persistence.Cart; +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.CartRepository; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.UserRepository; +import uz.jumanazar.ecommerceapp.model.requests.CreateUserRequest; + +import java.util.HashMap; +import java.util.Map; +@RestController +@RequestMapping("/api/user") +public class UserController { + + private static final Logger log = LogManager.getLogger(UserController.class); + + @Autowired + private UserRepository userRepository; + + @Autowired + private CartRepository cartRepository; + + @Autowired + private BCryptPasswordEncoder encoder; + + @GetMapping("/id/{id}") + public ResponseEntity findById(@PathVariable Long id) { + log.info("[findById] New request for searching a user by ID {}", id); + + return ResponseEntity.of(userRepository.findById(id)); + } + + @GetMapping("/{username}") + public ResponseEntity findByUserName(@PathVariable String username) { + log.info("[findByUserName] New request for searching a user by userName {}", username); + User user = userRepository.findByUsername(username); + return user == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(user); + } + + @PostMapping("/create") + public ResponseEntity createUser(@RequestBody CreateUserRequest createUserRequest) { +// log.info("[createUser] New request for user creation with request body {}", createUserRequest); + try { + User user = new User(); + user.setUsername(createUserRequest.getUsername()); + Cart cart = new Cart(); + cartRepository.save(cart); + user.setCart(cart); + if (createUserRequest.getPassword().length() < 7 || !createUserRequest.getPassword().equals(createUserRequest.getConfirmPassword())) { + Map response = new HashMap<>(); + response.put("success", false); + response.put("statusCode", 400); + response.put("errorMessage", "Bad password was provided. Please, check the password requirements (at least 8 chars) " + + "and make sure if the password and confirmPasswords are the same."); + log.error("[createUser_failure] Bad password was provided for username {}", createUserRequest.getUsername()); + return ResponseEntity + .status(400) + .body(response); + } + user.setPassword(encoder.encode(createUserRequest.getPassword())); + userRepository.save(user); + log.info("[createUser_success] User with username {} was successfully created", user.getUsername()); + return ResponseEntity.ok(user); + }catch (Exception e){ + log.error("[createUser_failure] User creation failed with error {}", e.getMessage()); + } + return ResponseEntity.status(500).build(); + } +} diff --git a/starter_code/src/main/java/com/example/demo/model/persistence/Cart.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/Cart.java similarity index 92% rename from starter_code/src/main/java/com/example/demo/model/persistence/Cart.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/Cart.java index 053906c31..e4733302c 100644 --- a/starter_code/src/main/java/com/example/demo/model/persistence/Cart.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/Cart.java @@ -1,10 +1,8 @@ -package com.example.demo.model.persistence; +package uz.jumanazar.ecommerceapp.model.persistence; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; -import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; @@ -12,7 +10,6 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; diff --git a/starter_code/src/main/java/com/example/demo/model/persistence/Item.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/Item.java similarity index 90% rename from starter_code/src/main/java/com/example/demo/model/persistence/Item.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/Item.java index 2ce3ae412..bee8d21e6 100644 --- a/starter_code/src/main/java/com/example/demo/model/persistence/Item.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/Item.java @@ -1,4 +1,4 @@ -package com.example.demo.model.persistence; +package uz.jumanazar.ecommerceapp.model.persistence; import java.math.BigDecimal; @@ -7,11 +7,8 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; import javax.persistence.Table; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @Entity diff --git a/starter_code/src/main/java/com/example/demo/model/persistence/User.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/User.java similarity index 79% rename from starter_code/src/main/java/com/example/demo/model/persistence/User.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/User.java index ab85ccc60..45212769b 100644 --- a/starter_code/src/main/java/com/example/demo/model/persistence/User.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/User.java @@ -1,4 +1,4 @@ -package com.example.demo.model.persistence; +package uz.jumanazar.ecommerceapp.model.persistence; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -26,11 +26,22 @@ public class User { @Column(nullable = false, unique = true) @JsonProperty private String username; + + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Column(nullable = false) + private String password; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "cart_id", referencedColumnName = "id") @JsonIgnore private Cart cart; + + public String getPassword(){ + return password; + } + public void setPassword(String password) { + this.password = password; + } public Cart getCart() { return cart; diff --git a/starter_code/src/main/java/com/example/demo/model/persistence/UserOrder.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/UserOrder.java similarity index 95% rename from starter_code/src/main/java/com/example/demo/model/persistence/UserOrder.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/UserOrder.java index 60e1bc490..6eb56e3b6 100644 --- a/starter_code/src/main/java/com/example/demo/model/persistence/UserOrder.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/UserOrder.java @@ -1,4 +1,4 @@ -package com.example.demo.model.persistence; +package uz.jumanazar.ecommerceapp.model.persistence; import java.math.BigDecimal; import java.util.List; @@ -11,7 +11,6 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; diff --git a/starter_code/src/main/java/com/example/demo/model/persistence/repositories/CartRepository.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/CartRepository.java similarity index 55% rename from starter_code/src/main/java/com/example/demo/model/persistence/repositories/CartRepository.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/CartRepository.java index bdedb3a55..4c82f863a 100644 --- a/starter_code/src/main/java/com/example/demo/model/persistence/repositories/CartRepository.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/CartRepository.java @@ -1,9 +1,9 @@ -package com.example.demo.model.persistence.repositories; +package uz.jumanazar.ecommerceapp.model.persistence.repositories; import org.springframework.data.jpa.repository.JpaRepository; -import com.example.demo.model.persistence.Cart; -import com.example.demo.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.Cart; +import uz.jumanazar.ecommerceapp.model.persistence.User; import org.springframework.stereotype.Repository; diff --git a/starter_code/src/main/java/com/example/demo/model/persistence/repositories/ItemRepository.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/ItemRepository.java similarity index 67% rename from starter_code/src/main/java/com/example/demo/model/persistence/repositories/ItemRepository.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/ItemRepository.java index de4988d8e..b1c4cb179 100644 --- a/starter_code/src/main/java/com/example/demo/model/persistence/repositories/ItemRepository.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/ItemRepository.java @@ -1,10 +1,10 @@ -package com.example.demo.model.persistence.repositories; +package uz.jumanazar.ecommerceapp.model.persistence.repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; -import com.example.demo.model.persistence.Item; +import uz.jumanazar.ecommerceapp.model.persistence.Item; import org.springframework.stereotype.Repository; @Repository diff --git a/starter_code/src/main/java/com/example/demo/model/persistence/repositories/OrderRepository.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/OrderRepository.java similarity index 59% rename from starter_code/src/main/java/com/example/demo/model/persistence/repositories/OrderRepository.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/OrderRepository.java index d16b5fcb3..640aaecf6 100644 --- a/starter_code/src/main/java/com/example/demo/model/persistence/repositories/OrderRepository.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/OrderRepository.java @@ -1,11 +1,11 @@ -package com.example.demo.model.persistence.repositories; +package uz.jumanazar.ecommerceapp.model.persistence.repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; -import com.example.demo.model.persistence.User; -import com.example.demo.model.persistence.UserOrder; +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.UserOrder; import org.springframework.stereotype.Repository; @Repository diff --git a/starter_code/src/main/java/com/example/demo/model/persistence/repositories/UserRepository.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/UserRepository.java similarity index 65% rename from starter_code/src/main/java/com/example/demo/model/persistence/repositories/UserRepository.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/UserRepository.java index 8f9274e5c..f3e5de5f5 100644 --- a/starter_code/src/main/java/com/example/demo/model/persistence/repositories/UserRepository.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/persistence/repositories/UserRepository.java @@ -1,8 +1,8 @@ -package com.example.demo.model.persistence.repositories; +package uz.jumanazar.ecommerceapp.model.persistence.repositories; import org.springframework.data.jpa.repository.JpaRepository; -import com.example.demo.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.User; import org.springframework.stereotype.Repository; @Repository diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/requests/CreateUserRequest.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/requests/CreateUserRequest.java new file mode 100644 index 000000000..1f5d245a1 --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/requests/CreateUserRequest.java @@ -0,0 +1,39 @@ +package uz.jumanazar.ecommerceapp.model.requests; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CreateUserRequest { + + @JsonProperty + private String username; + + @JsonProperty + private String password; + + @JsonProperty + private String confirmPassword; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getConfirmPassword() { + return confirmPassword; + } + + public void setConfirmPassword(String confirmPassword) { + this.confirmPassword = confirmPassword; + } +} diff --git a/starter_code/src/main/java/com/example/demo/model/requests/ModifyCartRequest.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/requests/ModifyCartRequest.java similarity index 92% rename from starter_code/src/main/java/com/example/demo/model/requests/ModifyCartRequest.java rename to eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/requests/ModifyCartRequest.java index 42fed2233..12adacc13 100644 --- a/starter_code/src/main/java/com/example/demo/model/requests/ModifyCartRequest.java +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/model/requests/ModifyCartRequest.java @@ -1,4 +1,4 @@ -package com.example.demo.model.requests; +package uz.jumanazar.ecommerceapp.model.requests; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/JWTAuthenticationFilter.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/JWTAuthenticationFilter.java new file mode 100644 index 000000000..f5c52919a --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/JWTAuthenticationFilter.java @@ -0,0 +1,64 @@ +package uz.jumanazar.ecommerceapp.security; + +import com.auth0.jwt.JWT; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import uz.jumanazar.ecommerceapp.model.persistence.User; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; + +import static com.auth0.jwt.algorithms.Algorithm.HMAC512; + +public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { + + private AuthenticationManager authenticationManager; + private static final Logger log = LogManager.getLogger(JWTAuthenticationFilter.class); + + public JWTAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public Authentication attemptAuthentication(HttpServletRequest req, + HttpServletResponse res) throws AuthenticationException { + try { + User credentials = new ObjectMapper() + .readValue(req.getInputStream(), User.class); + log.info("[attemptAuthentication] New request for authentication with username {}", credentials.getUsername()); + return authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken( + credentials.getUsername(), + credentials.getPassword(), + new ArrayList<>())); + } catch (IOException e) { + log.error("[attemptAuthentication] Exception while authentication"); + throw new RuntimeException(e); + } + } + + @Override + protected void successfulAuthentication(HttpServletRequest req, + HttpServletResponse res, + FilterChain chain, + Authentication auth) throws IOException, ServletException { + + log.info("[successfulAuthentication] Successful authentication for user {}", ((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername()); + String token = JWT.create() + .withSubject(((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername()) + .withExpiresAt(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME)) + .sign(HMAC512(SecurityConstants.SECRET.getBytes())); + res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token); + } +} diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/JWTAuthenticationVerficationFilter.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/JWTAuthenticationVerficationFilter.java new file mode 100644 index 000000000..fb5f9fc56 --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/JWTAuthenticationVerficationFilter.java @@ -0,0 +1,57 @@ +package uz.jumanazar.ecommerceapp.security; + +import com.auth0.jwt.JWT; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; +import org.springframework.stereotype.Component; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; + +import static com.auth0.jwt.algorithms.Algorithm.HMAC512; + +@Component +public class JWTAuthenticationVerficationFilter extends BasicAuthenticationFilter { + + public JWTAuthenticationVerficationFilter(AuthenticationManager authManager) { + super(authManager); + } + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) + throws IOException, ServletException { + String header = req.getHeader(SecurityConstants.HEADER_STRING); + + if (header == null || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) { + chain.doFilter(req, res); + return; + } + + UsernamePasswordAuthenticationToken authentication = getAuthentication(req); + + SecurityContextHolder.getContext().setAuthentication(authentication); + chain.doFilter(req, res); + } + + private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest req) { + String token = req.getHeader(SecurityConstants.HEADER_STRING); + if (token != null) { + String user = JWT.require(HMAC512(SecurityConstants.SECRET.getBytes())).build() + .verify(token.replace(SecurityConstants.TOKEN_PREFIX, "")) + .getSubject(); + if (user != null) { + return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>()); + } + return null; + } + return null; + } + + +} diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/SecurityConstants.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/SecurityConstants.java new file mode 100644 index 000000000..f4dbaf86a --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/SecurityConstants.java @@ -0,0 +1,10 @@ +package uz.jumanazar.ecommerceapp.security; + +public class SecurityConstants { + + public static final String SECRET = "parolSekret"; + public static final long EXPIRATION_TIME = 864_000_000; // 10 days + public static final String TOKEN_PREFIX = "Bearer "; + public static final String HEADER_STRING = "Authorization"; + public static final String SIGN_UP_URL = "/api/user/create"; +} diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/UserDetailsServiceImpl.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/UserDetailsServiceImpl.java new file mode 100644 index 000000000..e7e2e23e1 --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/UserDetailsServiceImpl.java @@ -0,0 +1,32 @@ +package uz.jumanazar.ecommerceapp.security; + + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.UserRepository; + +import java.util.Collections; + +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + + private static final Logger log = LogManager.getLogger(UserDetailsServiceImpl.class); + @Autowired + private UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = userRepository.findByUsername(username); + if (user == null) { +// log.error("[loadUserByUsername] User not found with username {}", username); + throw new UsernameNotFoundException(username); + } + return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.emptyList()); + } +} diff --git a/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/WebSecurityConfiguration.java b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/WebSecurityConfiguration.java new file mode 100644 index 000000000..1467fd5e9 --- /dev/null +++ b/eCommerceApplication/src/main/java/uz/jumanazar/ecommerceapp/security/WebSecurityConfiguration.java @@ -0,0 +1,48 @@ +package uz.jumanazar.ecommerceapp.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@EnableWebSecurity +public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { + + private UserDetailsServiceImpl userDetailsService; + private BCryptPasswordEncoder bCryptPasswordEncoder; + + public WebSecurityConfiguration(UserDetailsServiceImpl userDetailsService, + BCryptPasswordEncoder bCryptPasswordEncoder) { + this.userDetailsService = userDetailsService; + this.bCryptPasswordEncoder = bCryptPasswordEncoder; + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors().and().csrf().disable().authorizeRequests() + .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL).permitAll() + .anyRequest().authenticated() + .and() + .addFilter(new JWTAuthenticationFilter(authenticationManager())) + .addFilter(new JWTAuthenticationVerficationFilter(authenticationManager())) + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.parentAuthenticationManager(authenticationManagerBean()) + .userDetailsService(userDetailsService) + .passwordEncoder(bCryptPasswordEncoder); + } +} diff --git a/starter_code/src/main/resources/application.properties b/eCommerceApplication/src/main/resources/application.properties similarity index 67% rename from starter_code/src/main/resources/application.properties rename to eCommerceApplication/src/main/resources/application.properties index ed303a7d4..8a717ae53 100644 --- a/starter_code/src/main/resources/application.properties +++ b/eCommerceApplication/src/main/resources/application.properties @@ -2,5 +2,7 @@ spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.jpa.hibernate.ddl-auto=create +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/starter_code/src/main/resources/data.sql b/eCommerceApplication/src/main/resources/data.sql similarity index 100% rename from starter_code/src/main/resources/data.sql rename to eCommerceApplication/src/main/resources/data.sql diff --git a/eCommerceApplication/src/main/resources/log4j2-spring.xml b/eCommerceApplication/src/main/resources/log4j2-spring.xml new file mode 100644 index 000000000..3f9cbe011 --- /dev/null +++ b/eCommerceApplication/src/main/resources/log4j2-spring.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/starter_code/src/test/java/com/example/demo/SareetaApplicationTests.java b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/ECommerceApplicationTests.java similarity index 77% rename from starter_code/src/test/java/com/example/demo/SareetaApplicationTests.java rename to eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/ECommerceApplicationTests.java index 0fb7e471d..e626d8b84 100644 --- a/starter_code/src/test/java/com/example/demo/SareetaApplicationTests.java +++ b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/ECommerceApplicationTests.java @@ -1,4 +1,4 @@ -package com.example.demo; +package uz.jumanazar.ecommerceapp; import org.junit.Test; import org.junit.runner.RunWith; @@ -7,7 +7,7 @@ @RunWith(SpringRunner.class) @SpringBootTest -public class SareetaApplicationTests { +public class ECommerceApplicationTests { @Test public void contextLoads() { diff --git a/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/TestUtils.java b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/TestUtils.java new file mode 100644 index 000000000..698ad1759 --- /dev/null +++ b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/TestUtils.java @@ -0,0 +1,86 @@ +package uz.jumanazar.ecommerceapp; + +import uz.jumanazar.ecommerceapp.model.persistence.Cart; +import uz.jumanazar.ecommerceapp.model.persistence.Item; +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.UserOrder; + +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +public class TestUtils { + + public static void injectObjects(Object target, String fieldName, Object toInject){ + boolean wasPrivate = false; + + try { + Field declaredField = target.getClass().getDeclaredField(fieldName); + + if(!declaredField.isAccessible()){ + declaredField.setAccessible(true); + wasPrivate = true; + } + declaredField.set(target, toInject); + + if(wasPrivate){ + declaredField.setAccessible(false); + } + + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException(e); + } + + } + + public static User getUser(){ + User user = new User(); + user.setId(1L); + user.setUsername("test"); + user.setPassword("test1234"); + user.setCart(getCart()); + return user; + } + + public static Cart getCart(){ + Cart cart = new Cart(); + cart.setId(1L); + cart.setItems(getItems()); + return cart; + } + + public static List addToItems(Item item){ + List items = getItems(); + items.add(item); + return items; + } + + public static List getItems(){ + List items = new ArrayList<>(); + Item item1 = getItem(1L, "Bananas", 1000d, "Food"); + + items.add(item1); + return items; + } + + public static Item getItem(Long id, String name, Double price, String description){ + Item item = new Item(); + item.setId(id); + item.setName(name); + item.setPrice(new BigDecimal(price)); + item.setDescription(description); + return item; + } + + public static UserOrder getOrder() { + UserOrder order = new UserOrder(); + order.setId(1L); + order.setItems(getItems()); + BigDecimal totalPrice = getItems().stream().map(Item::getPrice) + .reduce(BigDecimal.ZERO, BigDecimal::add); + order.setTotal(totalPrice); + order.setUser(getUser()); + return order; + } +} diff --git a/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/CartControllerTest.java b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/CartControllerTest.java new file mode 100644 index 000000000..f66c5b70b --- /dev/null +++ b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/CartControllerTest.java @@ -0,0 +1,114 @@ +package uz.jumanazar.ecommerceapp.controllers; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.ResponseEntity; +import uz.jumanazar.ecommerceapp.TestUtils; +import uz.jumanazar.ecommerceapp.model.persistence.Cart; +import uz.jumanazar.ecommerceapp.model.persistence.Item; +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.CartRepository; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.ItemRepository; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.UserRepository; +import uz.jumanazar.ecommerceapp.model.requests.ModifyCartRequest; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; +import java.util.stream.IntStream; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class CartControllerTest { + + private CartController cartController; + private final CartRepository cartRepo = mock(CartRepository.class); + private final UserRepository userRepo = mock(UserRepository.class); + private final ItemRepository itemRepo = mock(ItemRepository.class); + + @Before + public void setUp() throws Exception { + cartController = new CartController(); + TestUtils.injectObjects(cartController, "cartRepository", cartRepo); + TestUtils.injectObjects(cartController, "userRepository", userRepo); + TestUtils.injectObjects(cartController, "itemRepository", itemRepo); + + when(userRepo.findByUsername("test")).thenReturn(TestUtils.getUser()); + } + + + @Test + public void addTocartWorks() { + ModifyCartRequest req = new ModifyCartRequest(); + req.setUsername("test"); + req.setQuantity(1); + req.setItemId(1); + + User testUser = TestUtils.getUser(); + Item itemApple = TestUtils.getItem(1L, "Apple", 2000d, "Food"); + + List itemAdded = TestUtils.addToItems(itemApple); + Cart cart = TestUtils.getCart(); + cart.setUser(testUser); + cart.setItems(itemAdded); + BigDecimal total = cart.getItems().stream() + .map(Item::getPrice) + .reduce(BigDecimal.ZERO, BigDecimal::add); + + cart.setTotal(total); + + User userReturned = userRepo.findByUsername(req.getUsername()); + assertNotNull(userReturned); + + when(itemRepo.findById(req.getItemId())).thenReturn(Optional.of(itemApple)); + Optional item = itemRepo.findById(req.getItemId()); + assertTrue(item.isPresent()); + Item itemReturned = item.get(); + assertEquals(itemApple.getId(), itemReturned.getId()); + assertEquals(itemApple.getPrice(), itemReturned.getPrice()); + assertEquals(itemApple.getName(), itemReturned.getName()); + + assertNotNull(userReturned.getCart()); + Cart userCart = userReturned.getCart(); + IntStream.range(0, req.getQuantity()) + .forEach(i -> userCart.addItem(itemReturned)); + ResponseEntity response = cartController.addTocart(req); + + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + Cart cart1 = response.getBody(); + assertNotNull(cart1); + assertNotNull(cart1.getItems()); + assertNotNull(cart1.getTotal()); + } + + @Test + public void addToCartNotWorks(){ + ModifyCartRequest req = new ModifyCartRequest(); + req.setUsername("tester"); + req.setItemId(0L); + ResponseEntity response = cartController.addTocart(req); + assertNotNull(response); + assertEquals(404, response.getStatusCodeValue()); + } + + @Test + public void removeFromcartWorks() { + ModifyCartRequest req = new ModifyCartRequest(); + req.setItemId(1); + req.setQuantity(1); + req.setUsername("test"); + User user = userRepo.findByUsername(req.getUsername()); + assertNotNull(user); + when(itemRepo.findById(req.getItemId())).thenReturn(Optional.of(TestUtils.getItem(1L, "Apple", 2000d, "Food"))); + Optional item = itemRepo.findById(req.getItemId()); + assertNotNull(item); + ResponseEntity response = cartController.removeFromcart(req); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + assertNotNull(response.getBody()); + assertNotNull(response.getBody().getId()); + } +} \ No newline at end of file diff --git a/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/ItemControllerTest.java b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/ItemControllerTest.java new file mode 100644 index 000000000..deea97302 --- /dev/null +++ b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/ItemControllerTest.java @@ -0,0 +1,82 @@ +package uz.jumanazar.ecommerceapp.controllers; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.ResponseEntity; +import uz.jumanazar.ecommerceapp.TestUtils; +import uz.jumanazar.ecommerceapp.model.persistence.Item; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.ItemRepository; + +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ItemControllerTest { + + private ItemController itemController; + private final ItemRepository itemRepo = mock(ItemRepository.class); + + @Before + public void setUp() throws Exception { + itemController = new ItemController(); + TestUtils.injectObjects(itemController, "itemRepository", itemRepo); + + when(itemRepo.findAll()).thenReturn(TestUtils.getItems()); + } + + @Test + public void getItems() { + ResponseEntity> response = itemController.getItems(); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + List items = response.getBody(); + assertNotNull(items); + assertFalse(items.isEmpty()); + } + + @Test + public void getItemById() { + Item item = TestUtils.getItem(1L, "Banana", 3000d, "Fruits"); + + when(itemRepo.findById(1L)).thenReturn(Optional.of(item)); + + ResponseEntity response = itemController.getItemById(1L); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + + Item itemReturned = response.getBody(); + assertNotNull(itemReturned); + assertEquals(item, itemReturned); + } + + @Test + public void getItemByIdNotWorks(){ + ResponseEntity response = itemController.getItemById(0L); + assertNotNull(response); + assertEquals(404, response.getStatusCodeValue()); + } + + @Test + public void getItemsByName() { + List itemList = TestUtils.getItems(); + when(itemRepo.findByName("Banana")).thenReturn(itemList); + ResponseEntity> response = itemController.getItemsByName("Banana"); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + + List itemsReturned = response.getBody(); + assertNotNull(itemsReturned); + assertEquals(itemList, itemsReturned); + } + + @Test + public void getItemsByNameNotWorks(){ + ResponseEntity> response = itemController.getItemsByName("DummyItemNotExists"); + assertNotNull(response); + assertEquals(404, response.getStatusCodeValue()); + + } +} \ No newline at end of file diff --git a/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/OrderControllerTest.java b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/OrderControllerTest.java new file mode 100644 index 000000000..aab26a63c --- /dev/null +++ b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/OrderControllerTest.java @@ -0,0 +1,68 @@ +package uz.jumanazar.ecommerceapp.controllers; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import uz.jumanazar.ecommerceapp.TestUtils; +import uz.jumanazar.ecommerceapp.model.persistence.Cart; +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.UserOrder; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.OrderRepository; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.UserRepository; + +import java.util.List; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class OrderControllerTest { + + private OrderController orderController; + private final UserRepository userRepo = mock(UserRepository.class); + private final OrderRepository orderRepo = mock(OrderRepository.class); + + @Before + public void setUp() throws Exception { + orderController = new OrderController(); + TestUtils.injectObjects(orderController, "userRepository", userRepo); + TestUtils.injectObjects(orderController, "orderRepository", orderRepo); + + when(userRepo.findByUsername("test")).thenReturn(TestUtils.getUser()); + } + + @Test + public void submit() { + UserOrder myOrder = TestUtils.getOrder(); + Cart cart = TestUtils.getCart(); + + User user = userRepo.findByUsername("test"); + user.setCart(cart); + UserOrder order = new UserOrder(); + order.setUser(user); + when(orderRepo.save(order)).thenReturn(myOrder); + ResponseEntity response = orderController.submit("test"); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + UserOrder orderReturned = response.getBody(); + assertNotNull(orderReturned); + } + + @Test + public void orderSubmitNotWorks(){ + ResponseEntity response = orderController.submit("tester"); + assertNotNull(response); + assertEquals(404, response.getStatusCodeValue()); + } + + @Test + public void getOrdersForUser() { + User user = userRepo.findByUsername("test"); + assertNotNull(user); + + ResponseEntity> response = orderController.getOrdersForUser(user.getUsername()); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + } +} \ No newline at end of file diff --git a/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/UserControllerTest.java b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/UserControllerTest.java new file mode 100644 index 000000000..7c5c48e77 --- /dev/null +++ b/eCommerceApplication/src/test/java/uz/jumanazar/ecommerceapp/controllers/UserControllerTest.java @@ -0,0 +1,112 @@ +package uz.jumanazar.ecommerceapp.controllers; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.ResponseEntity; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import uz.jumanazar.ecommerceapp.TestUtils; +import uz.jumanazar.ecommerceapp.model.persistence.User; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.CartRepository; +import uz.jumanazar.ecommerceapp.model.persistence.repositories.UserRepository; +import uz.jumanazar.ecommerceapp.model.requests.CreateUserRequest; + +import java.util.Optional; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class UserControllerTest { + + private UserController userController; + private final UserRepository userRepo = mock(UserRepository.class); + private final CartRepository cartRepo = mock(CartRepository.class); + private final BCryptPasswordEncoder encoder = mock(BCryptPasswordEncoder.class); + + @Before + public void setup(){ + userController = new UserController(); + TestUtils.injectObjects(userController, "userRepository", userRepo); + TestUtils.injectObjects(userController, "cartRepository", cartRepo); + TestUtils.injectObjects(userController, "encoder", encoder); + } + + @Test + public void create_user() throws Exception{ + when(encoder.encode("testtest")).thenReturn("thisIsHashed"); + CreateUserRequest req = new CreateUserRequest(); + req.setUsername("test"); + req.setPassword("testtest"); + req.setConfirmPassword("testtest"); + + final ResponseEntity response = userController.createUser(req); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + + assertTrue((response.getBody() instanceof User)); + User user = (User) response.getBody(); + assertNotNull(user); + assertEquals(0, user.getId()); + assertEquals("test", user.getUsername()); + assertEquals("thisIsHashed", user.getPassword()); + } + + @Test + public void user_create_fails() { + CreateUserRequest req = new CreateUserRequest(); + req.setUsername("test"); + req.setPassword("test12"); + req.setConfirmPassword("test12"); + final ResponseEntity response = userController.createUser(req); + assertNotNull(response); + assertEquals(400, response.getStatusCodeValue()); + assertFalse(response.getBody() instanceof User); + } + + @Test + public void findById() { + User user = new User(); + user.setId(1L); + user.setUsername("test"); + user.setPassword("test1234"); + + when(userRepo.findById(1L)).thenReturn(Optional.of(user)); + final ResponseEntity response = userController.findById(1L); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + User userReturned = response.getBody(); + assertNotNull(userReturned); + assertEquals(user.getId(), userReturned.getId()); + assertEquals(user.getUsername(), userReturned.getUsername()); + } + + @Test + public void findByIdNotWorks(){ + ResponseEntity response = userController.findById(10L); + assertNotNull(response); + assertEquals(404, response.getStatusCodeValue()); + } + + @Test + public void findByUserName() { + User user = new User(); + user.setUsername("test"); + String userName = "test"; + when(userRepo.findByUsername(userName)).thenReturn(user); + + ResponseEntity response = userController.findByUserName(userName); + assertNotNull(response); + assertEquals(200, response.getStatusCodeValue()); + User userReturned = response.getBody(); + assertNotNull(userReturned); + assertEquals(userName, userReturned.getUsername()); + } + + @Test + public void findByUserNameNotWorks(){ + String userName = "testNotWorks"; + ResponseEntity response = userController.findByUserName(userName); + assertNotNull(response); + assertEquals(404, response.getStatusCodeValue()); + } +} diff --git a/starter_code/target/classes/application.properties b/eCommerceApplication/target/classes/application.properties similarity index 67% rename from starter_code/target/classes/application.properties rename to eCommerceApplication/target/classes/application.properties index ed303a7d4..8a717ae53 100644 --- a/starter_code/target/classes/application.properties +++ b/eCommerceApplication/target/classes/application.properties @@ -2,5 +2,7 @@ spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.jpa.hibernate.ddl-auto=create +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/starter_code/target/classes/com/example/demo/SareetaApplication.class b/eCommerceApplication/target/classes/com/example/demo/SareetaApplication.class similarity index 100% rename from starter_code/target/classes/com/example/demo/SareetaApplication.class rename to eCommerceApplication/target/classes/com/example/demo/SareetaApplication.class diff --git a/starter_code/target/classes/com/example/demo/controllers/CartController.class b/eCommerceApplication/target/classes/com/example/demo/controllers/CartController.class similarity index 100% rename from starter_code/target/classes/com/example/demo/controllers/CartController.class rename to eCommerceApplication/target/classes/com/example/demo/controllers/CartController.class diff --git a/starter_code/target/classes/com/example/demo/controllers/ItemController.class b/eCommerceApplication/target/classes/com/example/demo/controllers/ItemController.class similarity index 100% rename from starter_code/target/classes/com/example/demo/controllers/ItemController.class rename to eCommerceApplication/target/classes/com/example/demo/controllers/ItemController.class diff --git a/starter_code/target/classes/com/example/demo/controllers/OrderController.class b/eCommerceApplication/target/classes/com/example/demo/controllers/OrderController.class similarity index 100% rename from starter_code/target/classes/com/example/demo/controllers/OrderController.class rename to eCommerceApplication/target/classes/com/example/demo/controllers/OrderController.class diff --git a/starter_code/target/classes/com/example/demo/controllers/UserController.class b/eCommerceApplication/target/classes/com/example/demo/controllers/UserController.class similarity index 100% rename from starter_code/target/classes/com/example/demo/controllers/UserController.class rename to eCommerceApplication/target/classes/com/example/demo/controllers/UserController.class diff --git a/starter_code/target/classes/com/example/demo/model/persistence/Cart.class b/eCommerceApplication/target/classes/com/example/demo/model/persistence/Cart.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/persistence/Cart.class rename to eCommerceApplication/target/classes/com/example/demo/model/persistence/Cart.class diff --git a/starter_code/target/classes/com/example/demo/model/persistence/Item.class b/eCommerceApplication/target/classes/com/example/demo/model/persistence/Item.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/persistence/Item.class rename to eCommerceApplication/target/classes/com/example/demo/model/persistence/Item.class diff --git a/starter_code/target/classes/com/example/demo/model/persistence/User.class b/eCommerceApplication/target/classes/com/example/demo/model/persistence/User.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/persistence/User.class rename to eCommerceApplication/target/classes/com/example/demo/model/persistence/User.class diff --git a/starter_code/target/classes/com/example/demo/model/persistence/UserOrder.class b/eCommerceApplication/target/classes/com/example/demo/model/persistence/UserOrder.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/persistence/UserOrder.class rename to eCommerceApplication/target/classes/com/example/demo/model/persistence/UserOrder.class diff --git a/starter_code/target/classes/com/example/demo/model/persistence/repositories/CartRepository.class b/eCommerceApplication/target/classes/com/example/demo/model/persistence/repositories/CartRepository.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/persistence/repositories/CartRepository.class rename to eCommerceApplication/target/classes/com/example/demo/model/persistence/repositories/CartRepository.class diff --git a/starter_code/target/classes/com/example/demo/model/persistence/repositories/ItemRepository.class b/eCommerceApplication/target/classes/com/example/demo/model/persistence/repositories/ItemRepository.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/persistence/repositories/ItemRepository.class rename to eCommerceApplication/target/classes/com/example/demo/model/persistence/repositories/ItemRepository.class diff --git a/starter_code/target/classes/com/example/demo/model/persistence/repositories/OrderRepository.class b/eCommerceApplication/target/classes/com/example/demo/model/persistence/repositories/OrderRepository.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/persistence/repositories/OrderRepository.class rename to eCommerceApplication/target/classes/com/example/demo/model/persistence/repositories/OrderRepository.class diff --git a/starter_code/target/classes/com/example/demo/model/persistence/repositories/UserRepository.class b/eCommerceApplication/target/classes/com/example/demo/model/persistence/repositories/UserRepository.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/persistence/repositories/UserRepository.class rename to eCommerceApplication/target/classes/com/example/demo/model/persistence/repositories/UserRepository.class diff --git a/starter_code/target/classes/com/example/demo/model/requests/CreateUserRequest.class b/eCommerceApplication/target/classes/com/example/demo/model/requests/CreateUserRequest.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/requests/CreateUserRequest.class rename to eCommerceApplication/target/classes/com/example/demo/model/requests/CreateUserRequest.class diff --git a/starter_code/target/classes/com/example/demo/model/requests/ModifyCartRequest.class b/eCommerceApplication/target/classes/com/example/demo/model/requests/ModifyCartRequest.class similarity index 100% rename from starter_code/target/classes/com/example/demo/model/requests/ModifyCartRequest.class rename to eCommerceApplication/target/classes/com/example/demo/model/requests/ModifyCartRequest.class diff --git a/starter_code/target/classes/data.sql b/eCommerceApplication/target/classes/data.sql similarity index 100% rename from starter_code/target/classes/data.sql rename to eCommerceApplication/target/classes/data.sql diff --git a/starter_code/target/test-classes/com/example/demo/SareetaApplicationTests.class b/eCommerceApplication/target/test-classes/com/example/demo/SareetaApplicationTests.class similarity index 100% rename from starter_code/target/test-classes/com/example/demo/SareetaApplicationTests.class rename to eCommerceApplication/target/test-classes/com/example/demo/SareetaApplicationTests.class diff --git a/starter_code/pom.xml b/starter_code/pom.xml deleted file mode 100644 index 608bb212f..000000000 --- a/starter_code/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.1.5.RELEASE - - - com.example - auth-course - war - 0.0.1-SNAPSHOT - auth-course - Demo project for Spring Boot - - - 1.8 - 3.1.1 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - com.h2database - h2 - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.codehaus.mojo - tomcat-maven-plugin - 1.1 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - - - - - diff --git a/starter_code/src/main/java/com/example/demo/SareetaApplication.java b/starter_code/src/main/java/com/example/demo/SareetaApplication.java deleted file mode 100644 index f161f699d..000000000 --- a/starter_code/src/main/java/com/example/demo/SareetaApplication.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.example.demo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@EnableJpaRepositories("com.example.demo.model.persistence.repositories") -@EntityScan("com.example.demo.model.persistence") -@SpringBootApplication -public class SareetaApplication { - - public static void main(String[] args) { - SpringApplication.run(SareetaApplication.class, args); - } - -} diff --git a/starter_code/src/main/java/com/example/demo/controllers/CartController.java b/starter_code/src/main/java/com/example/demo/controllers/CartController.java deleted file mode 100644 index 6f72169f8..000000000 --- a/starter_code/src/main/java/com/example/demo/controllers/CartController.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.example.demo.controllers; - -import java.util.Optional; -import java.util.stream.IntStream; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.example.demo.model.persistence.Cart; -import com.example.demo.model.persistence.Item; -import com.example.demo.model.persistence.User; -import com.example.demo.model.persistence.repositories.CartRepository; -import com.example.demo.model.persistence.repositories.ItemRepository; -import com.example.demo.model.persistence.repositories.UserRepository; -import com.example.demo.model.requests.ModifyCartRequest; - -@RestController -@RequestMapping("/api/cart") -public class CartController { - - @Autowired - private UserRepository userRepository; - - @Autowired - private CartRepository cartRepository; - - @Autowired - private ItemRepository itemRepository; - - @PostMapping("/addToCart") - public ResponseEntity addTocart(@RequestBody ModifyCartRequest request) { - User user = userRepository.findByUsername(request.getUsername()); - if(user == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); - } - Optional item = itemRepository.findById(request.getItemId()); - if(!item.isPresent()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); - } - Cart cart = user.getCart(); - IntStream.range(0, request.getQuantity()) - .forEach(i -> cart.addItem(item.get())); - cartRepository.save(cart); - return ResponseEntity.ok(cart); - } - - @PostMapping("/removeFromCart") - public ResponseEntity removeFromcart(@RequestBody ModifyCartRequest request) { - User user = userRepository.findByUsername(request.getUsername()); - if(user == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); - } - Optional item = itemRepository.findById(request.getItemId()); - if(!item.isPresent()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); - } - Cart cart = user.getCart(); - IntStream.range(0, request.getQuantity()) - .forEach(i -> cart.removeItem(item.get())); - cartRepository.save(cart); - return ResponseEntity.ok(cart); - } - -} diff --git a/starter_code/src/main/java/com/example/demo/controllers/OrderController.java b/starter_code/src/main/java/com/example/demo/controllers/OrderController.java deleted file mode 100644 index 79b8b288c..000000000 --- a/starter_code/src/main/java/com/example/demo/controllers/OrderController.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.example.demo.controllers; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.example.demo.model.persistence.Cart; -import com.example.demo.model.persistence.User; -import com.example.demo.model.persistence.UserOrder; -import com.example.demo.model.persistence.repositories.CartRepository; -import com.example.demo.model.persistence.repositories.OrderRepository; -import com.example.demo.model.persistence.repositories.UserRepository; - -@RestController -@RequestMapping("/api/order") -public class OrderController { - - - @Autowired - private UserRepository userRepository; - - @Autowired - private OrderRepository orderRepository; - - - @PostMapping("/submit/{username}") - public ResponseEntity submit(@PathVariable String username) { - User user = userRepository.findByUsername(username); - if(user == null) { - return ResponseEntity.notFound().build(); - } - UserOrder order = UserOrder.createFromCart(user.getCart()); - orderRepository.save(order); - return ResponseEntity.ok(order); - } - - @GetMapping("/history/{username}") - public ResponseEntity> getOrdersForUser(@PathVariable String username) { - User user = userRepository.findByUsername(username); - if(user == null) { - return ResponseEntity.notFound().build(); - } - return ResponseEntity.ok(orderRepository.findByUser(user)); - } -} diff --git a/starter_code/src/main/java/com/example/demo/controllers/UserController.java b/starter_code/src/main/java/com/example/demo/controllers/UserController.java deleted file mode 100644 index 87e8089df..000000000 --- a/starter_code/src/main/java/com/example/demo/controllers/UserController.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.example.demo.controllers; - -import java.util.Optional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.example.demo.model.persistence.Cart; -import com.example.demo.model.persistence.User; -import com.example.demo.model.persistence.repositories.CartRepository; -import com.example.demo.model.persistence.repositories.UserRepository; -import com.example.demo.model.requests.CreateUserRequest; - -@RestController -@RequestMapping("/api/user") -public class UserController { - - @Autowired - private UserRepository userRepository; - - @Autowired - private CartRepository cartRepository; - - @GetMapping("/id/{id}") - public ResponseEntity findById(@PathVariable Long id) { - return ResponseEntity.of(userRepository.findById(id)); - } - - @GetMapping("/{username}") - public ResponseEntity findByUserName(@PathVariable String username) { - User user = userRepository.findByUsername(username); - return user == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(user); - } - - @PostMapping("/create") - public ResponseEntity createUser(@RequestBody CreateUserRequest createUserRequest) { - User user = new User(); - user.setUsername(createUserRequest.getUsername()); - Cart cart = new Cart(); - cartRepository.save(cart); - user.setCart(cart); - userRepository.save(user); - return ResponseEntity.ok(user); - } - -} diff --git a/starter_code/src/main/java/com/example/demo/model/requests/CreateUserRequest.java b/starter_code/src/main/java/com/example/demo/model/requests/CreateUserRequest.java deleted file mode 100644 index a92d0bbb6..000000000 --- a/starter_code/src/main/java/com/example/demo/model/requests/CreateUserRequest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.example.demo.model.requests; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class CreateUserRequest { - - @JsonProperty - private String username; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } -}