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