<p>The following code examples show how to create different response actions.</p>
<button id="button_response_literal_body_only" class="accordion">literal response with body only</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
<pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    // this request matcher matches every request
    .when(
        request()
    )
    .respond(
        response()
            .withBody("some_response_body")
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    // if no request matcher is specified then every request matched
    "httpResponse": {
        "body": "some_response_body"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code"># if no request matcher is specified then every request matched
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpResponse": {
        "body": "some_response_body"
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_file_body" class="accordion">response with body loaded from file</button>
<div class="panel">
    <p>FileBody loads the response content from a file at response time, rather than embedding the content directly in the expectation. This is useful when the response payload is large (e.g. sample JSON or XML files), generated externally, or shared across multiple expectations. The file path can be absolute or relative to the working directory.</p>
    <button class="accordion inner">Java</button>
    <div class="panel">
<pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/api/data")
    )
    .respond(
        response()
            .withBodyFromFile("/path/to/response.json")
    );

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/api/data")
    )
    .respond(
        response()
            .withBodyFromFile("/path/to/response.json", MediaType.APPLICATION_JSON)
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/api/data"
    },
    "httpResponse": {
        "body": {
            "type": "FILE",
            "filePath": "/path/to/response.json",
            "contentType": "application/json"
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/api/data"
    },
    "httpResponse": {
        "body": {
            "type": "FILE",
            "filePath": "/path/to/response.json",
            "contentType": "application/json"
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_UTF16_body" class="accordion">literal response with UTF16 body</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    // this request matcher matches every request
    .when(
        request()
    )
    .respond(
        response()
            .withHeader(
                CONTENT_TYPE.toString(),
                MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()
            )
            .withBody("我说中国话".getBytes(Charsets.UTF_16))
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    // if no request matcher is specified then every request matched
    "httpResponse": {
        "headers": {
            "content-type": ["text/plain; charset=utf-16"]
        },
        "body": {
            "type": "BINARY",
            "base64Bytes": "/v9iEYv0Ti1W/Yvd"
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code"># if no request matcher is specified then every request matched
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpResponse": {
        "headers": {
            "content-type": ["text/plain; charset=utf-16"]
        },
        "body": {
            "type": "BINARY",
            "base64Bytes": "/v9iEYv0Ti1W/Yvd"
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_json_UTF8_body" class="accordion">json response with UTF8 body</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withMethod("GET")
            .withPath("/farsi_body")
    )
    .respond(
        response()
            .withBody(json("سلام", MediaType.APPLICATION_JSON_UTF_8))
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "method": "GET",
        "path": "/simple"
    },
    "httpResponse": {
        "body": {
            "type": "STRING",
            "string": "سلام",
            "contentType": "text/plain; charset=utf-8"
         }
    },
    "times": {
        "unlimited": true
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT http://localhost:1080/mockserver/expectation -H "Content-Type: application/json; charset=utf-8" --data '{
    "httpRequest": {
        "method": "GET",
        "path": "/simple"
    },
    "httpResponse": {
        "body": {
            "type": "STRING",
            "string": "سلام",
            "contentType": "text/plain; charset=utf-8"
         }
    },
    "times": {
        "unlimited": true
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_with_header" class="accordion">json response with header</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    // this request matcher matches every request
    .when(
        request()
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withHeader("Content-Type", "plain/text")
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    // if no request matcher is specified then every request matched
    "httpResponse": {
        "headers": {
            "Content-Type": ["plain/text"]
        },
        "body": "some_response_body"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT http://localhost:1080/mockserver/expectation -H "Content-Type: application/json; charset=utf-8" --data '{
    "httpResponse": {
        "headers": {
            "Content-Type": ["plain/text"]
        },
        "body": "some_response_body"
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_with_cookie" class="accordion">json response with cookie</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    // this request matcher matches every request
    .when(
        request()
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withHeader("Content-Type", "plain/text")
            .withCookie("Session", "97d43b1e-fe03-4855-926a-f448eddac32f")
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    // if no request matcher is specified then every request matched
    "httpResponse": {
        "headers": {
            "Content-Type": ["plain/text"]
        },
        "cookies": {
            "Session": "97d43b1e-fe03-4855-926a-f448eddac32f"
        },
        "body": "some_response_body"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT http://localhost:1080/mockserver/expectation -H "Content-Type: application/json; charset=utf-8" --data '{
    "httpResponse": {
        "headers": {
            "Content-Type": ["plain/text"]
        },
        "cookies": {
            "Session": "97d43b1e-fe03-4855-926a-f448eddac32f"
        },
        "body": "some_response_body"
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_status_code_and_reason_phrase" class="accordion">literal response with status code and reason phrase</button>
<div class="panel">
    <p><strong>Note for WAR deployments:</strong> Jakarta Servlet 6 (Tomcat 11+, Jetty 12+, WildFly 32+) removed support for custom HTTP reason phrases via <code>HttpServletResponse.setStatus(int, String)</code>, so when MockServer is deployed as a WAR in a Servlet 6 container only the status code is sent on the wire and the reason phrase is silently dropped. The reason phrase still works in MockServer's standalone, Docker, and Netty deployments.</p>
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withMethod("POST")
            .withPath("/some/path")
    )
    .respond(
        response()
            .withStatusCode(418)
            .withReasonPhrase("I'm a teapot")
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "method": "POST",
        "path": "/some/path"
    },
    "httpResponse": {
        "statusCode": 418,
        "reasonPhrase": "I'm a teapot"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "method": "POST",
        "path": "/some/path"
    },
    "httpResponse": {
        "statusCode": 418,
        "reasonPhrase": "I'm a teapot"
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_binary_PNG_body" class="accordion">literal response with binary PNG body</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("org/mockserver/examples/mockserver/test.png"));
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/ws/rest/user/[0-9]+/icon/[0-9]+\\.png")
    )
    .respond(
        response()
            .withStatusCode(HttpStatusCode.OK_200.code())
            .withHeaders(
                header(CONTENT_TYPE.toString(), MediaType.PNG.toString()),
                header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"")
            )
            .withBody(binary(pngBytes))
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/ws/rest/user/[0-9]+/icon/[0-9]+\\.png"
    },
    "httpResponse": {
        "statusCode": 200,
        "headers": {
            "content-type": ["image/png"],
            "content-disposition": ["form-data; name=\"test.png\"; filename=\"test.png\""]
        },
        "body": {
            "type": "BINARY",
            "base64Bytes": " "
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/{{ site.mockserver_api_version }}#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/ws/rest/user/[0-9]+/icon/[0-9]+\\.png"
    },
    "httpResponse": {
        "statusCode": 200,
        "headers": {
            "content-type": ["image/png"],
            "content-disposition": ["form-data; name=\"test.png\"; filename=\"test.png\""]
        },
        "body": {
            "type": "BINARY",
            "base64Bytes": " "
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_with_10_second_delay" class="accordion">literal response with 10 second delay</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withDelay(TimeUnit.SECONDS, 10)
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "body": "some_response_body",
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "body": "some_response_body",
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_with_distribution_delay" class="accordion">response with distribution-based delay (for realistic latency simulation)</button>
<div class="panel">
    <p>Distribution-based delays add realistic variability to response times. Each request samples a new random delay from the chosen distribution. Three distribution types are supported:</p>
    <ul>
        <li><strong>UNIFORM</strong> — equal probability across a min/max range; use for simple random variation</li>
        <li><strong>LOG_NORMAL</strong> — most values near the median with a long tail of slower responses; best for realistic network/API latency simulation. Specified via median and p99 (99th percentile)</li>
        <li><strong>GAUSSIAN</strong> — bell curve centered on the mean; use when you know the average latency and expected spread (standard deviation)</li>
    </ul>
    <p>Distribution-based delays are supported on all action types including response, forward, error, template, and callback actions.</p>
    <p>Sampled values are clamped to a minimum of 0 and a maximum of 86,400,000 milliseconds (24 hours). Validation constraints: UNIFORM requires <code>min &gt;= 0</code> and <code>max &gt;= min</code>; LOG_NORMAL requires <code>median &gt; 0</code> and <code>p99 &gt;= median</code>; GAUSSIAN requires <code>mean &gt;= 0</code> and <code>stdDev &gt;= 0</code>.</p>
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">// uniform random delay between 100ms and 500ms
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withDelay(Delay.uniform(TimeUnit.MILLISECONDS, 100, 500))
    );

// log-normal delay (realistic latency distribution) with median 200ms and p99 of 800ms
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withDelay(Delay.logNormal(TimeUnit.MILLISECONDS, 200, 800))
    );

// gaussian delay with mean 200ms and standard deviation of 50ms
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withDelay(Delay.gaussian(TimeUnit.MILLISECONDS, 200, 50))
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
// uniform random delay between 100ms and 500ms
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "body": "some_response_body",
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "UNIFORM",
                "min": 100,
                "max": 500
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

// log-normal delay with median 200ms and p99 of 800ms
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "body": "some_response_body",
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

// gaussian delay with mean 200ms and standard deviation of 50ms
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "body": "some_response_body",
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "GAUSSIAN",
                "mean": 200,
                "stdDev": 50
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code"># uniform random delay between 100ms and 500ms
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "body": "some_response_body",
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "UNIFORM",
                "min": 100,
                "max": 500
            }
        }
    }
}'

# log-normal delay with median 200ms and p99 of 800ms
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "body": "some_response_body",
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}'

# gaussian delay with mean 200ms and standard deviation of 50ms
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "body": "some_response_body",
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "GAUSSIAN",
                "mean": 200,
                "stdDev": 50
            }
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_differently_for_same_request" class="accordion">respond differently for the same request</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">MockServerClient mockServerClient = new MockServerClient("localhost", 1080);

// respond once with 200, then respond twice with 204, then
// respond with 404 as no remaining active expectations
mockServerClient
    .when(
        request()
            .withPath("/some/path"),
        Times.exactly(1)
    )
    .respond(
        response()
            .withStatusCode(200)
    );

mockServerClient
    .when(
        request()
            .withPath("/some/path"),
        Times.exactly(2)
    )
    .respond(
        response()
            .withStatusCode(204)
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var client = require('mockserver-client').mockServerClient("localhost", 1080);

// respond once with 200, then respond twice with 204, then
// respond with 404 as no remaining active expectations
client.mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "statusCode": 200
    },
    "times": {
        "remainingTimes": 1,
        "unlimited": false
    }
}).then(
    function () {
        console.log("first expectation created");

        client.mockAnyResponse({
            "httpRequest": {
                "path": "/some/path"
            },
            "httpResponse": {
                "statusCode": 204
            },
            "times": {
                "remainingTimes": 2,
                "unlimited": false
            }
        }).then(
            function () {
                console.log("second expectation created");
            },
            function (error) {
                console.log(error);
            }
        );
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code"># respond once with 200, then respond twice with 204, then
# respond with 404 as no remaining active expectations

curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "statusCode": 200
    },
    "times": {
        "remainingTimes": 1,
        "unlimited": false
    }
}'

curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponse": {
        "statusCode": 204
    },
    "times": {
        "remainingTimes": 2,
        "unlimited": false
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_with_connection_options_to_suppress_headers" class="accordion">literal response with connection options to suppress headers</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withConnectionOptions(
                connectionOptions()
                    .withSuppressConnectionHeader(true)
                    .withSuppressContentLengthHeader(true)
            )
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_response_body",
        "connectionOptions" : {
            "suppressContentLengthHeader" : true,
            "suppressConnectionHeader" : true
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_response_body",
        "connectionOptions" : {
            "suppressContentLengthHeader" : true,
            "suppressConnectionHeader" : true
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_with_connection_options_to_override_headers" class="accordion">literal response with connection options to override headers</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withConnectionOptions(
                connectionOptions()
                    .withKeepAliveOverride(false)
                    .withContentLengthHeaderOverride(10)
            )
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_response_body",
        "connectionOptions" : {
            "contentLengthHeaderOverride" : 10,
            "keepAliveOverride" : false
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_response_body",
        "connectionOptions" : {
            "contentLengthHeaderOverride" : 10,
            "keepAliveOverride" : false
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_with_connection_options_to_close_socket" class="accordion">literal response with connection options to close socket</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withConnectionOptions(
                connectionOptions()
                    .withCloseSocket(true)
            )
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_response_body",
        "connectionOptions" : {
            "closeSocket" : true
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_response_body",
        "connectionOptions" : {
            "closeSocket" : true
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_with_connection_options_to_close_socket_after_delay" class="accordion">literal response with connection options to close socket after a delay</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_response_body")
            .withConnectionOptions(
                connectionOptions()
                    .withCloseSocket(true)
                    .withCloseSocketDelay(new Delay(MILLISECONDS, 500))
            )
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_response_body",
        "connectionOptions" : {
            "closeSocket" : true,
            "closeSocketDelay" : {
                "timeUnit" : "MILLISECONDS",
                "value" : 500
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_response_body",
        "connectionOptions" : {
            "closeSocket" : true,
            "closeSocketDelay" : {
                "timeUnit" : "MILLISECONDS",
                "value" : 500
            }
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_literal_with_chunked_dribble_delay" class="accordion">literal response with chunked dribble delay</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        response()
            .withBody("some_long_response_body_delivered_in_chunks")
            .withConnectionOptions(
                connectionOptions()
                    .withChunkSize(10)
                    .withChunkDelay(new Delay(MILLISECONDS, 500))
            )
    );</code></pre>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some/path"
    },
    "httpResponse" : {
        "body" : "some_long_response_body_delivered_in_chunks",
        "connectionOptions" : {
            "chunkSize" : 10,
            "chunkDelay" : {
                "timeUnit" : "MILLISECONDS",
                "value" : 500
            }
        }
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_javascript_templated_response" class="accordion">javascript templated response</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">// $!request.headers['Session-Id'] returns an array of values because headers and queryStringParameters have multiple values
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        template(
            HttpTemplate.TemplateType.JAVASCRIPT,
            "return {\n" +
                "     'statusCode': 200,\n" +
                "     'cookies': {\n" +
                "          'session' : request.headers['Session-Id'][0]\n" +
                "     },\n" +
                "     'headers': {\n" +
                "          'Date' : Date()\n" +
                "     },\n" +
                "     'body': JSON.stringify(\n" +
                "               {\n" +
                "                    method: request.method,\n" +
                "                    path: request.path,\n" +
                "                    body: request.body\n" +
                "               }\n" +
                "          )\n" +
                "};"
        )
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
// $!request.headers['Session-Id'] returns an array of values because headers and queryStringParameters have multiple values
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponseTemplate": {
        "template": "return { statusCode: 200, cookies: { session: request.headers[\"Session-Id\"] && request.headers[\"Session-Id\"][0] }, headers: { Date: [ Date() ] }, body: JSON.stringify({method: request.method, path: request.path, body: request.body}) };",
        "templateType": "JAVASCRIPT"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponseTemplate": {
        "template": "return { statusCode: 200, cookies: { session: request.headers[\"Session-Id\"] && request.headers[\"Session-Id\"][0] }, headers: { Date: [ Date() ] }, body: JSON.stringify({method: request.method, path: request.path, body: request.body}) };",
        "templateType": "JAVASCRIPT"
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_javascript_templated_response_with_body_as_string" class="accordion">javascript templated response reading request body</button>
<div class="panel">
    <p>To simplify handling different types of bodies, JavaScript and Velocity templates, have access to both an object <code class="inline code">request.body</code> field and a string <code class="inline code">request.bodyAsString</code> field which can be used as shown in the examples below.</p>
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        template(
            HttpTemplate.TemplateType.JAVASCRIPT,
            "return { statusCode: 200, headers: { Date: [ Date() ] }, body: JSON.stringify({is_active: JSON.parse(request.bodyAsString).is_active, id: \"1234\", name: \"taras\"}) };"
        )
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponseTemplate": {
        "template": "return { statusCode: 200, headers: { Date: [ Date() ] }, body: JSON.stringify({is_active: JSON.parse(request.bodyAsString).is_active, id: \"1234\", name: \"taras\"}) };",
        "templateType": "JAVASCRIPT"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponseTemplate": {
        "template": "return { statusCode: 200, headers: { Date: [ Date() ] }, body: JSON.stringify({is_active: JSON.parse(request.bodyAsString).is_active, id: \"1234\", name: \"taras\"}) };",
        "templateType": "JAVASCRIPT"
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_javascript_templated_response_with_delay" class="accordion">javascript templated response with delay</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">String template = "" +
    "if (request.method === 'POST' && request.path === '/somePath') {\n" +
    "    return {\n" +
    "        'statusCode': 200,\n" +
    "        'body': JSON.stringify({name: 'value'})\n" +
    "    };\n" +
    "} else {\n" +
    "    return {\n" +
    "        'statusCode': 406,\n" +
    "        'body': request.body\n" +
    "    };\n" +
    "}";

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        template(HttpTemplate.TemplateType.JAVASCRIPT)
            .withTemplate(template)
            .withDelay(TimeUnit.MINUTES, 2)
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {"path": "/some/path"},
    "httpResponseTemplate": {
        "template": "if (request.method === \"POST\" && request.path === \"/some/path\") { return { statusCode: 200, body: JSON.stringify({name: \"value\"}) }; } else { return { statusCode: 406, body: request.body }; }",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "MINUTES", "value": 2}
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {"path": "/some/path"},
    "httpResponseTemplate": {
        "template": "if (request.method === \"POST\" && request.path === \"/some/path\") { return { statusCode: 200, body: JSON.stringify({name: \"value\"}) }; } else { return { statusCode: 406, body: request.body }; }",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "MINUTES", "value": 2}
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_javascript_velocity_templated_response" class="accordion">velocity templated response</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">// $!request.headers['Session-Id'] and $!request.headers['User-Agent'] both returns an
// array of values because headers and queryStringParameters have multiple values
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        template(
            HttpTemplate.TemplateType.VELOCITY,
            "{\n" +
                "     \"statusCode\": 200,\n" +
                "     \"cookies\": { \n" +
                "          \"session\": \"$!request.headers['Session-Id'][0]\"\n" +
                "     },\n" +
                "     \"headers\": {\n" +
                "          \"Client-User-Agent\": [ \"$!request.headers['User-Agent'][0]\" ]\n" +
                "     },\n" +
                "     \"body\": $!request.body\n" +
                "}"
        )
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
// $!request.headers['Session-Id'] and $!request.headers['User-Agent'] both returns an
// array of values because headers and queryStringParameters have multiple values
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponseTemplate": {
        "template": "{ \"statusCode\": 200, \"cookies\": { \"session\": \"$!request.headers[\"Session-Id\"][0]\" }, \"headers\": { \"Client-User-Agent\": [ \"$!request.headers[\"User-Agent\"][0]\" ] }, \"body\": \"$!request.body\" }",
        "templateType": "VELOCITY"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponseTemplate": {
        "template": "{ \"statusCode\": 200, \"cookies\": { \"session\": \"$!request.headers[\"Session-Id\"][0]\" }, \"headers\": { \"Client-User-Agent\": [ \"$!request.headers[\"User-Agent\"][0]\" ] }, \"body\": \"$!request.body\" }",
        "templateType": "VELOCITY"
    }
}'</code></pre>
        <p>See <a  href="https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/6.1.x#/expectation/put_expectation" target="_blank" rel="noopener noreferrer">REST API</a> for full JSON specification</p>
    </div>
</div>
<button id="button_response_class_callback" class="accordion">class callback</button>
<div class="panel">
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">public class CallbackActionExamples {

    public void responseClassCallback() {
        new ClientAndServer(1080)
            .when(
                request()
                    .withPath("/some.*")
            )
            .respond(
                callback()
                    .withCallbackClass(TestExpectationResponseCallback.class)
            );
    }

    public static class TestExpectationResponseCallback implements ExpectationResponseCallback {

        @Override
        public HttpResponse handle(HttpRequest httpRequest) {
            if (httpRequest.getPath().getValue().endsWith("/path")) {
                return response()
                    .withStatusCode(HttpStatusCode.ACCEPTED_202.code())
                    .withHeaders(
                        header("x-callback", "test_callback_header"),
                        header("Content-Length", "a_callback_response".getBytes(UTF_8).length),
                        header("Connection", "keep-alive")
                    )
                    .withBody("a_callback_response");
            } else {
                return notFoundResponse();
            }
        }
    }

}</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some.*"
    },
    "httpResponseClassCallback": {
        "callbackClass": "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationResponseCallback"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
    </div>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code">curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some.*"
    },
    "httpResponseClassCallback" : {
        "callbackClass" : "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationResponseCallback"
    }
}'</code></pre>
    </div>
    <p>To use a class callback MockServer must be able to <strong>load the class from the classpath</strong>.</p>
    <p>The callback class must:</p>
    <ul>
        <li>implement <ul><li><strong><span class="this_value">org.mockserver.mock.action.ExpectationResponseCallback</span></strong> to dynamically override the <strong>response</strong></li></ul></li>
        <li>have a zero argument constructor</li>
        <li>be available in the classpath of the MockServer</li>
    </ul>

    <p>If MockServer is started using the the <a href="/mock_server/running_mock_server.html#junit_rule">JUnit 4 @Rule</a>, the <a href="/mock_server/running_mock_server.html#junit_test_extension">JUnit 5 Test Extension</a>, <a href="/mock_server/running_mock_server.html#client_api">ClientAndServer</a> or directly using <span class="inline_code">org.mockserver.netty.MockServer</span> then any class present in the main or test classpaths will be visible to MockServer.</p>

    <p>If MockServer is started using the <a href="/mock_server/running_mock_server.html#maven_plugin">maven plugin</a> only the non-forked goals (such as <span class="element_value">runAndWait</span> and <span class="element_value">start</span>) will be able to load classes from the main and test classpaths.  It is possible to use classes from a separate maven dependency, however, this dependency must be specified in the plugin configuration <span class="element">dependencies</span> section.  Any dependency added to the plugin configuration <span class="element">dependencies</span> section will then be visible to MockServer run using both forked and non-forked goals.</p>

    <p>The following configuration shows how to use classes from a separate maven dependency in callback actions.</p>

    <pre><code class="code xml"> &lt;<span class="element">plugin</span>&gt;
     &lt;<span class="element">groupId</span>&gt;<span class="element_value">org.mock-server</span>&lt;/<span class="element">groupId</span>&gt;
     &lt;<span class="element">artifactId</span>&gt;<span class="element_value">mockserver-maven-plugin</span>&lt;/<span class="element">artifactId</span>&gt;
     &lt;<span class="element">version</span>&gt;<span class="element_value">{{ site.mockserver_version }}</span>&lt;/<span class="element">version</span>&gt;
     &lt;<span class="element">configuration</span>&gt;
        &lt;<span class="element">serverPort</span>&gt;<span class="element_value">1080</span>&lt;/<span class="element">serverPort</span>&gt;
        &lt;<span class="element">logLevel</span>&gt;<span class="element_value">DEBUG</span>&lt;/<span class="element">logLevel</span>&gt;
        &lt;<span class="element">pipeLogToConsole</span>&gt;<span class="element_value">true</span>&lt;/<span class="element">pipeLogToConsole</span>&gt;
     &lt;/<span class="element">configuration</span>&gt;
     &lt;<span class="element">executions</span>&gt;
         &lt;<span class="element">execution</span>&gt;
             &lt;<span class="element">id</span>&gt;<span class="element_value">pre-integration-test</span>&lt;/<span class="element">id</span>&gt;
             &lt;<span class="element">phase</span>&gt;<span class="element_value">pre-integration-test</span>&lt;/<span class="element">phase</span>&gt;
             &lt;<span class="element">goals</span>&gt;
                 &lt;<span class="element">goal</span>&gt;<span class="element_value">runForked</span>&lt;/<span class="element">goal</span>&gt;
             &lt;/<span class="element">goals</span>&gt;
         &lt;/<span class="element">execution</span>&gt;
         &lt;<span class="element">execution</span>&gt;
             &lt;<span class="element">id</span>&gt;<span class="element_value">post-integration-test</span>&lt;/<span class="element">id</span>&gt;
             &lt;<span class="element">phase</span>&gt;<span class="element_value">post-integration-test</span>&lt;/<span class="element">phase</span>&gt;
             &lt;<span class="element">goals</span>&gt;
                 &lt;<span class="element">goal</span>&gt;<span class="element_value">stopForked</span>&lt;/<span class="element">goal</span>&gt;
             &lt;/<span class="element">goals</span>&gt;
         &lt;/<span class="element">execution</span>&gt;
     &lt;/<span class="element">executions</span>&gt;
     &lt;<span class="element">dependencies</span>&gt;
         &lt;<span class="element">dependency</span>&gt;
             &lt;<span class="element">groupId</span>&gt;<span class="element_value">com.my-domain</span>&lt;/<span class="element">groupId</span>&gt;
             &lt;<span class="element">artifactId</span>&gt;<span class="element_value">my-callback-dependency</span>&lt;/<span class="element">artifactId</span>&gt;
             &lt;<span class="element">version</span>&gt;<span class="element_value">1.0.0</span>&lt;/<span class="element">version</span>&gt;
         &lt;/<span class="element">dependency</span>&gt;
     &lt;/<span class="element">dependencies</span>&gt;
 &lt;/<span class="element">plugin</span>&gt;</code></pre>

    <p>If MockServer is started using the <a href="/mock_server/running_mock_server.html#running_from_command_line">command line</a> then the callback classes must be added to the JVM using the classpath command line switch (<strong>cp</strong> or <strong>classpath</strong>). The <strong>classpath</strong> switch is ignored by the JVM if the
        <strong>jar</strong> switch is used. So to run the MockServer from the command line directly (with mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar) you must specify the <strong>org.mockserver.cli.Main</strong> main class specifically and not use the <strong>jar</strong> switch as follows.</p>

    <pre><code class="code">java -Dfile.encoding=UTF-8 -cp mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar:my-callback-dependency.jar org.mockserver.cli.Main -serverPort 1080</code></pre>
</div>
<button id="button_response_method_or_closure_callback" class="accordion">method / closure callback</button>
<div class="panel">
    <button class="accordion inner">Java 7</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        new ExpectationResponseCallback() {
            @Override
            public HttpResponse handle(HttpRequest httpRequest) {
                if (httpRequest.getMethod().getValue().equals("POST")) {
                    return response()
                        .withStatusCode(ACCEPTED_202.code())
                        .withHeaders(
                            header("x-object-callback", "test_object_callback_header")
                        )
                        .withBody("an_object_callback_response");
                } else {
                    return notFoundResponse();
                }
            }
        }
    );</code></pre>
    </div>
    <button class="accordion inner">Java 8+</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        request -> {
            if (request.getMethod().getValue().equals("POST")) {
                return response()
                    .withStatusCode(ACCEPTED_202.code())
                    .withHeaders(
                        header("x-object-callback", "test_object_callback_header")
                    )
                    .withBody("an_object_callback_response");
            } else {
                return notFoundResponse();
            }
        }
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
var callback = function (request) {
    if (request.method === 'POST') {
        return {
            'statusCode': 201,
            'header': {
                "x-object-callback": ["test_object_callback_header"]
            },
            'body': "an_object_callback_response"
        };
    } else {
        return {
            'statusCode': 404
        };
    }
};
mockServerClient("localhost", 1080)
    .mockWithCallback(
        {
            'path': '/some/path'
        },
        callback
    )
    .then(
        function () {
            console.log("expectation created");
        },
        function (error) {
            console.log(error);
        }
    );</code></pre>
    </div>
    <p>When using <span class="inline_code">org.mockserver.client.MockServerClient</span> each method / closure callback has a separate web socket client.  To ensure the number of total threads does not grow too large for large numbers of method / closure callback expectations the default event loop thread pool for the web socket client is kept fairly low.  However, if an extremely large load is matched against a single method / closure callback expectation the event loop thread pool may not be large enough for its web socket client.</p>
    <p>The number of threads for the event loop thread pool for each web socket client (i.e. for each expectation with a method / closure callback) <a href="/mock_server/configuration_properties.html#button_configuration_web_socket_event_loop_thread_count">can be configured and is described in the configuration section</a>.</p>
</div>
<button id="button_file_store_api" class="accordion">file store REST API (store, retrieve, list, and delete files)</button>
<div class="panel">
    <p>MockServer provides an in-memory file store that can be used with the <a href="#button_response_file_body">FileBody</a> type. Files stored via the file store API can be referenced in expectations by name. The file store is cleared when MockServer is reset.</p>
    <button class="accordion inner">REST API</button>
    <div class="panel">
        <pre class="prettyprint code"><code class="code"># Store a file
curl -v -X PUT "http://localhost:1080/mockserver/files/store?name=sample.json" \
    -H "Content-Type: application/json" \
    -d '{"id": 1, "name": "example"}'

# Retrieve a file
curl -v -X PUT "http://localhost:1080/mockserver/files/retrieve" \
    -H "Content-Type: application/json" \
    -d '{"name": "sample.json"}'

# List all stored files
curl -v -X PUT "http://localhost:1080/mockserver/files/list"

# Delete a file
curl -v -X PUT "http://localhost:1080/mockserver/files/delete" \
    -H "Content-Type: application/json" \
    -d '{"name": "sample.json"}'</code></pre>
    </div>
    <button class="accordion inner">Java</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">MockServerClient mockServerClient = new MockServerClient("localhost", 1080);

// Store a file, then reference it in an expectation using FileBody
mockServerClient
    .when(
        request()
            .withPath("/api/data")
    )
    .respond(
        response()
            .withBodyFromFile("sample.json", MediaType.APPLICATION_JSON)
    );</code></pre>
    </div>
    <p><strong>Endpoints:</strong></p>
    <ul>
        <li><strong>PUT /mockserver/files/store?name=&lt;filename&gt;</strong> &mdash; stores a file with the given name; the request body is the file content</li>
        <li><strong>PUT /mockserver/files/retrieve</strong> &mdash; retrieves a stored file; the request body is a JSON object with a <code class="inline code">"name"</code> field</li>
        <li><strong>PUT /mockserver/files/list</strong> &mdash; lists all stored file names</li>
        <li><strong>PUT /mockserver/files/delete</strong> &mdash; deletes a stored file; the request body is a JSON object with a <code class="inline code">"name"</code> field</li>
    </ul>
</div>
<button id="button_response_create_expecation_within_closure_callback" class="accordion">create expectation within method / closure callback</button>
<div class="panel">
    <button class="accordion inner">Java 7</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        new ExpectationResponseCallback() {
            @Override
            public HttpResponse handle(HttpRequest httpRequest) throws Exception {
                if (httpRequest.getMethod().getValue().equals("POST")) {
                    mockServerClient
                        .when(
                            request()
                                .withPath("/some/otherPath")
                        )
                        .respond(
                            response()
                                .withBody(httpRequest.getBodyAsString())
                        );
                    return response()
                        .withStatusCode(ACCEPTED_202.code())
                        .withBody("request processed");
                } else {
                    return notFoundResponse();
                }
            }
        }
    );</code></pre>
    </div>
    <button class="accordion inner">Java 8+</button>
    <div class="panel">
        <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .respond(
        httpRequest -> {
            if (httpRequest.getMethod().getValue().equals("POST")) {
                mockServerClient
                    .when(
                        request()
                            .withPath("/some/otherPath")
                    )
                    .respond(
                        response()
                            .withBody(httpRequest.getBodyAsString())
                    );
                return response()
                    .withStatusCode(ACCEPTED_202.code())
                    .withBody("request processed");
            } else {
                return notFoundResponse();
            }
        }
    );</code></pre>
    </div>
    <button class="accordion inner">JavaScript</button>
    <div class="panel">
        <pre class="prettyprint lang-javascript code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
var callback = function (request) {
    if (request.method === 'POST') {
        mockServerClient("localhost", 1080)
            .mockAnyResponse({
                "httpRequest": {
                    "path": "/some/otherPath"
                },
                "httpResponse": {
                    "body": request.body.string
                }
            })
            .then(
                function () {
                    console.log("chained expectation created");
                },
                function (error) {
                    console.log(error);
                }
            );
        return {
            'statusCode': 202,
            'body': "request processed"
        };
    } else {
        return {
            'statusCode': 404
        };
    }
};
mockServerClient("localhost", 1080)
    .mockWithCallback(
        {
            'path': '/some/path'
        },
        callback
    )
    .then(
        function () {
            console.log("expectation created");
        },
        function (error) {
            console.log(error);
        }
    );</code></pre>
    </div>
    <p>When using <span class="inline_code">org.mockserver.client.MockServerClient</span> each method / closure callback has a separate web socket client.  To ensure the number of total threads does not grow too large for large numbers of method / closure callback expectations the default event loop thread pool for the web socket client is kept fairly low.  However, if an extremely large load is matched against a single method / closure callback expectation the event loop thread pool may not be large enough for its web socket client.</p>
    <p>The number of threads for the event loop thread pool for each web socket client (i.e. for each expectation with a method / closure callback) <a href="/mock_server/configuration_properties.html#button_configuration_web_socket_event_loop_thread_count">can be configured and is described in the configuration section</a>.</p>
</div>
