class BrowserMobResponseUpdater {

    public void updateResponse(final BrowserMobHttpResponse browserMobHttpResponse, final WilmaHttpResponse wilmaResponse) {

        //Note: update (proxy) response is an experimental feature only
        if (!wilmaResponse.isVolatile()) {
            return;
        }

        // From now on, the response is volatile

        // update the headers of the original response with extra headers added/removed by Resp interceptors
        Map<String, HttpHeaderChange> headerChangeMap = wilmaResponse.getHeaderChanges();
        if (headerChangeMap != null && !headerChangeMap.isEmpty()) { //we have header change requests
            for (Map.Entry<String, HttpHeaderChange> headerChangeEntry : headerChangeMap.entrySet()) {
                String headerKey = headerChangeEntry.getKey();
                HttpHeaderChange headerChange = headerChangeEntry.getValue();
                Header header = browserMobHttpResponse.getRawResponse().getFirstHeader(headerKey);

                if (headerChange instanceof HttpHeaderToBeUpdated) {
                    // it is HttpHeaderToBeChanged, so added, or updated
                    if (header != null) {
                        ((HttpHeaderToBeUpdated) headerChange).setOriginalValue(header.getValue());
                    }
                    browserMobHttpResponse.getRawResponse().addHeader(headerKey, ((HttpHeaderToBeUpdated) headerChange).getNewValue());
                    headerChange.setApplied();
                } else {
                    // it is HttpHeaderToBeRemoved
                    if (header != null) {
                        browserMobHttpResponse.getRawResponse().removeHeader(header);
                        headerChange.setApplied();
                    }
                }
            }
        }

        byte[] newBody = wilmaResponse.getNewBody();
        if (newBody != null) {
            try {
                browserMobHttpResponse.setAnswer(newBody);
                browserMobHttpResponse.getRawResponse().setEntity(new ByteArrayEntity(wilmaResponse.getNewBody()));
            } catch (IOException e) {
                //ups, were unable to set new response correctly ...
                logger.warn("Message ont-the-fly update was failed for message: " + wilmaResponse.getWilmaMessageId(), e);
            }
        }
    }

}