CommonsController.java

  1. package edu.ucsb.cs156.happiercows.controllers;

  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import edu.ucsb.cs156.happiercows.entities.Commons;
  5. import edu.ucsb.cs156.happiercows.entities.CommonsPlus;
  6. import edu.ucsb.cs156.happiercows.entities.User;
  7. import edu.ucsb.cs156.happiercows.entities.UserCommons;
  8. import edu.ucsb.cs156.happiercows.errors.EntityNotFoundException;
  9. import edu.ucsb.cs156.happiercows.models.CreateCommonsParams;
  10. import edu.ucsb.cs156.happiercows.models.HealthUpdateStrategyList;
  11. import edu.ucsb.cs156.happiercows.repositories.CommonsRepository;
  12. import edu.ucsb.cs156.happiercows.repositories.UserCommonsRepository;
  13. import edu.ucsb.cs156.happiercows.strategies.CowHealthUpdateStrategies;
  14. import io.swagger.v3.oas.annotations.tags.Tag;
  15. import io.swagger.v3.oas.annotations.Operation;
  16. import io.swagger.v3.oas.annotations.Parameter;
  17. import lombok.extern.slf4j.Slf4j;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.http.HttpStatus;
  20. import org.springframework.http.ResponseEntity;
  21. import org.springframework.security.access.prepost.PreAuthorize;
  22. import org.springframework.web.bind.annotation.*;

  23. import java.util.ArrayList;
  24. import java.util.List;
  25. import java.util.Optional;
  26. import java.util.stream.Collectors;

  27. @Slf4j
  28. @Tag(name = "Commons")
  29. @RequestMapping("/api/commons")
  30. @RestController
  31. public class CommonsController extends ApiController {
  32.     @Autowired
  33.     private CommonsRepository commonsRepository;

  34.     @Autowired
  35.     private UserCommonsRepository userCommonsRepository;

  36.     @Autowired
  37.     ObjectMapper mapper;

  38.     @Operation(summary = "Get a list of all commons")
  39.     @GetMapping("/all")
  40.     public ResponseEntity<String> getCommons() throws JsonProcessingException {
  41.         log.info("getCommons()...");
  42.         Iterable<Commons> commons = commonsRepository.findAll();
  43.         String body = mapper.writeValueAsString(commons);
  44.         return ResponseEntity.ok().body(body);
  45.     }

  46.     @Operation(summary = "Get a list of all commons and number of cows/users")
  47.     @GetMapping("/allplus")
  48.     public ResponseEntity<String> getCommonsPlus() throws JsonProcessingException {
  49.         log.info("getCommonsPlus()...");
  50.         Iterable<Commons> commonsListIter = commonsRepository.findAll();

  51.         // convert Iterable to List for the purposes of using a Java Stream & lambda
  52.         // below
  53.         List<Commons> commonsList = new ArrayList<Commons>();
  54.         commonsListIter.forEach(commonsList::add);

  55.         List<CommonsPlus> commonsPlusList1 = commonsList.stream()
  56.                 .map(c -> toCommonsPlus(c))
  57.                 .collect(Collectors.toList());

  58.         ArrayList<CommonsPlus> commonsPlusList = new ArrayList<CommonsPlus>(commonsPlusList1);

  59.         String body = mapper.writeValueAsString(commonsPlusList);
  60.         return ResponseEntity.ok().body(body);
  61.     }

  62.     @Operation(summary = "Get the number of cows/users in a commons")
  63.     @PreAuthorize("hasRole('ROLE_USER')")
  64.     @GetMapping("/plus")
  65.     public CommonsPlus getCommonsPlusById(
  66.             @Parameter(name="id") @RequestParam long id) throws JsonProcessingException {
  67.                 CommonsPlus commonsPlus = toCommonsPlus(commonsRepository.findById(id)
  68.                 .orElseThrow(() -> new EntityNotFoundException(Commons.class, id)));

  69.         return commonsPlus;
  70.     }

  71.     @Operation(summary = "Update a commons")
  72.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  73.     @PutMapping("/update")
  74.     public ResponseEntity<String> updateCommons(
  75.             @Parameter(name="commons identifier") @RequestParam long id,
  76.             @Parameter(name="request body") @RequestBody CreateCommonsParams params
  77.     ) {
  78.         Optional<Commons> existing = commonsRepository.findById(id);

  79.         Commons updated;
  80.         HttpStatus status;

  81.         if (existing.isPresent()) {
  82.             updated = existing.get();
  83.             status = HttpStatus.NO_CONTENT;
  84.         } else {
  85.             updated = new Commons();
  86.             status = HttpStatus.CREATED;
  87.         }

  88.         updated.setName(params.getName());
  89.         updated.setCowPrice(params.getCowPrice());
  90.         updated.setMilkPrice(params.getMilkPrice());
  91.         updated.setStartingBalance(params.getStartingBalance());
  92.         updated.setStartingDate(params.getStartingDate());
  93.         updated.setShowLeaderboard(params.getShowLeaderboard());
  94.         updated.setDegradationRate(params.getDegradationRate());
  95.         updated.setCarryingCapacity(params.getCarryingCapacity());
  96.         updated.setCapacityPerUser(params.getCapacityPerUser());
  97.         if (params.getAboveCapacityHealthUpdateStrategy() != null) {
  98.             updated.setAboveCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getAboveCapacityHealthUpdateStrategy()));
  99.         }
  100.         if (params.getBelowCapacityHealthUpdateStrategy() != null) {
  101.             updated.setBelowCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getBelowCapacityHealthUpdateStrategy()));
  102.         }

  103.         if (params.getDegradationRate() < 0) {
  104.             throw new IllegalArgumentException("Degradation Rate cannot be negative");
  105.         }

  106.         commonsRepository.save(updated);

  107.         return ResponseEntity.status(status).build();
  108.     }

  109.     @Operation(summary = "Get a specific commons")
  110.     @PreAuthorize("hasRole('ROLE_USER')")
  111.     @GetMapping("")
  112.     public Commons getCommonsById(
  113.             @Parameter(name="id") @RequestParam Long id) throws JsonProcessingException {

  114.         Commons commons = commonsRepository.findById(id)
  115.                 .orElseThrow(() -> new EntityNotFoundException(Commons.class, id));

  116.         return commons;
  117.     }

  118.     @Operation(summary = "Create a new commons")
  119.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  120.     @PostMapping(value = "/new", produces = "application/json")
  121.     public ResponseEntity<String> createCommons(
  122.             @Parameter(name="request body") @RequestBody CreateCommonsParams params
  123.     ) throws JsonProcessingException {

  124.         var builder = Commons.builder()
  125.                 .name(params.getName())
  126.                 .cowPrice(params.getCowPrice())
  127.                 .milkPrice(params.getMilkPrice())
  128.                 .startingBalance(params.getStartingBalance())
  129.                 .startingDate(params.getStartingDate())
  130.                 .degradationRate(params.getDegradationRate())
  131.                 .showLeaderboard(params.getShowLeaderboard())
  132.                 .carryingCapacity(params.getCarryingCapacity())
  133.                 .capacityPerUser(params.getCapacityPerUser());

  134.         // ok to set null values for these, so old backend still works
  135.         if (params.getAboveCapacityHealthUpdateStrategy() != null) {
  136.             builder.aboveCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getAboveCapacityHealthUpdateStrategy()));
  137.         }
  138.         if (params.getBelowCapacityHealthUpdateStrategy() != null) {
  139.             builder.belowCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getBelowCapacityHealthUpdateStrategy()));
  140.         }

  141.         Commons commons = builder.build();


  142.         // throw exception for degradation rate
  143.         if (params.getDegradationRate() < 0) {
  144.             throw new IllegalArgumentException("Degradation Rate cannot be negative");
  145.         }

  146.         Commons saved = commonsRepository.save(commons);
  147.         String body = mapper.writeValueAsString(saved);

  148.         return ResponseEntity.ok().body(body);
  149.     }


  150.     @Operation(summary = "List all cow health update strategies")
  151.     @PreAuthorize("hasRole('ROLE_USER')")
  152.     @GetMapping("/all-health-update-strategies")
  153.     public ResponseEntity<String> listCowHealthUpdateStrategies() throws JsonProcessingException {
  154.         var result = HealthUpdateStrategyList.create();
  155.         String body = mapper.writeValueAsString(result);
  156.         return ResponseEntity.ok().body(body);
  157.     }

  158.     @Operation(summary = "Join a commons")
  159.     @PreAuthorize("hasRole('ROLE_USER')")
  160.     @PostMapping(value = "/join", produces = "application/json")
  161.     public ResponseEntity<String> joinCommon(
  162.             @Parameter(name="commonsId") @RequestParam Long commonsId) throws Exception {

  163.         User u = getCurrentUser().getUser();
  164.         Long userId = u.getId();
  165.         String username = u.getFullName();

  166.         Commons joinedCommons = commonsRepository.findById(commonsId)
  167.                 .orElseThrow(() -> new EntityNotFoundException(Commons.class, commonsId));
  168.         Optional<UserCommons> userCommonsLookup = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId);

  169.         if (userCommonsLookup.isPresent()) {
  170.             // user is already a member of this commons
  171.             String body = mapper.writeValueAsString(joinedCommons);
  172.             return ResponseEntity.ok().body(body);
  173.         }

  174.         UserCommons uc = UserCommons.builder()
  175.                 .user(u)
  176.                 .commons(joinedCommons)
  177.                 .username(username)
  178.                 .totalWealth(joinedCommons.getStartingBalance())
  179.                 .numOfCows(0)
  180.                 .cowHealth(100)
  181.                 .cowsBought(0)
  182.                 .cowsSold(0)
  183.                 .cowDeaths(0)
  184.                 .build();

  185.         userCommonsRepository.save(uc);

  186.         joinedCommons.setNumUsers(joinedCommons.getNumUsers() + 1);
  187.         commonsRepository.save(joinedCommons);

  188.         String body = mapper.writeValueAsString(joinedCommons);
  189.         return ResponseEntity.ok().body(body);
  190.     }

  191.     @Operation(summary = "Delete a Commons")
  192.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  193.     @DeleteMapping("")
  194.     public Object deleteCommons(
  195.             @Parameter(name="id") @RequestParam Long id) {

  196.         commonsRepository.findById(id)
  197.                 .orElseThrow(() -> new EntityNotFoundException(Commons.class, id));

  198.         commonsRepository.deleteById(id);

  199.         String responseString = String.format("commons with id %d deleted", id);
  200.         return genericMessage(responseString);

  201.     }

  202.     @Operation(summary="Delete a user from a commons")
  203.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  204.     @DeleteMapping("/{commonsId}/users/{userId}")
  205.     public Object deleteUserFromCommon(@PathVariable("commonsId") Long commonsId,
  206.                                        @PathVariable("userId") Long userId) throws Exception {

  207.         UserCommons userCommons = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId)
  208.                 .orElseThrow(() -> new EntityNotFoundException(
  209.                         UserCommons.class, "commonsId", commonsId, "userId", userId)
  210.                 );

  211.         userCommonsRepository.delete(userCommons);

  212.         String responseString = String.format("user with id %d deleted from commons with id %d, %d users remain", userId, commonsId, commonsRepository.getNumUsers(commonsId).orElse(0));

  213.         Commons exitedCommon = commonsRepository.findById(commonsId).orElse(null);

  214.         exitedCommon.setNumUsers(exitedCommon.getNumUsers() - 1);
  215.         commonsRepository.save(exitedCommon);
  216.        
  217.         return genericMessage(responseString);
  218.     }

  219.     public CommonsPlus toCommonsPlus(Commons c) {
  220.         Optional<Integer> numCows = commonsRepository.getNumCows(c.getId());
  221.         Optional<Integer> numUsers = commonsRepository.getNumUsers(c.getId());

  222.         return CommonsPlus.builder()
  223.                 .commons(c)
  224.                 .totalCows(numCows.orElse(0))
  225.                 .totalUsers(numUsers.orElse(0))
  226.                 .build();
  227.     }
  228. }