class BrowserMobRequestUpdater {

    public void updateRequest(final BrowserMobHttpRequest browserMobHttpRequest, final WilmaHttpRequest wilmaRequest) {
        // Update the headers of the original request with extra headers added/removed by Req interceptors
        // Note, that when we redirect the request to the stub, we always add the message id to the extra headers part

        Map<String, HttpHeaderChange> headerChangeMap = wilmaRequest.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 = browserMobHttpRequest.getMethod().getFirstHeader(headerKey);

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

        //update the body
        byte[] newBody = wilmaRequest.getNewBody();
        if (newBody != null) {
            if (browserMobHttpRequest.getMethod() instanceof HttpEntityEnclosingRequestBase) {
                HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) browserMobHttpRequest.getMethod();
                enclosingRequest.setEntity(new ByteArrayEntity(wilmaRequest.getNewBody()));
            }
        }
        //set response volatility approach
        browserMobHttpRequest.setResponseVolatile(wilmaRequest.isResponseVolatile());
        //switch between original uri (proxy mode selected) or wilma internal uri (stub mode selected)
        browserMobHttpRequest.getMethod().setURI(wilmaRequest.getUri());
    }

}