Spring: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
No edit summary
Line 41: Line 41:
| valign="top" |
| valign="top" |
* [https://blog.trifork.com/2018/08/28/spring-data-native-queries-and-projections-in-kotlin/ Spring Data Native Queries & Projections in Kotlin]
* [https://blog.trifork.com/2018/08/28/spring-data-native-queries-and-projections-in-kotlin/ Spring Data Native Queries & Projections in Kotlin]
* [https://stackoverflow.com/questions/6349421/ Jackson to de-serialize an array of objects]
* [https://stackoverflow.com/questions/45230898/ Spring Path Variable with Multiple Slash]
* [https://stackoverflow.com/questions/45230898/ Spring Path Variable with Multiple Slash]
* [https://www.baeldung.com/spring-template-engines Template Engines for Spring]
* [https://www.baeldung.com/spring-template-engines Template Engines for Spring]

Revision as of 04:56, 15 December 2022

Multiple Slash Path Variable

@RestController
@RequestMapping("/api/file")
public class FileController {
    @Autowired
    FileService fileService;

    /**
     * File download requests handler
     *
     * @param prefix of relative file path
     *    <ul>
     *        <li>certificates/Policy-8691-191939b9-526b-4933-b05c-61e672609dcc.pdf</li>
     *        <li>certificates/extras/Policy_Wording.pdf</li>
     *    </ul>
     */
    @GetMapping("/{prefix}/**")
    public void fetch(
            @PathVariable("prefix") final String prefix,
            final HttpServletResponse response,
            final HttpServletRequest request
    ) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String name = (!ObjectUtils.isEmpty(prefix)) ? path.substring(path.indexOf(prefix)) : null;
        try {
            if (!ObjectUtils.isEmpty(name)) {
                InputStream inputStream = fileService.fetch(name);
                OutputStream outputStream = response.getOutputStream();
                IOUtils.copy(inputStream, outputStream);
            } else throw new FileNotFoundException(name);
        } catch (IOException e) {
            throw new InternalServerException(e.getMessage(), e);
        }
    }
}

References