ś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.


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

public class OptionalResponseControllerAdvice implements ResponseBodyAdvice {

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

 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;

 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 miss underscore library in your most recent Angular 5 application?

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

Install dependecies

You can do this with npm command.

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

How to 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 = _
     .map(a => _.keys(a))

piątek, 12 stycznia 2018

HttpClient - ssl - unable to find valid certification path to requested target

The javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target usually stands for issues with accepting/validating SSL/TLS certificate given by web server. ClientHandshaker class is responsible for handshaking from the client side. It shares common logic such control flow and key generation with its counterpart ServerHandshaker though common parent class called Handshaker.
void processMessage(byte type, int messageLen) throws IOException {
 switch (type) {
 case HandshakeMessage.ht_certificate:
       if (keyExchange == K_DH_ANON || keyExchange == K_ECDH_ANON
                    || keyExchange == K_KRB5 || keyExchange == K_KRB5_EXPORT) {
                    "unexpected server cert chain");
                // NOTREACHED
            this.serverCertificate(new CertificateMsg(input));
            serverKey =
Let's go briefly to the details 1. Creating CerificateMsg just takes input as a HandshakeInStream, reads first 24 bytes as a chainLenght, so can read the cert as a byte array and finally instantiates X.509 certificate, as below
cf = CertificateFactory.getInstance("X.509");
cf.generateCertificate(new ByteArrayInputStream(cert)
2. serverCertificate method will deletegate cerificate validation to the Trust Manager taken from sslContext. To solve the error the sslcontext have to be feeded with TrustStrategy that accepts self-sighed cerificates as trusted. Apache Http Client comes with org.apache.http.conn.ssl.TrustSelfSignedStrategy to do so.
                .setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContextBuilder.create()
      .build(), NoopHostnameVerifier.INSTANCE))

poniedziałek, 1 stycznia 2018

bash - how to check if string starts with specific prefix

Let's assume we want to process only files that start with specific string (eg. 2018). Our script is listening to every new file appeared in given directory, so let's assume we cannot do this at the os level directly. Our script is invoking the following command:
$ convert.sh /path/to/2018_file.pdf 
To process all files begins with 2018 we can do this way:
for i in `ls`; do [[ $i == 2018* ]] && echo $i; done
Or, if we'd like to process all but 2018 files we can do this way:
for i in `ls`; do [[ $i != 2018* ]] && echo $i; done
Or even more general with help of regexp we can do
for i in `ls`; do [[ $i =~ ^2018 ]] && echo $i; done
Happy New Year!!

środa, 13 grudnia 2017

bash - how to concatenate array with given delimiter

Let's declare array
 a=(aa bb cc) 
Now we can display the content with
$echo ${a[@]}
aa bb cc
First, give some naive solutions a try
$for el in ${a[@]}; do echo -n ,$el; done
$printf ",%s" ${a[@]}
Both work well, right? Hmm.. almost.

The last thing to do is get rid of the first comma

$for ab in ${a[@]}; do echo -n ,${ab}; done | cut -c2-

wtorek, 21 listopada 2017

Why Spring returns 404 for my request?

When Spring Web MVC returns 404 in response to our request it means that cannot find handler for request "signature". As a signature we mean request mapping and request parameters.

How Spring resolves handler for a given url address?

The class responsible for matching mappings with requests is org.springframework.web.servlet.DispatcherServlet. The specific handler will be determined by applying handler mappings. Method responsible for that is called getHandler and it takes HTTP servlet request (Good old javax.servlet.http.HttpServletRequest instance). It basically goes through all registered handler mappings and tests each in order. The first match win. As the result, it returns an object of HandlerExecutionChain class.

protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {..}

Resolving details

At first, it looks for a direct match. eg /api/logs/3/4 Next, it starts to look for matching patterned paths eg. /api/logs/{parent}/{child}. Takes all matched and is looking for the best match.

sobota, 14 października 2017

Watchman - How to automatically copy modified files to the docker container

Watchman package is a really great tool but requires a while to understand its magic. To install it just type
$ brew install watchman
In 4.9 version it comes with three commands:
  • watchman
  • watchman-wait
  • watchman-make

The latter two are just utilities under the first one.

Lets focus on watchman itself and one of its outstanding feature called triggers. Actually, it is what it sounds to be - a mechanism that causes invoking given action on a given event happened (for example copying file to the remote server once it appear in certain folder)

Watchman Trigger Examples

Copying js files
 watchman -- trigger $PWD cr '**/*.js' '**/*.css' '**/*.html' '**/*.php' -- sh push.sh
Which basically causes all js, css, html and php files from the current folder are passed to push.sh script.

Push.sh script can look like this:

for i in $@
 docker cp $i centrum:/var/www/html/$i