Skip to content

Commit

Permalink
[Fix partially kbss-cvut/record-manager-ui#36] Consider Accept header…
Browse files Browse the repository at this point in the history
… when extracting exportType from request. Accept header takes precedence over exportType uri parameter.
  • Loading branch information
kostobog committed Jul 10, 2024
1 parent 397569d commit 22b49af
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/main/java/cz/cvut/kbss/study/rest/PatientRecordController.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import cz.cvut.kbss.study.security.SecurityConstants;
import cz.cvut.kbss.study.service.PatientRecordService;
import cz.cvut.kbss.study.util.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.io.InputStreamResource;
Expand All @@ -24,8 +25,10 @@
import org.springframework.web.util.UriComponentsBuilder;

import java.io.InputStream;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

@RestController
@PreAuthorize("hasRole('" + SecurityConstants.ROLE_USER + "')")
Expand Down Expand Up @@ -59,13 +62,19 @@ public List<PatientRecordDto> getRecords(
public ResponseEntity<?> exportRecords(
@RequestParam(name = "institution", required = false) String institutionKey,
@RequestParam(required = false) MultiValueMap<String, String> params,
UriComponentsBuilder uriBuilder, HttpServletResponse response) {

String exportType = Optional.ofNullable(params)
.map(p -> p.getFirst(Constants.EXPORT_TYPE_PARAM))
.orElse(MediaType.APPLICATION_JSON_VALUE);

return switch (exportType){
UriComponentsBuilder uriBuilder, HttpServletRequest request, HttpServletResponse response) {
MediaType exportType = Stream.of(
Optional.ofNullable(request.getHeader(HttpHeaders.ACCEPT)),
Optional.ofNullable(params).map(p -> p.getFirst(Constants.EXPORT_TYPE_PARAM))
).filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty())
.flatMap(s -> MediaType.parseMediaTypes(s).stream()
.max(Comparator.comparing(MediaType::getQualityValue))
).orElse(MediaType.APPLICATION_JSON)
.removeQualityValue();

return switch (exportType.toString()){
case Constants.MEDIA_TYPE_EXCEL -> exportRecordsExcel(params, response);
case MediaType.APPLICATION_JSON_VALUE -> exportRecordsAsJson(institutionKey, params, uriBuilder, response);
default -> throw new IllegalArgumentException("Unsupported export type: " + exportType);
Expand Down

0 comments on commit 22b49af

Please sign in to comment.