Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Product REST API #43

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
Authentication authentication) throws IOException, ServletException {
Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (roles.contains("ROLE_ADMIN")) {
response.sendRedirect("/admin/product/list");
response.sendRedirect("/admin/product");
} else {
response.sendRedirect("/customer");
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/me/anant/PMS/controller/OrderController.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public ModelAndView orderPlace(HttpServletRequest request, Principal principal)
Set<OrderProduct> opList = new HashSet<>();
for(String pId: pIds) {
long pid = Long.parseLong(pId);
Product product = productService.findById(pid).get();
Product product = productService.findById(pid);
int buyqty = Integer.parseInt(request.getParameter(pId));
opList.add(new OrderProduct(product, buyqty));
productService.deductQty(pid, buyqty);
Expand Down
160 changes: 92 additions & 68 deletions src/main/java/me/anant/PMS/controller/ProductController.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
package me.anant.PMS.controller;

import java.util.List;
import java.util.Optional;
import java.util.*;

import javax.validation.Valid;

import me.anant.PMS.dto.CategoryDto;
import me.anant.PMS.dto.ProductDto;
import me.anant.PMS.exceptions.ProductNotFoundException;
import me.anant.PMS.model.ProductCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

Expand All @@ -24,7 +27,9 @@
* This Controller is responsible for CRUD operations related to Products.
*/
@Controller
@RequestMapping("/admin/product")
public class ProductController {

@Autowired
ProductService productService;

Expand All @@ -35,101 +40,120 @@ public class ProductController {
* This api is responsible to fetch the model and view for add Product.
* @return ModelAndView
*/
@GetMapping("/admin/product/add")
public ModelAndView addView() {
ModelAndView modelAndView = new ModelAndView("admin/product/add");
modelAndView.addObject("pcList", categoryService.get());
modelAndView.addObject("command", new Product());
return modelAndView;
@GetMapping("/add")
public String addView() {
return "/admin/product/add";
}

/**
* This api is responsible to add Product.
* @param product
* @param result
* @param model
* @param redirectAttributes
* @return String redirect path
* @param productDto - product data
* @return 201 created
*/
@PostMapping("/admin/product/add")
public String add(@ModelAttribute("command") @Valid Product product, BindingResult result, Model model, final RedirectAttributes redirectAttributes) {
if(result.hasErrors()) {
model.addAttribute("pcList", categoryService.get());
return "admin/product/add";
}
@PostMapping(value = "/add")
public ResponseEntity<Void> add(@RequestBody ProductDto productDto) {
Product product = new Product();
product.setProductName(productDto.getName());
product.setProductPrice(productDto.getPrice());
product.setProductQty(productDto.getQuantity());
product.setCategory(categoryService.findById(productDto.getCategory()).get());
productService.save(product);
redirectAttributes.addFlashAttribute("msg", "Product added successfully");
redirectAttributes.addFlashAttribute("class", "alert-success");
return "redirect:/admin/product/add";
return ResponseEntity.status(HttpStatus.CREATED).build();
}

/**
* This endpoint returns products index page.
* @return product list uri string
*/
@GetMapping
public String index() {
return "admin/product/list";
}

/**
* This Get api is responsible to view Product List
* @return ModelAndView
*/
@GetMapping("/admin/product/list")
public ModelAndView list() {
@GetMapping("/list")
public ResponseEntity<List<Product>> list() {
List<Product> pList = productService.get();
ModelAndView modelAndView = new ModelAndView("/admin/product/list");
modelAndView.addObject("pList", pList);
return modelAndView;
return ResponseEntity.ok(pList);
}

/**
* This GET api is responsible to delete the product.
* @param id
* @param redirectAttributes
* @return redirect path
* This DELETE api is responsible to delete the product.
* @param id - unique id of the product
*/
@GetMapping("/admin/product/delete")
public String list(@RequestParam("id") long id,
final RedirectAttributes redirectAttributes) {
@DeleteMapping("/delete/{id}")
public ResponseEntity<Void> list(@PathVariable("id") long id) {
productService.delete(id);
redirectAttributes.addFlashAttribute("msg", "Product deleted successfully");
redirectAttributes.addFlashAttribute("class", "alert-success");
return "redirect:/admin/product/list";
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}

/**
* This api is responsible to fetch the model and view for update Products Screen.
* @param id
* @return ModelAndView
* @param id - unique id of the product
* @return ResponseEntity
*/
@GetMapping("/admin/product/update")
public ModelAndView updateView(long id) throws ProductNotFoundException {
Optional<Product> optional = productService.findById(id);
Product product = optional.get();
ModelAndView modelAndView = new ModelAndView("admin/product/add");
modelAndView.addObject("command", product);
modelAndView.addObject("pcList", categoryService.get());
return modelAndView;
@GetMapping("/{id}")
public ResponseEntity<ProductDto> fetchProduct(@PathVariable long id) {
try {
Product product = productService.findById(id);
ProductDto dto = productService.toDto(product);
return ResponseEntity.ok(dto);
} catch (ProductNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}

/**
* This endpoint return product add form.
* @return string - product add form uri
*/
@GetMapping("/update/{id}")
public String showUpdateForm() {
return "/admin/product/add";
}

/**
* This POST api is responsible to update the Product.
* @param product
* @param result
* @param model
* @param redirectAttributes
* @return String redirect path
* This PUT api is responsible to update the Product.
* @return ResponseEntity
*/
@PostMapping("/admin/product/update")
public String updateView(@ModelAttribute("command") @Valid Product product, BindingResult result, Model model, final RedirectAttributes redirectAttributes) {
if(result.hasErrors()) {
model.addAttribute("pcList", categoryService.get());
return "admin/product/add";
@PutMapping(value = "/update", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> updateProduct(@RequestBody ProductDto productDto) {
try {
final Product product = productService.findById(productDto.getId());
product.setProductName(productDto.getName());
product.setProductPrice(productDto.getPrice());
product.setProductQty(productDto.getQuantity());
Optional<ProductCategory> productCategory = categoryService.findById(productDto.getCategory());
productCategory.ifPresent(product::setCategory);
productService.save(product);
return ResponseEntity.status(HttpStatus.OK).build();
} catch (ProductNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
productService.save(product);
redirectAttributes.addFlashAttribute("msg", "Product Updated successfully");
redirectAttributes.addFlashAttribute("class", "alert-success");
return "redirect:/admin/product/list";
}

/**
* This endpoint returns list of categories
* @return list of categories
*/
@GetMapping("/categories")
public ResponseEntity<List<CategoryDto>> fetchCategories() {
List<ProductCategory> categories = categoryService.get();
List<CategoryDto> result = new ArrayList<>();
categories.forEach(category -> {
result.add(productService.toDto(category));
});
return ResponseEntity.ok(result);
}

/**
* This api is responsible to generate report related to Product.
* @return ModelAndView
*/
@GetMapping("/admin/product/report")
@GetMapping("/report")
public ModelAndView report() {
ModelAndView modelAndView = new ModelAndView("admin/product/report");
modelAndView.addObject("pList", productService.get());
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/me/anant/PMS/dto/CategoryDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package me.anant.PMS.dto;

public class CategoryDto {

private Long id;
private String name;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
50 changes: 50 additions & 0 deletions src/main/java/me/anant/PMS/dto/ProductDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package me.anant.PMS.dto;

public class ProductDto {

private long id;
private String name;
private float price;
private int quantity;
private Long category;

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public float getPrice() {
return price;
}

public void setPrice(float price) {
this.price = price;
}

public int getQuantity() {
return quantity;
}

public void setQuantity(int quantity) {
this.quantity = quantity;
}

public Long getCategory() {
return category;
}

public void setCategory(Long category) {
this.category = category;
}
}
12 changes: 8 additions & 4 deletions src/main/java/me/anant/PMS/model/Product.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package me.anant.PMS.model;

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Set;

import javax.persistence.CascadeType;
Expand Down Expand Up @@ -36,13 +38,15 @@ public class Product {
@Min(value=0, message="Product quantity can not be negative")
@Max(value=50, message="Product quantity can be maximum 50.")
int productQty;


@JsonIgnore
@OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
Set<OrderProduct> orderProduct;
Set<OrderProduct> orderProduct;

@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
ProductCategory category;
ProductCategory category;

public Product() {
// TODO Auto-generated constructor stub
}
Expand Down
Loading