protected BufferedImage fetchImage ( @ Nonnull final ClientHttpRequest request , @ Nonnull final MapfishMapContext transformer ) throws IOException { final String baseMetricName = getClass ( ) . getName ( ) + ".read." + StatsUtils . quotePart ( request . getURI ( ) . getHost ( ) ) ; final Timer . Context timerDownload = this . registry . timer ( baseMetricName ) . time ( ) ; try ( ClientHttpResponse httpResponse = request . execute ( ) ) { if ( httpResponse . getStatusCode ( ) != HttpStatus . OK ) { final String message = String . format ( "Invalid status code for %s (%d!=%d). The response was: '%s'" , request . getURI ( ) , httpResponse . getStatusCode ( ) . value ( ) , HttpStatus . OK . value ( ) , httpResponse . getStatusText ( ) ) ; this . registry . counter ( baseMetricName + ".error" ) . inc ( ) ; if ( getFailOnError ( ) ) { throw new RuntimeException ( message ) ; } else { LOGGER . info ( message ) ; return createErrorImage ( transformer . getPaintArea ( ) ) ; } } final List < String > contentType = httpResponse . getHeaders ( ) . get ( "Content-Type" ) ; if ( contentType == null || contentType . size ( ) != 1 ) { LOGGER . debug ( "The image {} didn't return a valid content type header." , request . getURI ( ) ) ; } else if ( ! contentType . get ( 0 ) . startsWith ( "image/" ) ) { final byte [ ] data ; try ( InputStream body = httpResponse . getBody ( ) ) { data = IOUtils . toByteArray ( body ) ; } LOGGER . debug ( "We get a wrong image for {}, content type: {}\nresult:\n{}" , request . getURI ( ) , contentType . get ( 0 ) , new String ( data , StandardCharsets . UTF_8 ) ) ; this . registry . counter ( baseMetricName + ".error" ) . inc ( ) ; return createErrorImage ( transformer . getPaintArea ( ) ) ; } final BufferedImage image = ImageIO . read ( httpResponse . getBody ( ) ) ; if ( image == null ) { LOGGER . warn ( "Cannot read image from %a" , request . getURI ( ) ) ; this . registry . counter ( baseMetricName + ".error" ) . inc ( ) ; if ( getFailOnError ( ) ) { throw new RuntimeException ( "Cannot read image from " + request . getURI ( ) ) ; } else { return createErrorImage ( transformer . getPaintArea ( ) ) ; } } timerDownload . stop ( ) ; return image ; } catch ( Throwable e ) { this . registry . counter ( baseMetricName + ".error" ) . inc ( ) ; throw e ; } }
Fetch the given image from the web .