1 | package edu.ucsb.cs156.happiercows.controllers; | |
2 | ||
3 | import com.fasterxml.jackson.core.JsonProcessingException; | |
4 | import com.fasterxml.jackson.databind.ObjectMapper; | |
5 | import com.nimbusds.jose.util.Resource; | |
6 | ||
7 | import edu.ucsb.cs156.happiercows.entities.Commons; | |
8 | import edu.ucsb.cs156.happiercows.entities.CommonsPlus; | |
9 | import edu.ucsb.cs156.happiercows.entities.CommonStats; | |
10 | import edu.ucsb.cs156.happiercows.entities.User; | |
11 | import edu.ucsb.cs156.happiercows.entities.UserCommons; | |
12 | import edu.ucsb.cs156.happiercows.errors.EntityNotFoundException; | |
13 | import edu.ucsb.cs156.happiercows.models.CreateCommonsParams; | |
14 | import edu.ucsb.cs156.happiercows.models.HealthUpdateStrategyList; | |
15 | import edu.ucsb.cs156.happiercows.repositories.CommonsRepository; | |
16 | import edu.ucsb.cs156.happiercows.repositories.UserCommonsRepository; | |
17 | import edu.ucsb.cs156.happiercows.repositories.CommonStatsRepository; | |
18 | import edu.ucsb.cs156.happiercows.strategies.CowHealthUpdateStrategies; | |
19 | import edu.ucsb.cs156.happiercows.helpers.CommonStatsCSVHelper; | |
20 | import edu.ucsb.cs156.happiercows.helpers.ReportCSVHelper; | |
21 | import io.swagger.v3.oas.annotations.tags.Tag; | |
22 | import io.swagger.v3.oas.annotations.Operation; | |
23 | import io.swagger.v3.oas.annotations.Parameter; | |
24 | import lombok.extern.slf4j.Slf4j; | |
25 | import org.springframework.beans.factory.annotation.Autowired; | |
26 | import org.springframework.http.HttpStatus; | |
27 | import org.springframework.http.ResponseEntity; | |
28 | import org.springframework.security.access.prepost.PreAuthorize; | |
29 | import org.springframework.web.bind.annotation.*; | |
30 | import org.springframework.core.io.InputStreamResource; | |
31 | import org.springframework.http.HttpHeaders; | |
32 | import org.springframework.http.MediaType; | |
33 | ||
34 | import java.util.ArrayList; | |
35 | import java.util.List; | |
36 | import java.util.Optional; | |
37 | import java.util.stream.Collectors; | |
38 | ||
39 | import java.io.ByteArrayInputStream; | |
40 | import java.io.IOException; | |
41 | ||
42 | @Slf4j | |
43 | @Tag(name = "Commons") | |
44 | @RequestMapping("/api/commons") | |
45 | @RestController | |
46 | public class CommonsController extends ApiController { | |
47 | @Autowired | |
48 | private CommonsRepository commonsRepository; | |
49 | ||
50 | @Autowired | |
51 | private UserCommonsRepository userCommonsRepository; | |
52 | ||
53 | @Autowired | |
54 | private CommonStatsRepository commonStatsRepository; | |
55 | ||
56 | @Autowired | |
57 | ObjectMapper mapper; | |
58 | ||
59 | @Operation(summary = "Get a list of all commons") | |
60 | @GetMapping("/all") | |
61 | public ResponseEntity<String> getCommons() throws JsonProcessingException { | |
62 | log.info("getCommons()..."); | |
63 | Iterable<Commons> commons = commonsRepository.findAll(); | |
64 | String body = mapper.writeValueAsString(commons); | |
65 |
1
1. getCommons : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::getCommons → KILLED |
return ResponseEntity.ok().body(body); |
66 | } | |
67 | ||
68 | @Operation(summary = "Get a list of all commons and number of cows/users") | |
69 | @GetMapping("/allplus") | |
70 | public ResponseEntity<String> getCommonsPlus() throws JsonProcessingException { | |
71 | log.info("getCommonsPlus()..."); | |
72 | Iterable<Commons> commonsListIter = commonsRepository.findAll(); | |
73 | ||
74 | // convert Iterable to List for the purposes of using a Java Stream & lambda | |
75 | // below | |
76 | List<Commons> commonsList = new ArrayList<Commons>(); | |
77 |
1
1. getCommonsPlus : removed call to java/lang/Iterable::forEach → KILLED |
commonsListIter.forEach(commonsList::add); |
78 | ||
79 | List<CommonsPlus> commonsPlusList1 = commonsList.stream() | |
80 |
1
1. lambda$getCommonsPlus$0 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::lambda$getCommonsPlus$0 → KILLED |
.map(c -> toCommonsPlus(c)) |
81 | .collect(Collectors.toList()); | |
82 | ||
83 | ArrayList<CommonsPlus> commonsPlusList = new ArrayList<CommonsPlus>(commonsPlusList1); | |
84 | ||
85 | String body = mapper.writeValueAsString(commonsPlusList); | |
86 |
1
1. getCommonsPlus : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::getCommonsPlus → KILLED |
return ResponseEntity.ok().body(body); |
87 | } | |
88 | ||
89 | @Operation(summary = "Get the number of cows/users in a commons") | |
90 | @PreAuthorize("hasRole('ROLE_USER')") | |
91 | @GetMapping("/plus") | |
92 | public CommonsPlus getCommonsPlusById( | |
93 | @Parameter(name="id") @RequestParam long id) throws JsonProcessingException { | |
94 | CommonsPlus commonsPlus = toCommonsPlus(commonsRepository.findById(id) | |
95 |
1
1. lambda$getCommonsPlusById$1 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::lambda$getCommonsPlusById$1 → KILLED |
.orElseThrow(() -> new EntityNotFoundException(Commons.class, id))); |
96 | ||
97 |
1
1. getCommonsPlusById : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::getCommonsPlusById → KILLED |
return commonsPlus; |
98 | } | |
99 | ||
100 | @Operation(summary = "Update a commons") | |
101 | @PreAuthorize("hasRole('ROLE_ADMIN')") | |
102 | @PutMapping("/update") | |
103 | public ResponseEntity<String> updateCommons( | |
104 | @Parameter(name="id") @RequestParam long id, | |
105 | @Parameter(name="request body") @RequestBody CreateCommonsParams params | |
106 | ) { | |
107 | Optional<Commons> existing = commonsRepository.findById(id); | |
108 | ||
109 | Commons updated; | |
110 | HttpStatus status; | |
111 | ||
112 |
1
1. updateCommons : negated conditional → KILLED |
if (existing.isPresent()) { |
113 | updated = existing.get(); | |
114 | status = HttpStatus.NO_CONTENT; | |
115 | } else { | |
116 | updated = new Commons(); | |
117 | status = HttpStatus.CREATED; | |
118 | } | |
119 | ||
120 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setName → KILLED |
updated.setName(params.getName()); |
121 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setCowPrice → KILLED |
updated.setCowPrice(params.getCowPrice()); |
122 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setMilkPrice → KILLED |
updated.setMilkPrice(params.getMilkPrice()); |
123 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setStartingBalance → KILLED |
updated.setStartingBalance(params.getStartingBalance()); |
124 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setStartingDate → KILLED |
updated.setStartingDate(params.getStartingDate()); |
125 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setLastdayDate → KILLED |
updated.setLastdayDate(params.getLastdayDate()); |
126 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setShowLeaderboard → KILLED |
updated.setShowLeaderboard(params.getShowLeaderboard()); |
127 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setDegradationRate → KILLED |
updated.setDegradationRate(params.getDegradationRate()); |
128 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setCarryingCapacity → KILLED |
updated.setCarryingCapacity(params.getCarryingCapacity()); |
129 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setCapacityPerUser → KILLED |
updated.setCapacityPerUser(params.getCapacityPerUser()); |
130 | ||
131 |
1
1. updateCommons : negated conditional → KILLED |
if (params.getAboveCapacityHealthUpdateStrategy() != null) { |
132 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setAboveCapacityHealthUpdateStrategy → KILLED |
updated.setAboveCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getAboveCapacityHealthUpdateStrategy())); |
133 | } | |
134 |
1
1. updateCommons : negated conditional → KILLED |
if (params.getBelowCapacityHealthUpdateStrategy() != null) { |
135 |
1
1. updateCommons : removed call to edu/ucsb/cs156/happiercows/entities/Commons::setBelowCapacityHealthUpdateStrategy → KILLED |
updated.setBelowCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getBelowCapacityHealthUpdateStrategy())); |
136 | } | |
137 | ||
138 |
2
1. updateCommons : changed conditional boundary → KILLED 2. updateCommons : negated conditional → KILLED |
if (params.getDegradationRate() < 0) { |
139 | throw new IllegalArgumentException("Degradation Rate cannot be negative"); | |
140 | } | |
141 | ||
142 | commonsRepository.save(updated); | |
143 | ||
144 |
1
1. updateCommons : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::updateCommons → KILLED |
return ResponseEntity.status(status).build(); |
145 | } | |
146 | ||
147 | @Operation(summary = "Get a specific commons") | |
148 | @PreAuthorize("hasRole('ROLE_USER')") | |
149 | @GetMapping("") | |
150 | public Commons getCommonsById( | |
151 | @Parameter(name="id") @RequestParam Long id) throws JsonProcessingException { | |
152 | ||
153 | Commons commons = commonsRepository.findById(id) | |
154 |
1
1. lambda$getCommonsById$2 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::lambda$getCommonsById$2 → KILLED |
.orElseThrow(() -> new EntityNotFoundException(Commons.class, id)); |
155 | ||
156 |
1
1. getCommonsById : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::getCommonsById → KILLED |
return commons; |
157 | } | |
158 | ||
159 | @Operation(summary = "Create a new commons") | |
160 | @PreAuthorize("hasRole('ROLE_ADMIN')") | |
161 | @PostMapping(value = "/new", produces = "application/json") | |
162 | public ResponseEntity<String> createCommons( | |
163 | @Parameter(name="request body") @RequestBody CreateCommonsParams params | |
164 | ) throws JsonProcessingException { | |
165 | ||
166 | var builder = Commons.builder() | |
167 | .name(params.getName()) | |
168 | .cowPrice(params.getCowPrice()) | |
169 | .milkPrice(params.getMilkPrice()) | |
170 | .startingBalance(params.getStartingBalance()) | |
171 | .startingDate(params.getStartingDate()) | |
172 | .lastdayDate(params.getLastdayDate()) | |
173 | .degradationRate(params.getDegradationRate()) | |
174 | .showLeaderboard(params.getShowLeaderboard()) | |
175 | .carryingCapacity(params.getCarryingCapacity()) | |
176 | .capacityPerUser(params.getCapacityPerUser()); | |
177 | ||
178 | // ok to set null values for these, so old backend still works | |
179 |
1
1. createCommons : negated conditional → KILLED |
if (params.getAboveCapacityHealthUpdateStrategy() != null) { |
180 | builder.aboveCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getAboveCapacityHealthUpdateStrategy())); | |
181 | } | |
182 |
1
1. createCommons : negated conditional → KILLED |
if (params.getBelowCapacityHealthUpdateStrategy() != null) { |
183 | builder.belowCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getBelowCapacityHealthUpdateStrategy())); | |
184 | } | |
185 | ||
186 | Commons commons = builder.build(); | |
187 | ||
188 | ||
189 | // throw exception for degradation rate | |
190 |
2
1. createCommons : changed conditional boundary → KILLED 2. createCommons : negated conditional → KILLED |
if (params.getDegradationRate() < 0) { |
191 | throw new IllegalArgumentException("Degradation Rate cannot be negative"); | |
192 | } | |
193 | ||
194 | Commons saved = commonsRepository.save(commons); | |
195 | String body = mapper.writeValueAsString(saved); | |
196 | ||
197 |
1
1. createCommons : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::createCommons → KILLED |
return ResponseEntity.ok().body(body); |
198 | } | |
199 | ||
200 | ||
201 | @Operation(summary = "List all cow health update strategies") | |
202 | @PreAuthorize("hasRole('ROLE_USER')") | |
203 | @GetMapping("/all-health-update-strategies") | |
204 | public ResponseEntity<String> listCowHealthUpdateStrategies() throws JsonProcessingException { | |
205 | var result = HealthUpdateStrategyList.create(); | |
206 | String body = mapper.writeValueAsString(result); | |
207 |
1
1. listCowHealthUpdateStrategies : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::listCowHealthUpdateStrategies → KILLED |
return ResponseEntity.ok().body(body); |
208 | } | |
209 | ||
210 | @Operation(summary = "Join a commons") | |
211 | @PreAuthorize("hasRole('ROLE_USER')") | |
212 | @PostMapping(value = "/join", produces = "application/json") | |
213 | public ResponseEntity<String> joinCommon( | |
214 | @Parameter(name="commonsId") @RequestParam Long commonsId) throws Exception { | |
215 | ||
216 | User u = getCurrentUser().getUser(); | |
217 | Long userId = u.getId(); | |
218 | String username = u.getFullName(); | |
219 | ||
220 | Commons joinedCommons = commonsRepository.findById(commonsId) | |
221 |
1
1. lambda$joinCommon$3 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::lambda$joinCommon$3 → KILLED |
.orElseThrow(() -> new EntityNotFoundException(Commons.class, commonsId)); |
222 | Optional<UserCommons> userCommonsLookup = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId); | |
223 | ||
224 |
1
1. joinCommon : negated conditional → KILLED |
if (userCommonsLookup.isPresent()) { |
225 | // user is already a member of this commons | |
226 | String body = mapper.writeValueAsString(joinedCommons); | |
227 |
1
1. joinCommon : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::joinCommon → KILLED |
return ResponseEntity.ok().body(body); |
228 | } | |
229 | ||
230 | UserCommons uc = UserCommons.builder() | |
231 | .user(u) | |
232 | .commons(joinedCommons) | |
233 | .username(username) | |
234 | .totalWealth(joinedCommons.getStartingBalance()) | |
235 | .numOfCows(0) | |
236 | .cowHealth(100) | |
237 | .cowsBought(0) | |
238 | .cowsSold(0) | |
239 | .cowDeaths(0) | |
240 | .build(); | |
241 | ||
242 | userCommonsRepository.save(uc); | |
243 | ||
244 | String body = mapper.writeValueAsString(joinedCommons); | |
245 |
1
1. joinCommon : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::joinCommon → KILLED |
return ResponseEntity.ok().body(body); |
246 | } | |
247 | ||
248 | @Operation(summary = "Delete a Commons") | |
249 | @PreAuthorize("hasRole('ROLE_ADMIN')") | |
250 | @DeleteMapping("") | |
251 | public Object deleteCommons( | |
252 | @Parameter(name="id") @RequestParam Long id) { | |
253 | ||
254 | commonsRepository.findById(id) | |
255 |
1
1. lambda$deleteCommons$4 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::lambda$deleteCommons$4 → KILLED |
.orElseThrow(() -> new EntityNotFoundException(Commons.class, id)); |
256 | ||
257 |
1
1. deleteCommons : removed call to edu/ucsb/cs156/happiercows/repositories/CommonsRepository::deleteById → KILLED |
commonsRepository.deleteById(id); |
258 | ||
259 | String responseString = String.format("commons with id %d deleted", id); | |
260 |
1
1. deleteCommons : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::deleteCommons → KILLED |
return genericMessage(responseString); |
261 | ||
262 | } | |
263 | ||
264 | @Operation(summary="Delete a user from a commons") | |
265 | @PreAuthorize("hasRole('ROLE_ADMIN')") | |
266 | @DeleteMapping("/{commonsId}/users/{userId}") | |
267 | public Object deleteUserFromCommon(@PathVariable("commonsId") Long commonsId, | |
268 | @PathVariable("userId") Long userId) throws Exception { | |
269 | ||
270 | UserCommons userCommons = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId) | |
271 |
1
1. lambda$deleteUserFromCommon$5 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::lambda$deleteUserFromCommon$5 → KILLED |
.orElseThrow(() -> new EntityNotFoundException( |
272 | UserCommons.class, "commonsId", commonsId, "userId", userId) | |
273 | ); | |
274 | ||
275 |
1
1. deleteUserFromCommon : removed call to edu/ucsb/cs156/happiercows/repositories/UserCommonsRepository::delete → KILLED |
userCommonsRepository.delete(userCommons); |
276 | ||
277 | String responseString = String.format("user with id %d deleted from commons with id %d, %d users remain", userId, commonsId, commonsRepository.getNumUsers(commonsId).orElse(0)); | |
278 | ||
279 |
1
1. deleteUserFromCommon : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::deleteUserFromCommon → KILLED |
return genericMessage(responseString); |
280 | } | |
281 | ||
282 | public CommonsPlus toCommonsPlus(Commons c) { | |
283 | Optional<Integer> numCows = commonsRepository.getNumCows(c.getId()); | |
284 | Optional<Integer> numUsers = commonsRepository.getNumUsers(c.getId()); | |
285 | int effectiveCapacity = Commons.computeEffectiveCapacity(c, commonsRepository); | |
286 | ||
287 |
1
1. toCommonsPlus : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::toCommonsPlus → KILLED |
return CommonsPlus.builder() |
288 | .commons(c) | |
289 | .totalCows(numCows.orElse(0)) | |
290 | .totalUsers(numUsers.orElse(0)) | |
291 | .effectiveCapacity(effectiveCapacity) | |
292 | .build(); | |
293 | } | |
294 | ||
295 | @Operation(summary="Download CSV file for common stats for a given Commons ID") | |
296 | @PreAuthorize("hasRole('ROLE_ADMIN')") | |
297 | @GetMapping("/{commonsId}/download") | |
298 | public ResponseEntity<InputStreamResource> downloadCommonStats( | |
299 | @Parameter(name = "commonsId") @RequestParam Long commonsId) throws IOException{ | |
300 | ||
301 | Iterable<CommonStats> commonStatsList = commonStatsRepository.findAllByCommonsId(commonsId); | |
302 | ||
303 | String filename = String.format("commonStats%05d.csv",commonsId); | |
304 | ||
305 | ByteArrayInputStream bais = CommonStatsCSVHelper.toCSV(commonStatsList); | |
306 | InputStreamResource isr = new InputStreamResource(bais); | |
307 | ||
308 |
1
1. downloadCommonStats : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/CommonsController::downloadCommonStats → KILLED |
return ResponseEntity.ok() |
309 | .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename) | |
310 | .contentType(MediaType.parseMediaType("application/csv")) | |
311 | .body(isr); | |
312 | } | |
313 | } | |
Mutations | ||
65 |
1.1 |
|
77 |
1.1 |
|
80 |
1.1 |
|
86 |
1.1 |
|
95 |
1.1 |
|
97 |
1.1 |
|
112 |
1.1 |
|
120 |
1.1 |
|
121 |
1.1 |
|
122 |
1.1 |
|
123 |
1.1 |
|
124 |
1.1 |
|
125 |
1.1 |
|
126 |
1.1 |
|
127 |
1.1 |
|
128 |
1.1 |
|
129 |
1.1 |
|
131 |
1.1 |
|
132 |
1.1 |
|
134 |
1.1 |
|
135 |
1.1 |
|
138 |
1.1 2.2 |
|
144 |
1.1 |
|
154 |
1.1 |
|
156 |
1.1 |
|
179 |
1.1 |
|
182 |
1.1 |
|
190 |
1.1 2.2 |
|
197 |
1.1 |
|
207 |
1.1 |
|
221 |
1.1 |
|
224 |
1.1 |
|
227 |
1.1 |
|
245 |
1.1 |
|
255 |
1.1 |
|
257 |
1.1 |
|
260 |
1.1 |
|
271 |
1.1 |
|
275 |
1.1 |
|
279 |
1.1 |
|
287 |
1.1 |
|
308 |
1.1 |