27/04/2019

[Spring Boot] Configure CORS

CORS (Cross-origin resource sharing) is an important security aspect of modern web applications. To prevent malicious content from being pulled into your page, usually the source(s) of the content for it are restricted to prevent external domains from serving pieces of your final page.
This functionality goes along with CSRFX-Frame-Options, SessionPolicy and SecurityHeaders to provide a complete setup for your application.

All of this can be however very easily configured in Spring version 4+ (and therefore Spring Boot 2 as well) by providing a custom SecurityConfig (WebSecurityConfigurerAdapter) that will prevent Spring Boot from autoconfiguring the security with its own defaults.

Here is a sample implementation for Spring Boot 2 that completely disables (allows everything) CORS, it comes from this StackOverflow, slightly modified:

[Spring Boot] Upload file

In Spring Boot 2, your controller can expose a POST method to accept a file upload and return a JSON response simply as such:

 @RequestMapping(value="/upload", method=RequestMethod.POST, consumes = {"multipart/form-data"}, produces=MediaType.APPLICATION_JSON_VALUE)  
 @Transactional  
 public ResponseEntity<String> uploadFile(@ModelAttribute FileUploadRequest fileUploadRequest) {  
   
  fileUploadRequest.getFile(); //@TODO do something with your file  
   
  return new ResponseEntity<String>("{\"result\":\"success\"}", HttpStatus.OK);  
 }  
   
   
   
 @InitBinder  
 protected void initBinder(HttpServletRequest request,  
              ServletRequestDataBinder binder)   
 throws ServletException {  
  binder.registerCustomEditor(byte[].class,  
                new ByteArrayMultipartFileEditor());  
 }  


And the FileUploadRequest class looks something like this:

 @Accessors(chain = true)  
 @AllArgsConstructor  
 @NoArgsConstructor  
 public class FileUploadRequest {  
   private String fileName;  
   private byte[] file;  
 }  


With all the magic annotations coming from Lombok, Gradle configuration will look like this:

annotationProcessor "org.projectlombok:lombok:VERSION"
compileOnly "org.projectlombok:lombok:VERSION"

[Spring Boot] Download or display file in browser from controller

In Spring Boot 2, we can provide an endpoint that allows users to perform GET requests to download (or display) a file in their browsers as follows:

 @RequestMapping("/downloadFile/{fileId}")  
 public ResponseEntity<byte[]> downloadFile(@PathVariable("fileId") String fileId){  
  File file = null; //@TODO get your file from wherever using fileId or the logic you need  
   
  byte[] fileBytes = Files.readAllBytes(file.toPath()); //@TODO for example, but you might convert file to byte[] as you wish  
   
  HttpHeaders headers = new HttpHeaders();  
  headers.setContentType(MediaType.APPLICATION_PDF); //@TODO change accordingly!  
  headers.setContentDispositionFormData("attachment", file.getName()); //change to "inline" if you wish the browser to try do display it instead of downloading. WARNING: behaviour is browser dependent!  
  headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); //prevent caching  
  ResponseEntity<byte[]> response = new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);  
  return response;  
 }  
   
   
   
 @InitBinder  
 protected void initBinder(HttpServletRequest request,  
              ServletRequestDataBinder binder)   
 throws ServletException {  
  binder.registerCustomEditor(byte[].class,  
                new ByteArrayMultipartFileEditor());  
 }  

[Spring Boot] Send HTML email with attachment using Thymeleaf template

Thymeleaf provides a powerful and easy to use template engine that is effortlessly integrated in Spring and Spring Boot projects.

In this example we look at how to send HTML emails with attachments using a Thymeleaf template from a Spring Boot 2 project.

First of all these are the imports we need to add:

org.springframework.boot:spring-boot-starter-mail
org.springframework.boot:spring-boot-starter-thymeleaf


18/03/2019

[Ubuntu] Install Microsoft fonts

Most of the world uses Microsoft Windows and Office, therefore it might be sometimes necessary to generate documents using Microsoft fonts, which of course are only available on Windows.

For Ubuntu, the ttf-mscorefonts-installer package contains SOME of those fonts, simply install it and you can start using them AFTER regenerating the font cache with fc-cache

[Linux] Bind special key press to ALSA control action

If using ALSA, it's possible to bind special keyboard keys to action controls with a few configuration lines.

First of all, to find the available action controls, run in a terminal: amixer scontrols

Then, find the key event we need to bind to the desired action, and add it as an event,action pair in a new configuration file under /etc/acpi/events for example:

event=button/mute MUTE 00000080 00000000 K
action=/usr/bin/amixer sset 'Master',0 toggle

which in this case for my lapotop binds the mute button to the mute action. It is also possible to execute a script instead, for example:

event=ibm/hotkey HKEY 00000080 00001009
action=/etc/acpi/undock.sh

which runs some actions when the laptop is undocked.

[Linux] Find which event is generated on special keypress

To determine which ACPI event is generated when a special key is pressed, simply open a terminal and run: acpi_listen

Then press any special key (media keys and such, normal keys won't generate an event) and you will see the output eg:

button/volumedown VOLDN 00000080 00000000 K
button/mute MUTE 00000080 00000000 K
button/volumeup VOLUP 00000080 00000000 K