środa, 14 lutego 2018

Spring MVC - Redirect 404 when Optional.empty returned

Optional returned from controllers method

If you need to show 404 error page when no object found in your backend you can think of returning Optional from the controller's method and may expect Spring MVC takes care of exposing the value if present and throws 404 if empty.

Solution

The mechanism of controller advice comes to play. We can create a class that will be used to modify controller responses.

There are actually two features used:

  • @ExceptionHandler which is used for translation exceptions into 404 error response
  • ResponseBodyAdvice interface which cause body will be processed before been returned from controller endpoint.

Here you are piece of code that should gather above mentioned into one universal class

@ControllerAdvice
public class OptionalResponseControllerAdvice implements ResponseBodyAdvice {

 @Override
 public boolean supports(MethodParameter returnType, Class converterType) {
  return returnType.getParameterType().equals(Optional.class);
 }

 @Override
 public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
   Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
  if (returnType.getParameterType().equals(Optional.class)) {
   return ((Optional<?>) body).orElseThrow(() -> new NotFoundException("No object found: " + request.getURI()));
  }
  return body;
 }

 @ExceptionHandler(UnauthorizedException.class)
 public ResponseEntity<Map<String, Serializable>> handle(NotFoundException e) {
  return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
 }

}

wtorek, 13 lutego 2018

Angular 5 and underscore library

Are you missing the underscore library in your most recent Angular 5 project?

It is easier than you may think - the only you need to do is just add two dependencies to your package.json file.

Step 1. Install dependencies

You can do this with npm command.

npm install --save @types/underscore
and next
npm install --save underscore

Step 2. Use it

In order to use underscore library in your component or service class you have to import library in the following way:
import * as _ from "underscore";
That is basically all - now you can take all the goodies from underscore. For example, to fetch all unique key values from an array of key-value struct we can do this way:
public uniqueKeys(input: {[key: string]: string}[]): string[] {

   let keys = _
     .chain(input)
     .map(a => _.keys(a))
     .flatten()
     .uniq(false)
     .value()