### Configure stubby4j using Docker Compose Source: https://context7.com/azagniotov/stubby4j/llms.txt Define and run stubby4j as a service in a Docker Compose setup. This example configures ports, volumes, and environment variables for the stubby4j container. ```yaml # docker-compose.yml version: '3.8' services: stubby4j: image: azagniotov/stubby4j:latest-jre17 volumes: - "./stubs:/home/stubby4j/data" ports: - "8882:8882" - "8889:8889" - "7443:7443" environment: YAML_CONFIG: main.yaml STUBS_PORT: 8882 ADMIN_PORT: 8889 STUBS_TLS_PORT: 7443 WITH_ARGS: "--enable_tls_with_alpn_and_http_2 --watch" ``` -------------------------------- ### startJettyYamless Source: https://context7.com/azagniotov/stubby4j/llms.txt Starts the Stubby4j server without a YAML configuration file, allowing YAML configuration to be injected at runtime. ```APIDOC ## `startJettyYamless` — Start without a YAML file (inject YAML at runtime) ### Description Starts the Stubby4j server with a YAML configuration provided as a string at runtime. ### Method Signature ```java STUBBY_CLIENT.startJettyYamless(String yamlConfig, int httpPort, int httpsPort, int adminPort, String host) ``` ### Parameters - **yamlConfig** (String) - Required - The YAML configuration for the stubs. - **httpPort** (int) - Required - The port for HTTP traffic. - **httpsPort** (int) - Required - The port for HTTPS traffic. - **adminPort** (int) - Required - The port for the admin interface. - **host** (String) - Required - The host address to bind to. ### Request Example ```java String yamlConfig = "- request:\n method: GET\n url: /api/hello\n response:\n status: 200\n body: Hello World\n"; STUBBY_CLIENT.startJettyYamless( yamlConfig, STUBS_PORT, TLS_PORT, ADMIN_PORT, "localhost" ); ``` ``` -------------------------------- ### Start Stubby4j Server Without YAML File Source: https://context7.com/azagniotov/stubby4j/llms.txt Starts the Stubby4j server with a YAML configuration injected at runtime. Ensure STUBS_PORT, TLS_PORT, and ADMIN_PORT are defined. ```java String yamlConfig = "- request:\n" + " method: GET\n" + " url: /api/hello\n" + " response:\n" + " status: 200\n" + " body: Hello World\n"; STUBBY_CLIENT.startJettyYamless( yamlConfig, STUBS_PORT, TLS_PORT, ADMIN_PORT, "localhost" ); ``` -------------------------------- ### Run Stubby4j with All Environment Variables Source: https://github.com/azagniotov/stubby4j/blob/master/docs/DOCKERHUB.md This command demonstrates starting a stubby4j instance with all available environment variables configured. Ensure the WITH_ARGS value is properly quoted. ```bash docker run --rm \ --env YAML_CONFIG=stubs.yaml \ --env STUBS_PORT=9991 \ --env ADMIN_PORT=8889 \ --env STUBS_TLS_PORT=8443 \ --env WITH_ARGS="--enable_tls_with_alpn_and_http_2 --disable_stub_caching --debug --watch" \ --volume /Users/zaggy/docker-playground/yaml:/home/stubby4j/data \ -p 9991:9991 -p 8889:8889 -p 8443:8443 \ azagniotov/stubby4j:7.5.2-jre8 ``` -------------------------------- ### Start embedded Jetty server with StubbyClient Source: https://context7.com/azagniotov/stubby4j/llms.txt Initializes and starts the embedded Jetty server for stubby4j, configuring ports and optional features like TLS and watching for config changes. ```java import io.github.azagniotov.stubby4j.client.StubbyClient; import io.github.azagniotov.stubby4j.client.StubbyResponse; import io.github.azagniotov.stubby4j.client.Authorization; import io.github.azagniotov.stubby4j.utils.NetworkPortUtils; public class MyIntegrationTest { private static final StubbyClient STUBBY_CLIENT = new StubbyClient(); private static final int STUBS_PORT = NetworkPortUtils.findAvailableTcpPort(); private static final int TLS_PORT = NetworkPortUtils.findAvailableTcpPort(); private static final int ADMIN_PORT = NetworkPortUtils.findAvailableTcpPort(); @BeforeClass public static void setUp() throws Exception { // Start with all three portals on dynamic ports STUBBY_CLIENT.startJetty( STUBS_PORT, TLS_PORT, ADMIN_PORT, "localhost", "/path/to/stubs.yaml", "--enable_tls_with_alpn_and_http_2", "--watch" ); } @AfterClass public static void tearDown() throws Exception { STUBBY_CLIENT.stopJetty(); } } ``` -------------------------------- ### Run stubby4j Docker Instance Source: https://github.com/azagniotov/stubby4j/blob/master/docs/DOCKERHUB.md Use this command to start a stubby4j instance, mapping a local directory with your YAML config to the container and exposing necessary ports. Ensure you replace placeholders with your actual values. ```bash $ docker run --rm \ --env YAML_CONFIG=stubs.yaml \ --volume :/home/stubby4j/data \ -p 8882:8882 -p 8889:8889 -p 7443:7443 \ azagniotov/stubby4j: ``` ```bash $ docker run --rm \ --env YAML_CONFIG=stubs.yaml \ --volume /Users/zaggy/docker-playground/yaml:/home/stubby4j/data \ -p 8882:8882 -p 8889:8889 -p 7443:7443 \ azagniotov/stubby4j:7.5.2-jre8 ``` -------------------------------- ### Run stubby4j JAR with Basic YAML Configuration Source: https://context7.com/azagniotov/stubby4j/llms.txt Start stubby4j as a standalone JAR using a YAML configuration file for stubs. Download the JAR from Maven Central. ```bash # Download from Maven Central # groupId: io.github.azagniotov, artifactId: stubby4j # Basic start with YAML config java -jar stubby4j-7.6.0.jar --data stubs.yaml ``` -------------------------------- ### Make GET Requests with Stubby4j Source: https://context7.com/azagniotov/stubby4j/llms.txt Demonstrates making GET requests using explicit host/port, default settings, with Basic Auth, and over TLS. The default stub port is 8882. ```java // GET using explicit host/port StubbyResponse response = STUBBY_CLIENT.doGet("localhost", "/api/users", STUBS_PORT); System.out.println(response.statusCode()); // 200 System.out.println(response.body()); // {"users": [...]} // GET using defaults (localhost:8882) StubbyResponse defaultResponse = STUBBY_CLIENT.doGetUsingDefaults("/api/status"); // GET with Basic Auth Authorization auth = new Authorization( Authorization.AuthorizationType.BASIC, "dXNlcjpwYXNzd29yZA==" ); StubbyResponse authResponse = STUBBY_CLIENT.doGet("localhost", "/secure", STUBS_PORT, auth); // GET over TLS (default TLS port 7443) StubbyResponse tlsResponse = STUBBY_CLIENT.doGetOverSsl("localhost", "/api/secure"); ``` -------------------------------- ### Run stubby4j Docker Container with Basic Configuration Source: https://context7.com/azagniotov/stubby4j/llms.txt Start a basic stubby4j Docker container, mounting a local directory for YAML configuration and exposing the default ports. The `YAML_CONFIG` environment variable specifies the configuration file. ```bash # Basic Docker run docker run --rm \ --env YAML_CONFIG=stubs.yaml \ --volume /path/to/yaml/dir:/home/stubby4j/data \ -p 8882:8882 -p 8889:8889 -p 7443:7443 \ azagniotov/stubby4j:7.6.0-jre17 ``` -------------------------------- ### Run stubby4j JAR with Disabled Admin Portal and TLS Source: https://context7.com/azagniotov/stubby4j/llms.txt Launch stubby4j with the admin portal and TLS support disabled. This is useful for simpler setups where these features are not required. ```bash # Disable admin portal and TLS java -jar stubby4j-7.6.0.jar \ --data stubs.yaml \ --disable_admin_portal \ --disable_ssl ``` -------------------------------- ### Build Stub with Description and UUID using YamlBuilder Source: https://context7.com/azagniotov/stubby4j/llms.txt Create a stub that includes a description and a UUID, which is helpful for targeted updates to stubbed data via the Admin API. This example shows a GET request. ```java String stubbedFeature = yamlBuilder .newStubbedFeature() .withDescription("User profile endpoint") .withUUID("user-profile-stub") .newStubbedRequest() .withMethodGet() .withUrl("/api/v1/profile") .withHeaderAuthorizationBearer("valid-token") .newStubbedResponse() .withStatus("200") .withLiteralBody("{\"id\": 1, \"name\": \"Jane\"}") .build(); ``` -------------------------------- ### doGet / doGetUsingDefaults Source: https://context7.com/azagniotov/stubby4j/llms.txt Makes GET requests to the stubbed server, with options for explicit host/port, default ports, and authentication. ```APIDOC ## `doGet` / `doGetUsingDefaults` — Make GET requests ### Description Executes GET requests against the stubbed API. Supports specifying host and port, using default ports, and including authorization headers. ### Method Signatures ```java StubbyResponse doGet(String host, String path, int port) StubbyResponse doGetUsingDefaults(String path) StubbyResponse doGet(String host, String path, int port, Authorization auth) StubbyResponse doGetOverSsl(String host, String path) ``` ### Parameters - **host** (String) - Required - The host of the stubbed server. - **path** (String) - Required - The endpoint path to request. - **port** (int) - Required - The port of the stubbed server. - **auth** (Authorization) - Optional - Authorization object for the request. ### Request Examples ```java // GET using explicit host/port StubbyResponse response = STUBBY_CLIENT.doGet("localhost", "/api/users", STUBS_PORT); System.out.println(response.statusCode()); // 200 System.out.println(response.body()); // {"users": [...]} // GET using defaults (localhost:8882) StubbyResponse defaultResponse = STUBBY_CLIENT.doGetUsingDefaults("/api/status"); // GET with Basic Auth Authorization auth = new Authorization( Authorization.AuthorizationType.BASIC, "dXNlcjpwYXNzd29yZA==" ); StubbyResponse authResponse = STUBBY_CLIENT.doGet("localhost", "/secure", STUBS_PORT, auth); // GET over TLS (default TLS port 7443) StubbyResponse tlsResponse = STUBBY_CLIENT.doGetOverSsl("localhost", "/api/secure"); ``` ### Response - **StubbyResponse** - An object containing the status code and body of the response. ``` -------------------------------- ### Print stubby4j JAR Version Source: https://context7.com/azagniotov/stubby4j/llms.txt Display the version of the stubby4j JAR file. This command is useful for verifying the installed version. ```bash # Print version java -jar stubby4j-7.6.0.jar --version ``` -------------------------------- ### Included Stub Configuration Source: https://context7.com/azagniotov/stubby4j/llms.txt An example of a stub configuration file that can be included in a main YAML file. It uses regex for URL matching and captures groups from the POST body for dynamic response generation. ```yaml # stubs/auth-stubs.yaml - request: method: POST url: /api/auth/login post: '{"username":"(.*)","password":"(.*)"}' response: status: 200 body: '{"token":"stubbed-token-<%post.1%>"}' headers: content-type: application/json ``` -------------------------------- ### Build GET Stub with Query Params and JSON Response using YamlBuilder Source: https://context7.com/azagniotov/stubby4j/llms.txt Use YamlBuilder to programmatically construct a GET request stub with query parameters and a JSON response body. Ensure necessary imports are included. ```java import io.github.azagniotov.stubby4j.yaml.YamlBuilder; YamlBuilder yamlBuilder = new YamlBuilder(); // Build a GET stub with query params and JSON response String getStub = yamlBuilder .newStubbedRequest() .withMethodGet() .withUrl("/api/v1/users") .withQuery("role", "admin") .withQuery("active", "true") .withHeaders("content-type", "application/json") .newStubbedResponse() .withStatus("200") .withHeaderContentType("application/json") .withLiteralBody("{\"users\": [{\"id\": 1, \"name\": \"Alice\"}]}") .build(); ``` -------------------------------- ### Get stub by index via Admin API Source: https://context7.com/azagniotov/stubby4j/llms.txt Retrieve the YAML configuration for a specific stub using its index in the loaded stubs list. ```bash curl http://localhost:8889/0 # Returns YAML of stub at index 0 ``` -------------------------------- ### Get Admin status page Source: https://context7.com/azagniotov/stubby4j/llms.txt Access the Admin portal's status page to view all loaded stubs and their hit statistics. ```bash curl http://localhost:8889/status # Returns HTML status page with all loaded stubs and hit statistics ``` -------------------------------- ### Main YAML Config with Includes Source: https://context7.com/azagniotov/stubby4j/llms.txt Demonstrates how to split a large stub configuration into multiple files using the 'includes' directive in the main YAML entry point. ```yaml # main.yaml - entry point that includes sub-configs includes: - stubs/auth-stubs.yaml - stubs/user-stubs.yaml - stubs/payment-stubs.yaml - proxy-config.yaml ``` -------------------------------- ### Run Stubby4j with Volume Mount for Configuration Source: https://github.com/azagniotov/stubby4j/blob/master/docs/DOCKERHUB.md This command shows how to run stubby4j, mounting a host directory to the container's data volume for configuration files. The logs will be persisted in the specified host directory. ```bash $ docker run --rm \ --env YAML_CONFIG=stubs.yaml \ --volume :/home/stubby4j/data \ -p 8882:8882 -p 8889:8889 -p 7443:7443 \ ... ... ... ``` -------------------------------- ### Run stubby4j Docker Container with Full Configuration Source: https://context7.com/azagniotov/stubby4j/llms.txt Deploy stubby4j in Docker with advanced settings including HTTP/2 over TLS, debug mode, file watching, and custom port configurations. The `WITH_ARGS` environment variable passes additional command-line arguments. ```bash # Full configuration with HTTP/2, debug mode, and file watching docker run --rm \ --env YAML_CONFIG=stubs.yaml \ --env STUBS_PORT=9991 \ --env ADMIN_PORT=8889 \ --env STUBS_TLS_PORT=8443 \ --env WITH_ARGS="--enable_tls_with_alpn_and_http_2 --disable_stub_caching --debug --watch" \ --volume /path/to/yaml/dir:/home/stubby4j/data \ -p 9991:9991 -p 8889:8889 -p 8443:8443 \ azagniotov/stubby4j:7.6.0-jre17 ``` -------------------------------- ### Display PKCS12 Keystore Contents (keytool) Source: https://github.com/azagniotov/stubby4j/blob/master/src/main/resources/ssl/stubby4j.self.signed.v3.commands.txt Lists the contents of a PKCS12 keystore in verbose mode. This command is used to inspect the contents of the PKCS12 file. ```bash keytool -list -v -keystore openssl.downloaded.stubby4j.self.signed.v3.pkcs12 -storetype PKCS12 ``` -------------------------------- ### Run stubby4j JAR with Custom TLS Keystore Source: https://context7.com/azagniotov/stubby4j/llms.txt Configure stubby4j to use a custom TLS keystore for secure connections. Provide the path to the keystore file and its password. ```bash # Custom TLS keystore java -jar stubby4j-7.6.0.jar \ --data stubs.yaml \ --keystore /path/to/keystore.jks \ --password keystorePassword ``` -------------------------------- ### Verify TLS Connection with cURL Source: https://github.com/azagniotov/stubby4j/blob/master/src/main/resources/ssl/stubby4j.self.signed.v3.commands.txt Performs a GET request to a TLS-enabled endpoint using cURL, specifying the CA certificate for verification. The '-k' option is intentionally omitted to enforce certificate validation. ```bash curl -X GET --cacert openssl.downloaded.stubby4j.self.signed.v3.pem --tls-max 1.1 https://localhost:7443/hello -v ``` ```bash curl -X GET --cacert openssl.downloaded.stubby4j.self.signed.v3.pem --tls-max 1.1 https://127.0.0.1:7443/hello -v ``` ```bash curl -X GET --cacert openssl.downloaded.stubby4j.self.signed.v3.pem --tls-max 1.1 https://0.0.0.0:7443/hello -v ``` -------------------------------- ### Import Certificate to JKS Keystore (keytool) Source: https://github.com/azagniotov/stubby4j/blob/master/src/main/resources/ssl/stubby4j.self.signed.v3.commands.txt Imports a PEM-formatted certificate into a Java KeyStore (JKS) file. This JKS file can then be added to a Java client's trust-store. ```bash keytool -import -trustcacerts -alias stubby4j -file openssl.downloaded.stubby4j.self.signed.v3.pem -keystore openssl.downloaded.stubby4j.self.signed.v3.jks ``` -------------------------------- ### Regex URL Matching and Dynamic Token Replacement Source: https://context7.com/azagniotov/stubby4j/llms.txt Illustrates how to use regex for URL matching and capture groups to dynamically populate response bodies, headers, or redirect locations. Supports tokens from URL, query, headers, and POST bodies. ```yaml # Dynamic token replacement from URL capture groups - request: method: GET url: ^/resources/invoices/(\d{5})/category/([a-zA-Z]+) response: status: 200 body: "Invoice #<%url.1%> in category '<%url.2%>'" headers: content-type: text/plain ``` ```yaml # Dynamic token from POST JSON body capture groups - request: method: POST url: /api/transactions headers: content-type: application/json post: > {"userId":"19","requestId":"(.*)","transactionDate":"(.*)","transactionTime":"(.*)"} response: status: 200 headers: content-type: application/json body: > {"requestId": "<%post.1%>", "transactionDate": "<%post.2%>", "transactionTime": "<%post.3%>"} ``` ```yaml # Dynamic redirect using query param capture group - request: method: GET url: ^/v\d/identity/authorize query: redirect_uri: "https://(.*)/app.*" response: status: 302 headers: location: https://<% query.redirect_uri.1 %>/auth ``` -------------------------------- ### Display JKS Keystore Contents (keytool) Source: https://github.com/azagniotov/stubby4j/blob/master/src/main/resources/ssl/stubby4j.self.signed.v3.commands.txt Lists the contents of a JKS keystore in verbose mode, showing details about the stored certificates and keys. ```bash keytool -list -v -keystore openssl.downloaded.stubby4j.self.signed.v3.jks -storetype JKS ``` -------------------------------- ### Run stubby4j JAR with Full Configuration Options Source: https://context7.com/azagniotov/stubby4j/llms.txt Execute the stubby4j JAR with a comprehensive set of command-line arguments to configure network interfaces, ports, TLS, and debugging. The `--watch` flag enables hot-reloading. ```bash # Full configuration java -jar stubby4j-7.6.0.jar \ --data stubs.yaml \ --location 0.0.0.0 \ --stubs 8882 \ --admin 8889 \ --tls 7443 \ --enable_tls_with_alpn_and_http_2 \ --watch \ --debug ``` -------------------------------- ### Catch-all Proxy Configuration Source: https://context7.com/azagniotov/stubby4j/llms.txt Configure a catch-all proxy to forward any unmatched requests to a specified endpoint using the 'as-is' strategy, forwarding the request without modification. ```yaml # Catch-all proxy: forwards any unmatched request to jsonplaceholder - proxy-config: description: catch-all proxy strategy: as-is properties: endpoint: https://jsonplaceholder.typicode.com ``` -------------------------------- ### Proxy Configuration Source: https://context7.com/azagniotov/stubby4j/llms.txt Configure stubby4j to forward unmatched requests to a real backend using 'as-is' or 'additive' proxy strategies. Includes runtime management via Admin portal. ```APIDOC ## Proxy Configuration (Catch-all) ### Description This configuration acts as a catch-all proxy, forwarding any unmatched request to the specified endpoint without modifying the request. ### Properties - **description** (string) - Optional - A description for the proxy configuration. - **strategy** (string) - Required - Must be 'as-is' to forward the request unchanged. - **properties.endpoint** (string) - Required - The backend endpoint to forward requests to. ### Request Example ```yaml # Catch-all proxy: forwards any unmatched request to jsonplaceholder - proxy-config: description: catch-all proxy strategy: as-is properties: endpoint: https://jsonplaceholder.typicode.com ``` ``` ```APIDOC ## Proxy Configuration (Additive Headers) ### Description This configuration forwards requests to a backend endpoint and adds custom headers to the forwarded request. ### Properties - **uuid** (string) - Optional - A unique identifier for the proxy configuration. - **description** (string) - Optional - A description for the proxy configuration. - **strategy** (string) - Required - Must be 'additive' to add custom headers. - **headers** (object) - Optional - Key-value pairs of headers to add to the forwarded request. - **properties.endpoint** (string) - Required - The backend endpoint to forward requests to. ### Request Example ```yaml # Named proxy with additive headers and a UUID for targeted management - proxy-config: uuid: my-backend-proxy description: additive proxy to backend strategy: additive headers: x-forwarded-by: stubby4j x-custom-header: my-value properties: endpoint: https://api.mybackend.com ``` ``` ```APIDOC ## Admin Portal Proxy Management ### Description Stubby4j's Admin portal allows for viewing and updating proxy configurations at runtime. ### Operations #### View Proxy Configuration ```bash curl http://localhost:8889/proxy-config/my-backend-proxy ``` #### Update Proxy Configuration ```bash curl -X PUT http://localhost:8889/proxy-config/my-backend-proxy \ -H "Content-Type: application/yaml" \ --data-binary @updated-proxy.yaml ``` ``` -------------------------------- ### Additive Proxy Configuration with Custom Headers Source: https://context7.com/azagniotov/stubby4j/llms.txt Set up a named proxy with an 'additive' strategy, allowing custom headers to be added to requests forwarded to the specified endpoint. ```yaml # Named proxy with additive headers and a UUID for targeted management - proxy-config: uuid: my-backend-proxy description: additive proxy to backend strategy: additive headers: x-forwarded-by: stubby4j x-custom-header: my-value properties: endpoint: https://api.mybackend.com ``` -------------------------------- ### Convert JKS to PKCS12 (keytool) Source: https://github.com/azagniotov/stubby4j/blob/master/src/main/resources/ssl/stubby4j.self.signed.v3.commands.txt Converts a JKS keystore to a PKCS12 keystore. This is useful for compatibility with systems that prefer the PKCS12 format. ```bash keytool -importkeystore -srckeystore openssl.downloaded.stubby4j.self.signed.v3.jks -destkeystore openssl.downloaded.stubby4j.self.signed.v3.pkcs12 -srcstoretype JKS -deststoretype PKCS12 -deststorepass stubby4j ``` -------------------------------- ### Make POST Requests with Stubby4j Source: https://context7.com/azagniotov/stubby4j/llms.txt Shows how to make POST requests with a JSON payload, with Bearer authentication, and using default settings. Ensure the correct port is specified. ```java // POST with JSON payload StubbyResponse response = STUBBY_CLIENT.doPost( "localhost", "/api/users", STUBS_PORT, "{\"name\": \"Alice\", \"email\": \"alice@example.com\"}" ); assert response.statusCode() == 201; // POST with Bearer auth Authorization bearer = new Authorization( Authorization.AuthorizationType.BEARER, "my-api-token" ); StubbyResponse authPost = STUBBY_CLIENT.doPost( "localhost", "/api/protected", STUBS_PORT, bearer, "{\"action\": \"create\"}" ); // POST using defaults StubbyResponse defaults = STUBBY_CLIENT.doPostUsingDefaults("/api/events", "{\"type\":\"click\"}"); ``` -------------------------------- ### List all loaded stubs via Admin API Source: https://context7.com/azagniotov/stubby4j/llms.txt Use this command to retrieve the full YAML configuration of all currently loaded stubs from the stubby4j Admin portal. ```bash curl http://localhost:8889/ # Returns full YAML of all loaded stubs ``` -------------------------------- ### Make PUT and DELETE Requests with Stubby4j Source: https://context7.com/azagniotov/stubby4j/llms.txt Illustrates making PUT and DELETE requests, including PUT requests over TLS. The `null` argument can be used for headers if not needed. ```java // PUT request StubbyResponse putResponse = STUBBY_CLIENT.doPut( "localhost", "/api/users/42", STUBS_PORT, null, "{\"name\": \"Alice Updated\"}" ); assert putResponse.statusCode() == 200; // PUT over TLS StubbyResponse tlsPut = STUBBY_CLIENT.doPutOverSsl( "localhost", "/api/secure/resource", TLS_PORT, null, "{\"data\": \"value\"}" ); // DELETE request StubbyResponse deleteResponse = STUBBY_CLIENT.doDelete( "localhost", "/api/users/42", STUBS_PORT, null ); assert deleteResponse.statusCode() == 200; ``` -------------------------------- ### Record & Replay Source: https://context7.com/azagniotov/stubby4j/llms.txt Configure stubs to record the response from a given URL on the first request and replay it for subsequent requests, avoiding repeated external calls. ```APIDOC ## GET /feed/1 (Record & Replay) ### Description This endpoint triggers a record and replay behavior. The first request will fetch data from `http://api.example.com`, record it, and replay it for all subsequent matching requests. ### Method GET ### Endpoint /feed/1 ### Parameters #### Query Parameters - **greeting** (string) - Optional - Greeting parameter. - **language** (string) - Optional - Language parameter. #### Request Headers - **content-type** (string) - Optional - application/json ### Response #### Success Response (200) - **content-type** (string) - application/json ### Request Example ```yaml - request: method: GET url: /feed/1 query: greeting: nihao language: chinese headers: content-type: application/json response: status: 200 headers: content-type: application/json body: http://api.example.com # URL triggers record & replay behavior ``` ``` ```APIDOC ## GET /recordable/feed/1 (Recordable Target) ### Description This is a pre-defined stub that can be used as the target for the record & replay behavior. ### Method GET ### Endpoint /recordable/feed/1 ### Parameters #### Query Parameters - **greeting** (string) - Optional - Greeting parameter. - **language** (string) - Optional - Language parameter. ### Response #### Success Response (200) - **content-type** (string) - application/xml ### Response Example ```yaml - request: method: GET url: /recordable/feed/1 query: greeting: nihao language: chinese response: status: 200 headers: content-type: application/xml body: > recorded ``` ``` -------------------------------- ### Build Proxy Configuration Stub using YamlBuilder Source: https://context7.com/azagniotov/stubby4j/llms.txt Define a proxy configuration stub using YamlBuilder, specifying the UUID, description, proxy strategy, and the endpoint of the backend to proxy to. ```java String proxyConfig = yamlBuilder .newStubbedProxyConfig() .withUuid("backend-proxy") .withDescription("Proxy to real backend") .withProxyStrategyAsIs() .withPropertyEndpoint("https://api.realbackend.com") .build(); ``` -------------------------------- ### Docker Compose Configuration for Stubby4j Source: https://github.com/azagniotov/stubby4j/blob/master/docs/DOCKERHUB.md Integrate stubby4j into your application stack using this Docker Compose configuration. Replace `` with your actual host directory. ```yaml # This compose file adds stubby4j https://hub.docker.com/r/azagniotov/stubby4j to your stack # See "Environment variables" section at https://hub.docker.com/r/azagniotov/stubby4j version: '3.8' services: stubby4j: image: azagniotov/stubby4j:latest-jre8 # you can also use other tags: latest-jre11, latest-jre15 volumes: - ":/home/stubby4j/data" container_name: stubby4j ports: - 8882:8882 - 8889:8889 - 7443:7443 environment: YAML_CONFIG: main.yaml STUBS_PORT: 8882 ADMIN_PORT: 8889 STUBS_TLS_PORT: 7443 WITH_ARGS: "--enable_tls_with_alpn_and_http_2 --debug --watch" ``` -------------------------------- ### Convert Certificate to PKCS12 Keystore (OpenSSL) Source: https://github.com/azagniotov/stubby4j/blob/master/src/main/resources/ssl/stubby4j.self.signed.v3.commands.txt Converts a private key and certificate into a PKCS12 keystore, which is used for configuring TLS on the server. ```bash openssl pkcs12 -inkey stubby4j.v3.key.pem -in stubby4j.v3.crt.pem -export -out stubby4j.self.signed.v3.pkcs12 ``` -------------------------------- ### Basic HTTP Stub Configuration Source: https://context7.com/azagniotov/stubby4j/llms.txt Defines a basic HTTP stub with request matching by method, regex URL, headers, and query parameters. The response includes status, headers, and a JSON body. ```yaml # stubs.yaml - basic HTTP stub - request: method: [GET, POST] url: ^/api/v1/users/.*$ # regex URL matching headers: content-type: application/json query: active: true response: status: 200 headers: content-type: application/json body: > {"id": 42, "name": "Jane Doe", "active": true} ``` -------------------------------- ### View Proxy Configuration via Admin Portal Source: https://context7.com/azagniotov/stubby4j/llms.txt Use curl to retrieve the current proxy configuration for a specific proxy by its UUID from the stubby4j Admin portal. ```bash # View proxy config via Admin portal curl http://localhost:8889/proxy-config/my-backend-proxy ``` -------------------------------- ### Configure WebSocket Stub with Policies Source: https://context7.com/azagniotov/stubby4j/llms.txt Defines behavior for WebSocket endpoints including on-open and on-message events. Supports policies like 'once', 'push', 'disconnect', 'fragmentation', and 'ping'. ```yaml - web-socket: description: demo WebSocket endpoint url: /ws/chat sub-protocols: chat, echo # Message sent to client immediately on connection on-open: policy: once message-type: text body: "Welcome! You are connected." delay: 100 # ms delay before sending # Map client messages to server responses on-message: - client-request: message-type: text body: hello server-response: policy: once message-type: text body: "Hello back!" delay: 50 - client-request: message-type: text body: do push server-response: policy: push # keep pushing this response message-type: text body: "Pushing data..." delay: 200 - client-request: message-type: text body: bye server-response: policy: disconnect message-type: text body: "Goodbye!" delay: 100 # Binary response from file - client-request: message-type: text body: get report server-response: policy: once message-type: binary file: responses/report.pdf delay: 300 # Ping policy on open (WebSocket keepalive) - web-socket: url: /ws/ping-endpoint sub-protocols: echo on-open: policy: ping delay: 5000 ``` -------------------------------- ### Download Server SSL Certificate (OpenSSL) Source: https://github.com/azagniotov/stubby4j/blob/master/src/main/resources/ssl/stubby4j.self.signed.v3.commands.txt Downloads the SSL certificate from the server and saves it in PEM format. This is used for client-side TLS configuration. ```bash echo quit | openssl s_client -showcerts -servername localhost -connect "localhost":7443 > openssl.downloaded.stubby4j.self.signed.v3.pem ``` -------------------------------- ### Display Certificate Contents (OpenSSL) Source: https://github.com/azagniotov/stubby4j/blob/master/src/main/resources/ssl/stubby4j.self.signed.v3.commands.txt Displays the detailed contents of a PEM-formatted certificate. Useful for inspecting certificate information. ```bash openssl x509 -in openssl.downloaded.stubby4j.self.signed.v3.pem -noout -text ``` -------------------------------- ### Create or replace all stubs via Admin API Source: https://context7.com/azagniotov/stubby4j/llms.txt Replace the entire in-memory stub configuration. Can be done by providing a YAML file or an inline YAML payload. ```bash # Replace entire in-memory stub configuration from a YAML file curl -X POST http://localhost:8889/ \ -H "Content-Type: application/yaml" \ --data-binary @stubs.yaml # 201 Created on success # Inline YAML payload curl -X POST http://localhost:8889/ \ -H "Content-Type: application/yaml" \ -d ' - request: method: GET url: /hello response: status: 200 body: Hello World ' ``` -------------------------------- ### Update Proxy Configuration Endpoint at Runtime Source: https://context7.com/azagniotov/stubby4j/llms.txt Update the endpoint of a proxy configuration at runtime by sending a PUT request to the Admin portal with the updated YAML configuration. ```bash # Update proxy config endpoint at runtime via Admin portal curl -X PUT http://localhost:8889/proxy-config/my-backend-proxy \ -H "Content-Type: application/yaml" \ --data-binary @updated-proxy.yaml ``` -------------------------------- ### Stub with Latency and File-Based Body Source: https://context7.com/azagniotov/stubby4j/llms.txt Configures a stub to simulate network latency and serve a binary file as the response body. This is useful for testing performance and file downloads. ```yaml # Stub with latency simulation and file-based body - request: method: GET url: /api/v1/report response: status: 200 latency: 2000 # delay response by 2000ms headers: content-type: application/pdf content-disposition: attachment; filename=report.pdf file: responses/report.pdf # serve binary file ``` -------------------------------- ### Admin Portal REST API Source: https://context7.com/azagniotov/stubby4j/llms.txt Manage in-memory stubs without restarting stubby4j using the Admin Portal REST API. ```APIDOC ## Admin Portal REST API The Admin portal (default: `http://localhost:8889`) provides a REST API to manage in-memory stubs without restarting stubby4j. ### `GET /` — List all loaded stubs as YAML ```bash curl http://localhost:8889/ # Returns full YAML of all loaded stubs ``` ### `GET /` — Get stub by index ```bash curl http://localhost:8889/0 # Returns YAML of stub at index 0 ``` ### `POST /` — Create / replace all stubs ```bash # Replace entire in-memory stub configuration from a YAML file curl -X POST http://localhost:8889/ \ -H "Content-Type: application/yaml" \ --data-binary @stubs.yaml # 201 Created on success # Inline YAML payload curl -X POST http://localhost:8889/ \ -H "Content-Type: application/yaml" \ -d ' - request: method: GET url: /hello response: status: 200 body: Hello World ' ``` ### `PUT /` — Update stub by index ```bash curl -X PUT http://localhost:8889/0 \ -H "Content-Type: application/yaml" \ --data-binary @updated-stub.yaml # 200 OK on success ``` ### `DELETE /` — Delete stub by index ```bash curl -X DELETE http://localhost:8889/0 # 200 OK on success ``` ### `DELETE /` — Delete all stubs ```bash curl -X DELETE http://localhost:8889/ # 200 OK on success ``` ### `GET /status` — Admin status page ```bash curl http://localhost:8889/status # Returns HTML status page with all loaded stubs and hit statistics ``` ### `GET /refresh` — Reload YAML config from disk ```bash curl http://localhost:8889/refresh # 200 OK — reloads the YAML file from the filesystem ``` ``` -------------------------------- ### Record and Replay Stub with URL Body Source: https://context7.com/azagniotov/stubby4j/llms.txt Configure stubby4j to record the response from a given URL on the first request and replay it for subsequent requests. This avoids repeated calls to the remote server. ```yaml # First request to /feed/1 fetches & records from http://api.example.com # Subsequent requests replay the recorded response - request: method: GET url: /feed/1 query: greeting: nihao language: chinese headers: content-type: application/json response: status: 200 headers: content-type: application/json body: http://api.example.com # URL triggers record & replay behavior ``` -------------------------------- ### WebSocket Stub Configuration Source: https://context7.com/azagniotov/stubby4j/llms.txt Configure WebSocket endpoints with various policies for message handling and connection management. ```APIDOC ## WebSocket Stub Configuration WebSocket endpoints are configured using `web-socket` stubs. The stub defines behavior for the `on-open` event (message sent on connection) and `on-message` event (responses to specific client messages). Policies include `once`, `push` (repeated), `disconnect`, `fragmentation`, and `ping`. ```yaml - web-socket: description: demo WebSocket endpoint url: /ws/chat sub-protocols: chat, echo # Message sent to client immediately on connection on-open: policy: once message-type: text body: "Welcome! You are connected." delay: 100 # ms delay before sending # Map client messages to server responses on-message: - client-request: message-type: text body: hello server-response: policy: once message-type: text body: "Hello back!" delay: 50 - client-request: message-type: text body: do push server-response: policy: push # keep pushing this response message-type: text body: "Pushing data..." delay: 200 - client-request: message-type: text body: bye server-response: policy: disconnect message-type: text body: "Goodbye!" delay: 100 # Binary response from file - client-request: message-type: text body: get report server-response: policy: once message-type: binary file: responses/report.pdf delay: 300 # Ping policy on open (WebSocket keepalive) - web-socket: url: /ws/ping-endpoint sub-protocols: echo on-open: policy: ping delay: 5000 ``` ``` -------------------------------- ### Add stubby4j Gradle Dependency Source: https://context7.com/azagniotov/stubby4j/llms.txt Add this line to your build.gradle file for Gradle projects. The 'testImplementation' configuration is standard for testing libraries. ```groovy testImplementation 'io.github.azagniotov:stubby4j:7.6.0' ``` -------------------------------- ### doPost / doPostUsingDefaults Source: https://context7.com/azagniotov/stubby4j/llms.txt Makes POST requests to the stubbed server, supporting JSON payloads and various authorization types. ```APIDOC ## `doPost` / `doPostUsingDefaults` — Make POST requests ### Description Executes POST requests against the stubbed API. Allows for sending JSON payloads and various types of authorization, including Bearer tokens. ### Method Signatures ```java StubbyResponse doPost(String host, String path, int port, String payload) StubbyResponse doPostUsingDefaults(String path, String payload) StubbyResponse doPost(String host, String path, int port, Authorization auth, String payload) ``` ### Parameters - **host** (String) - Required - The host of the stubbed server. - **path** (String) - Required - The endpoint path to request. - **port** (int) - Required - The port of the stubbed server. - **payload** (String) - Required - The request body payload. - **auth** (Authorization) - Optional - Authorization object for the request. ### Request Examples ```java // POST with JSON payload StubbyResponse response = STUBBY_CLIENT.doPost( "localhost", "/api/users", STUBS_PORT, "{\"name\": \"Alice\", \"email\": \"alice@example.com\"}" ); assert response.statusCode() == 201; // POST with Bearer auth Authorization bearer = new Authorization( Authorization.AuthorizationType.BEARER, "my-api-token" ); StubbyResponse authPost = STUBBY_CLIENT.doPost( "localhost", "/api/protected", STUBS_PORT, bearer, "{\"action\": \"create\"}" ); // POST using defaults StubbyResponse defaults = STUBBY_CLIENT.doPostUsingDefaults("/api/events", "{\"type\": \"click\"}"); ``` ### Response - **StubbyResponse** - An object containing the status code and body of the response. ``` -------------------------------- ### Sequenced Responses with File Bodies Source: https://context7.com/azagniotov/stubby4j/llms.txt Configure multiple responses for a single endpoint, allowing for sequenced behavior. Responses can be defined by status, headers, and file content or an empty body. ```APIDOC ## GET /api/v1/paginated ### Description This endpoint returns a sequence of responses, simulating pagination or state changes. ### Method GET ### Endpoint /api/v1/paginated ### Response #### Success Response (200) - **content-type** (string) - application/json - **file** (string) - Path to the JSON file for the response body. #### Success Response (204) - **content-type** (string) - application/json - **body** (string) - An empty string for a no-content response. ### Response Example ```yaml - request: method: GET url: /api/v1/paginated response: - status: 200 headers: content-type: application/json file: responses/page1.json - status: 200 headers: content-type: application/json file: responses/page2.json - status: 204 headers: content-type: application/json body: '' ``` ``` -------------------------------- ### Reload YAML config from disk Source: https://context7.com/azagniotov/stubby4j/llms.txt Triggers stubby4j to re-read its YAML configuration file from the filesystem. ```bash curl http://localhost:8889/refresh # 200 OK — reloads the YAML file from the filesystem ``` -------------------------------- ### Authorization Stubs (Basic, Bearer, Custom) Source: https://context7.com/azagniotov/stubby4j/llms.txt Stubby4j can verify incoming requests for specific authorization headers before serving a response. Supports Basic, Bearer, and custom authorization schemes. ```APIDOC ## GET /api/secure/data (Basic Auth) ### Description This endpoint requires a Basic Authorization header for access. ### Method GET ### Endpoint /api/secure/data ### Parameters #### Request Headers - **authorization-basic** (string) - Required - Base64 encoded "user:password". ### Response #### Success Response (200) - **content-type** (string) - application/json ### Request Example ```yaml - request: method: GET url: /api/secure/data headers: authorization-basic: "dXNlcjpwYXNzd29yZA==" # base64(user:password) response: status: 200 body: '{"data": "secret"}' headers: content-type: application/json ``` ``` ```APIDOC ## GET /api/v2/profile (Bearer Token Auth) ### Description This endpoint requires a Bearer token for authentication. ### Method GET ### Endpoint /api/v2/profile ### Parameters #### Request Headers - **authorization-bearer** (string) - Required - The bearer token. ### Response #### Success Response (200) - **content-type** (string) - application/json ### Request Example ```yaml - request: method: GET url: /api/v2/profile headers: authorization-bearer: "valid-bearer-token-abc" response: status: 200 body: '{"profile": {"id": 1, "role": "admin"}}' headers: content-type: application/json ``` ``` ```APIDOC ## GET /api/v2/custom-auth (Custom Auth) ### Description This endpoint uses a custom authorization header for verification. ### Method GET ### Endpoint /api/v2/custom-auth ### Parameters #### Request Headers - **authorization-custom** (string) - Required - The custom authorization key and value. ### Response #### Success Response (200) - **content-type** (string) - application/json ### Request Example ```yaml - request: method: GET url: /api/v2/custom-auth headers: authorization-custom: "ApiKey myApiKeyValue" response: status: 200 body: '{"result": "ok"}' ``` ```