### Lifecycle example Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Shows how to configure, start, retrieve the API URL, set an auth token, and stop the ngrok process. ```java // Lifecycle example final JavaNgrokConfig config = new JavaNgrokConfig.Builder() .withStartupTimeout(30) .build(); final NgrokProcess ngrokProcess = new NgrokProcess(config, new NgrokInstaller()); ngrokProcess.start(); System.out.println("API: " + ngrokProcess.getApiUrl()); // http://127.0.0.1:4040 ngrokProcess.setAuthToken(""); ngrokProcess.stop(); ``` -------------------------------- ### Error handling example Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Demonstrates catching NgrokException when starting with an invalid ngrok path and accessing error details. ```java // Error handling final NgrokProcess ngrokProcess = new NgrokProcess( new JavaNgrokConfig.Builder().withNgrokPath(Path.of("/does/not/exist")).build(), new NgrokInstaller()); try { ngrokProcess.start(); } catch (final NgrokException e) { System.out.println(e.getNgrokLogs()); // captured ngrok logs, may be null System.out.println(e.getNgrokError()); // startup error string, may be null System.out.println(e.getNgrokErrorCode()); // e.g. "ERR_NGROK_xxx", parsed from error } ``` -------------------------------- ### start() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Starts the ngrok agent process. It is a no-op if already running, resets internal state, validates configuration, and spawns a process monitor thread. Throws NgrokException on startup failures. ```APIDOC ## [JAVA] start() ### Description Starts the ngrok agent process. No-op if already running. Resets state (`apiUrl`, `tunnelStarted`, `clientConnected`, `processMonitor`). Throws `NgrokException` if the binary is missing. Validates the config (`ngrokInstaller.validateConfig`), then runs: ` start --none --log stdout [--config ] [--authtoken ] [--region ]` with `redirectErrorStream(true)` and piped stdout. Reads lines until `startupTimeout` seconds elapse, mapping log messages: `"starting web service"` → `apiUrl = http://`; `"tunnel session started"` → `tunnelStarted = true`; `"client session established"` → `clientConnected = true`. Healthy (see `healthy()`) then spawns a `ProcessMonitor` thread; otherwise stops and throws `NgrokException` (with startup error and logs when available). Registers a JVM shutdown hook calling `stop()`. ### Method JAVA ### Endpoint start() ### Parameters None ### Request Example ```java final JavaNgrokConfig config = new JavaNgrokConfig.Builder() .withStartupTimeout(30) .build(); final NgrokProcess ngrokProcess = new NgrokProcess(config, new NgrokInstaller()); ngrokProcess.start(); ``` ### Response #### Success Response No return value. #### Error Handling Throws `NgrokException` ("The ngrok process errored on start: .", "The ngrok process was unable to start.", "An error occurred while starting ngrok."), `JavaNgrokSecurityException` if a healthy `apiUrl` does not start with `http`. ``` -------------------------------- ### Example: installDefaultConfig with custom config path Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Example usage of installDefaultConfig that writes a configuration file to /opt/ngrok/au.yml with a custom agent connect URL. ```java final Path configPath = Path.of("/opt/ngrok/au.yml"); new NgrokInstaller().installDefaultConfig(configPath, Map.of("agent", Map.of("connect_url", "connect.au.ngrok-agent.com:443"))); ``` -------------------------------- ### start() method signature Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Starts the ngrok agent process. No-op if already running. Resets state and validates config. Throws NgrokException if binary missing or startup fails, JavaNgrokSecurityException if apiUrl is not http. ```java public synchronized void start() ``` -------------------------------- ### Custom HttpClient usage + config read Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Example showing how to create an NgrokInstaller with a custom HttpClient, install ngrok, read a config file, and validate a config map. The validateConfig call throws JavaNgrokException with the message "\"web_addr\" cannot be false, as the ngrok API is a dependency for java-ngrok" when web_addr is "false". ```java // Custom HttpClient usage + config read final NgrokInstaller installer = new NgrokInstaller(new DefaultHttpClient.Builder().withTimeout(12000).build()); installer.installNgrok(Path.of("/opt/tools/ngrok")); final Map config = installer.getNgrokConfig(Path.of("/opt/ngrok/config.yml"), false); try { installer.validateConfig(Map.of("version", "2", "agent", Map.of("web_addr", "false"))); } catch (final JavaNgrokException e) { // "\"web_addr\" cannot be false, as the ngrok API is a dependency for java-ngrok" } ``` -------------------------------- ### JavaNgrokVersion usage example Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/Util.md Example of getting the library version via the JavaNgrokVersion singleton. ```java final String version = JavaNgrokVersion.getInstance().getVersion(); ``` -------------------------------- ### Start a Tunnel from Config File Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/index.md Start a tunnel defined in the ngrok configuration file by its name. ```java final CreateTunnel createTunnel = new CreateTunnel.Builder() .withName("my-config-file-tunnel") .build(); final Tunnel tunnel = ngrokClient.connect(createTunnel); ``` -------------------------------- ### connectAll() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokClient.md Starts every tunnel defined in the configuration file. Returns a list of Tunnel objects, one per started definition. ```APIDOC ## connectAll() ### Description Starts every tunnel defined in the configuration file. Returns a list of Tunnel objects, one per started definition. ### Method connectAll() ### Signature public List connectAll() ### Parameters None ### Returns - **List** - A list of tunnels that were started ### Exceptions - JavaNgrokException - JavaNgrokHTTPException - JavaNgrokSecurityException ### Example ```java final NgrokClient ngrokClient = new NgrokClient.Builder() .withJavaNgrokConfig(new JavaNgrokConfig.Builder() .withConfigPath(Path.of("/opt/ngrok/config.yml")) .build()) .build(); final List tunnels = ngrokClient.connectAll(); ``` ``` -------------------------------- ### connectAll() — start every defined tunnel Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokClient.md Reads the config file at JavaNgrokConfig.getConfigPath(); returns an empty list if the file does not exist. Starts one tunnel per definition name, skipping the java-ngrok-default definition. Returns List; throws JavaNgrokException, JavaNgrokHTTPException, JavaNgrokSecurityException. ```java public List connectAll() ``` ```java final NgrokClient ngrokClient = new NgrokClient.Builder() .withJavaNgrokConfig(new JavaNgrokConfig.Builder() .withConfigPath(Path.of("/opt/ngrok/config.yml")) .build()) .build(); final List tunnels = ngrokClient.connectAll(); ``` -------------------------------- ### getStartupTimeout() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/JavaNgrokConfig.md Returns the maximum number of seconds to wait for ngrok to start up. ```APIDOC ## getStartupTimeout() ### Description Returns the maximum number of seconds to wait for ngrok to start up. ### Method Getter ### Returns `int` - The startup timeout in seconds. ``` -------------------------------- ### installNgrok(Path) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Installs the ngrok binary at the specified path using the default version. Downloads the appropriate archive for the current OS and architecture, extracts it, and sets execute permissions. ```APIDOC ## installNgrok(Path) ### Description Installs the ngrok binary at the specified path using the default version. Downloads the appropriate archive for the current OS and architecture, extracts it, and sets execute permissions. ### Method installNgrok ### Parameters - **ngrokPath** (Path) - Required - The destination path for the ngrok binary. ### Throws - **JavaNgrokInstallerException** - On download or extraction failures, or unsupported archive format. ``` -------------------------------- ### Reserve a domain and create a Cloud Endpoint using ngrokClient.api() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/index.md Use the api() method to interact with the ngrok agent CLI. This example reserves a domain and creates a Cloud Endpoint with a traffic policy. ```java final String domain = "some-domain.ngrok.dev"; final ApiResponse domainResponse = ngrokClient.api( List.of("reserved-domains", "create", "--domain", domain)); final ApiResponse endpointResponse = ngrokClient.api( List.of("endpoints", "create", "--bindings", "public", "--url", String.format("https://%s", domain), "--traffic-policy-file", "policy.yml")); ``` -------------------------------- ### Example: api() with reserved-domains create Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokClient.md Shows how to call `api()` with a list of arguments to create a reserved domain. Requires setting an API key via `setApiKey`. Prints the response status and data. ```java final NgrokClient ngrokClient = new NgrokClient.Builder().build(); ngrokClient.setApiKey(""); final ApiResponse response = ngrokClient.api( List.of("reserved-domains", "create", "--domain", "some-domain.ngrok.dev")); System.out.println(response.getStatus()); System.out.println(response.getData()); ``` -------------------------------- ### installNgrok(Path, NgrokVersion) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Installs the ngrok binary at the specified path with a specific version. Downloads the appropriate archive for the current OS and architecture, extracts it, and sets execute permissions. ```APIDOC ## installNgrok(Path, NgrokVersion) ### Description Installs the ngrok binary at the specified path with a specific version. Downloads the appropriate archive for the current OS and architecture, extracts it, and sets execute permissions. ### Method installNgrok ### Parameters - **ngrokPath** (Path) - Required - The destination path for the ngrok binary. - **ngrokVersion** (NgrokVersion) - Required - The ngrok version to install. ### Throws - **JavaNgrokInstallerException** - On download or extraction failures, or unsupported archive format. ``` -------------------------------- ### Credentials and version method signatures Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Methods for setting auth token and API key, updating ngrok, and getting version. Each runs a CLI command and throws NgrokException on failure. ```java public void setAuthToken(final String authToken) // line 268 — runs `ngrok config add-authtoken --config `; NgrokException if output lacks "Authtoken saved" public void setApiKey(final String apiKey) // line 299 — runs `ngrok config add-api-key --config `; NgrokException if output lacks "API key saved" public void update() // line 330 — runs `ngrok update`; NgrokException on failure public String getVersion() // line 345 — parses `ngrok --version` output ("version "); NgrokException on failure ``` -------------------------------- ### Example: Customizing dependencies with Builder Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokClient.md Shows how to customize the `NgrokClient` by providing a custom `JavaNgrokConfig` (here with `maxLogs` set to 10). ```java // Customizing dependencies final NgrokClient ngrokClient = new NgrokClient.Builder() .withJavaNgrokConfig(new JavaNgrokConfig.Builder().withMaxLogs(10).build()) .build(); ``` -------------------------------- ### Command Line Usage Source: https://github.com/alexdlaird/java-ngrok/blob/develop/README.md Execute ngrok commands directly from the command line if pyngrok is installed. ```sh ngrok http 80 ``` -------------------------------- ### String helpers usage example Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/Util.md Example of using StringUtils.streamToString to read an InputStream with UTF-8 charset, then checking if the result is blank with isBlank. Catches IOException. ```java // String helpers try { final String body = StringUtils.streamToString(inputStream, StandardCharsets.UTF_8); if (StringUtils.isBlank(body)) { System.out.println("empty response"); } } catch (final IOException e) { e.printStackTrace(); } ``` -------------------------------- ### ProcessUtils.captureRunProcess usage example Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/Util.md Example of calling captureRunProcess with a Path to the ngrok binary and a list of arguments, then printing the output. Catches NgrokException and prints the error message to stderr. ```java try { final String output = ProcessUtils.captureRunProcess( Path.of("/opt/ngrok/bin/ngrok"), List.of("config", "check")); System.out.println(output); } catch (final NgrokException e) { System.err.println(e.getMessage()); } ``` -------------------------------- ### Define v3 Endpoints in YAML Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/index.md Example of a v3 configuration file defining endpoints and upstream services. ```yaml version: "3" endpoints: - name: my-config-file-tunnel upstream: url: http://localhost:8000 protocol: http1 pooling_enabled: true - name: java-ngrok-default upstream: url: http://localhost:80 ``` -------------------------------- ### isRunning(), stop(), and getter method signatures Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Provides method signatures for checking process status, stopping the process, and retrieving installer, monitor, and logs. stop() is non-blocking and kills descendants. ```java public boolean isRunning() // line 231 — nonNull(process) && process.isAlive() public synchronized void stop() // line 239 — kills descendants + process, stops monitor, closes reader public NgrokInstaller getNgrokInstaller() // line 105 public ProcessMonitor getProcessMonitor() // line 112 public List getLogs() // line 119 — copy of the bounded log ring ``` -------------------------------- ### installDefaultConfig(Path, Map) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Installs a default ngrok configuration file at the specified path, merging provided data into any existing configuration. Creates parent directories and the file if missing, validates the configuration, and writes it as YAML. ```APIDOC ## installDefaultConfig(Path, Map) ### Description Installs a default ngrok configuration file at the specified path, merging provided data into any existing configuration. Creates parent directories and the file if missing, validates the configuration, and writes it as YAML. ### Method installDefaultConfig ### Parameters - **configPath** (Path) - Required - The path where the configuration file should be installed. - **data** (Map) - Required - Configuration data to merge into the existing config. ### Throws - **JavaNgrokInstallerException** - On I/O errors. ### Example ```java final Path configPath = Path.of("/opt/ngrok/au.yml"); new NgrokInstaller().installDefaultConfig(configPath, Map.of("agent", Map.of("connect_url", "connect.au.ngrok-agent.com:443"))); ``` ``` -------------------------------- ### get(String url, List parameters, Map additionalHeaders, Path dest) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/HttpClient.md Downloads the response of an HTTP GET request to the specified destination path, with optional query parameters and additional headers. ```APIDOC ## GET (HttpClient.get download) ### Description Downloads the response of an HTTP GET request to the specified destination path, with optional query parameters and additional headers. ### Method GET ### Endpoint `String url` (the URL to send the GET request to) ### Parameters #### Method Parameters - **url** (String) - Required - The URL to send the GET request to. - **parameters** (List) - Required - Query parameters to include in the request. - **additionalHeaders** (Map) - Required - Additional headers to include in the request. - **dest** (Path) - Required - The destination path to write the response to. ### Response #### Success Response No return value (void). ### Errors Throws `InterruptedException`. ``` -------------------------------- ### installDefaultConfig(Path, Map, NgrokVersion) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Installs a default ngrok configuration file with a specified ngrok version. Behaves like the two-argument overload but includes version-specific configuration. ```APIDOC ## installDefaultConfig(Path, Map, NgrokVersion) ### Description Installs a default ngrok configuration file with a specified ngrok version. Behaves like the two-argument overload but includes version-specific configuration. ### Method installDefaultConfig ### Parameters - **configPath** (Path) - Required - The path where the configuration file should be installed. - **data** (Map) - Required - Configuration data to merge into the existing config. - **ngrokVersion** (NgrokVersion) - Required - The ngrok version to use for configuration. ### Throws - **JavaNgrokInstallerException** - On I/O errors. ``` -------------------------------- ### Set ngrok region via config file Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/index.md Install a custom configuration file that specifies the region's connect_url, then use that path in the JavaNgrokConfig. ```java final Path configPath = Path.of("/opt/ngrok/au.yml"); new NgrokInstaller().installDefaultConfig(configPath, Map.of("agent", Map.of("connect_url", "connect.au.ngrok-agent.com:443"))); final JavaNgrokConfig javaNgrokConfig = new JavaNgrokConfig.Builder() .withConfigPath(configPath) .build(); final NgrokClient ngrokClient = new NgrokClient.Builder() .withJavaNgrokConfig(javaNgrokConfig) .build(); ``` -------------------------------- ### NgrokInstaller() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Creates a new NgrokInstaller with a default HttpClient that has a timeout of 6000 milliseconds. This constructor is used to set up the installer for downloading and managing ngrok. ```APIDOC ## Constructor: NgrokInstaller() ### Description Creates a new NgrokInstaller with a default HttpClient that has a timeout of 6000 milliseconds. ### Signature ```java public NgrokInstaller() ``` ### Parameters None. ### Returns A new NgrokInstaller instance. ``` -------------------------------- ### Dockerfile for java-ngrok Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/integration.md This Dockerfile installs the ngrok binary and configures the environment for a Java application. It sets the JAVA_NGROK_NGROK_PATH environment variable to bypass the automatic installer. ```Dockerfile FROM ubuntu:24.04 RUN apt-get update RUN apt-get install -y curl openjdk-21-jre-headless RUN curl -sSL https://ngrok-agent.s3.amazonaws.com/ngrok.asc \ | tee /etc/apt/trusted.gpg.d/ngrok.asc >/dev/null \ && echo "deb https://ngrok-agent.s3.amazonaws.com buster main" \ | tee /etc/apt/sources.list.d/ngrok.list \ && apt update \ && apt install ngrok RUN mkdir -p /root/.config/ngrok RUN echo "version: 3\nagent:\n web_addr: 0.0.0.0:4040" >> /root/.config/ngrok/ngrok.yml # Provision your Java application ENV JAVA_NGROK_NGROK_PATH="/usr/local/bin/ngrok" COPY my-java-ngrok-app.jar /root/my-java-ngrok-app.jar CMD ["java", "-jar", "/root/my-java-ngrok-app.jar"] ``` -------------------------------- ### installDefaultConfig method overloads Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Overloads for installing a default ngrok configuration. Creates parent directories and the file if missing, merges the provided data into the existing config (recursively for nested maps), validates it, and writes YAML via SnakeYAML. Throws JavaNgrokInstallerException on I/O errors. ```java public synchronized void installDefaultConfig(final Path configPath, final Map data) // line 141 public synchronized void installDefaultConfig(final Path configPath, final Map data, final NgrokVersion ngrokVersion) // line 148 public synchronized void installDefaultConfig(final Path configPath, final Map data, final NgrokVersion ngrokVersion, final ConfigVersion configVersion) // line 164 ``` -------------------------------- ### get(String url, List parameters, Map additionalHeaders, Path dest, int retries) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/HttpClient.md Downloads the response of an HTTP GET request to the specified destination path, with optional query parameters and additional headers, and a retry attempt index. ```APIDOC ## GET (HttpClient.get download) ### Description Downloads the response of an HTTP GET request to the specified destination path, with optional query parameters and additional headers, and a retry attempt index. ### Method GET ### Endpoint `String url` (the URL to send the GET request to) ### Parameters #### Method Parameters - **url** (String) - Required - The URL to send the GET request to. - **parameters** (List) - Required - Query parameters to include in the request. - **additionalHeaders** (Map) - Required - Additional headers to include in the request. - **dest** (Path) - Required - The destination path to write the response to. - **retries** (int) - Required - The attempt index for retries. ### Response #### Success Response No return value (void). ### Errors Throws `InterruptedException`. ``` -------------------------------- ### Launch container with bash shell Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/integration.md Starts the container in an interactive bash shell instead of the default Java application. ```sh docker run -e NGROK_AUTHTOKEN=$NGROK_AUTHTOKEN -it my-java-ngrok /bin/bash ``` -------------------------------- ### get(String url, List parameters, Map additionalHeaders, Class clazz) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/HttpClient.md Performs an HTTP GET request to the specified URL with optional query parameters and additional headers, and deserializes the response body into an instance of the provided class. ```APIDOC ## GET (HttpClient.get) ### Description Performs an HTTP GET request to the specified URL with optional query parameters and additional headers, and deserializes the response body into an instance of the provided class. ### Method GET ### Endpoint `String url` (the URL to send the GET request to) ### Parameters #### Method Parameters - **url** (String) - Required - The URL to send the GET request to. - **parameters** (List) - Required - Query parameters to include in the request. - **additionalHeaders** (Map) - Required - Additional headers to include in the request. - **clazz** (Class) - Required - The class type to deserialize the response body into. ### Response #### Success Response - **Response** - The response object containing the deserialized body. ### Errors Throws `HttpClientException` on failure. ``` -------------------------------- ### Example: getAgentStatus() usage Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokAgent.md Retrieves the agent status and prints the status and agent version. Requires an already-running ngrok process. ```java final NgrokAgent ngrokAgent = new NgrokAgent(ngrokClient.getNgrokProcess()); final AgentStatus status = ngrokAgent.getAgentStatus().getBody(); System.out.println(status.getStatus() + " " + status.getAgentVersion()); ``` -------------------------------- ### installDefaultConfig(Path, Map, NgrokVersion, ConfigVersion) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Installs a default ngrok configuration file with a specified ngrok version and configuration version. Provides full control over the configuration format. ```APIDOC ## installDefaultConfig(Path, Map, NgrokVersion, ConfigVersion) ### Description Installs a default ngrok configuration file with a specified ngrok version and configuration version. Provides full control over the configuration format. ### Method installDefaultConfig ### Parameters - **configPath** (Path) - Required - The path where the configuration file should be installed. - **data** (Map) - Required - Configuration data to merge into the existing config. - **ngrokVersion** (NgrokVersion) - Required - The ngrok version to use for configuration. - **configVersion** (ConfigVersion) - Required - The configuration version to use. ### Throws - **JavaNgrokInstallerException** - On I/O errors. ``` -------------------------------- ### Using Version with ngrokClient.getVersion Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/protocol-response-types.md Example of calling NgrokClient.getVersion() and printing the ngrok and java-ngrok versions. ```java final Version version = ngrokClient.getVersion(); System.out.println("ngrok " + version.getNgrokVersion() + " / java-ngrok " + version.getJavaNgrokVersion()); ``` -------------------------------- ### Passthrough option example using withOption Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/CreateTunnel.md Shows how to pass a custom ngrok option (verify_upstream_tls) as a top-level JSON key. The key is sent verbatim and replaces any previous value for the same key. ```java // Passthrough option example final CreateTunnel createTunnel = new CreateTunnel.Builder() .withAddr(5000) .withOption("verify_upstream_tls", false) .build(); ``` -------------------------------- ### Example: replayRequest(String) usage Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokAgent.md Replays a captured request by its ID. Requires an already-running ngrok process. ```java ngrokAgent.replayRequest("req_xxxxxxxx"); ``` -------------------------------- ### Inspecting captured logs on startup failure Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokLog.md Shows how to inspect captured logs when a connection attempt fails. The example catches NgrokException and iterates over the logs to print error messages for entries with level ERROR. ```java // Inspect captured logs on startup failure try { ngrokClient.connect(); } catch (final NgrokException e) { if (e.getNgrokLogs() != null) { e.getNgrokLogs().forEach(log -> { if (log.getLvl().equals("ERROR")) { System.err.println(log.getErr()); } }); } } ``` -------------------------------- ### installNgrok and getNgrokCDNUrl method overloads Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Overloads for installing the ngrok binary and retrieving the CDN URL. getNgrokCDNUrl(ngrokVersion) selects the CDN URL based on os.arch and OS. installNgrok downloads the archive (.zip for mac/windows, .tgz for linux/freebsd), extracts it with path-traversal checks that throw JavaNgrokSecurityException on bad entries, and adds the POSIX owner-execute permission when supported. Throws JavaNgrokInstallerException for download or extraction failures and for unsupported archive formats. ```java public void installNgrok(final Path ngrokPath) // line 212 public void installNgrok(final Path ngrokPath, final NgrokVersion ngrokVersion) // line 225 public NgrokCDNUrl getNgrokCDNUrl() // line 248 public NgrokCDNUrl getNgrokCDNUrl(final NgrokVersion ngrokVersion) // line 258 ``` -------------------------------- ### Example: getRequests(String) usage Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokAgent.md Retrieves captured requests for a specific tunnel and prints the HTTP method and URI of each request. Requires an already-running ngrok process. ```java final CapturedRequests requests = ngrokAgent.getRequests("my-tunnel").getBody(); for (final CapturedRequest request : requests.getRequests()) { System.out.println(request.getRequest().getMethod() + " " + request.getRequest().getUri()); } ``` -------------------------------- ### Blocking binary invocation with error handling Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/Util.md Example of using ProcessUtils.captureRunProcess to run the ngrok binary with the --version flag, printing the output or catching NgrokException. ```java // Blocking binary invocation with error handling (ProcessUtils) try { final String output = ProcessUtils.captureRunProcess(Path.of("/opt/ngrok/bin/ngrok"), List.of("--version")); System.out.println(output); } catch (final NgrokException e) { System.err.println(e.getMessage()); } ``` -------------------------------- ### getApiUrl() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Returns the agent web URL (e.g., http://127.0.0.1:4040) if the process is running and healthy; otherwise returns null. Throws JavaNgrokSecurityException if the URL does not start with http. ```APIDOC ## [JAVA] getApiUrl() ### Description Returns the agent web URL (e.g., http://127.0.0.1:4040) if the process is running and healthy; otherwise returns null. Throws JavaNgrokSecurityException if the URL does not start with http. ### Method JAVA ### Endpoint getApiUrl() ### Parameters None ### Request Example ```java String apiUrl = ngrokProcess.getApiUrl(); ``` ### Response #### Success Response - **String** - The agent web URL, or `null` if not running or not healthy. #### Error Handling Throws `JavaNgrokSecurityException` if the URL does not start with `http`. ``` -------------------------------- ### NgrokClient.Builder Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokClient.md Builder for constructing an NgrokClient with custom dependencies. Provides methods to set configuration, installer, process, and HTTP client, then build the client. ```APIDOC ## NgrokClient.Builder ### Description Builder for constructing an NgrokClient with custom dependencies. Provides methods to set configuration, installer, process, and HTTP client, then build the client. ### Methods - `public Builder withJavaNgrokConfig(final JavaNgrokConfig javaNgrokConfig)` - Sets the config used for all interactions; `Objects.requireNonNull`. - `public Builder withNgrokInstaller(final NgrokInstaller ngrokInstaller)` - Sets the download/install + config parsing; only needed if `withNgrokProcess` is not called. - `public Builder withNgrokProcess(final NgrokProcess ngrokProcess)` - Sets the process manager (injected dependencies). - `public Builder withHttpClient(final HttpClient httpClient)` - Sets the Agent API HTTP client. - `public NgrokClient build()` - Applies defaults and returns the client. ### Example ```java // Customizing dependencies final NgrokClient ngrokClient = new NgrokClient.Builder() .withJavaNgrokConfig(new JavaNgrokConfig.Builder().withMaxLogs(10).build()) .build(); ``` ### Errors - **NullPointerException** - Thrown from any `with*` method when passed `null` (via `Objects.requireNonNull`). ``` -------------------------------- ### Initialize java-ngrok in Dropwizard Application Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/integration.md This example demonstrates initializing the NgrokClient within the run method of a Dropwizard application. It checks the ngrok.enabled configuration flag before creating a tunnel and updating the application's public URL. ```java public class JavaNgrokExampleDropwizardApplication extends Application { private static final Logger LOGGER = Logger.getLogger(String.valueOf(JavaNgrokExampleDropwizardApplication.class)); @Override public void run(final JavaNgrokExampleDropwizardConfiguration configuration, final Environment environment) { // Only install and initialize ngrok if we're actually using it if (configuration.getEnvironment().equals("dev") && configuration.getNgrokConfiguration().isEnabled()) { final NgrokClient ngrokClient = new NgrokClient.Builder() .build(); configuration.getNgrokConfiguration().setNgrokClient(ngrokClient); final int port = getPort(configuration); final CreateTunnel createTunnel = new CreateTunnel.Builder() .withAddr(port) .build(); final Tunnel tunnel = ngrokClient.connect(createTunnel); final String publicUrl = tunnel.getPublicUrl(); LOGGER.info(String.format("ngrok tunnel \"%s\" -> \"http://127.0.0.1:%d\"", publicUrl, port)); // Update any base URLs or webhooks to use the public ngrok URL configuration.setPublicUrl(publicUrl); initWebhooks(publicUrl); } // ... Implement the rest of our Dropwizard application } private int getPort(JavaNgrokExampleDropwizardConfiguration configuration) { final Stream connectors = configuration.getServerFactory() instanceof DefaultServerFactory ? ((DefaultServerFactory) configuration.getServerFactory()).getApplicationConnectors().stream() : Stream.of((SimpleServerFactory) configuration.getServerFactory()).map(SimpleServerFactory::getConnector); return connectors.filter(connector -> connector.getClass().isAssignableFrom(HttpConnectorFactory.class)) .map(connector -> (HttpConnectorFactory) connector) .mapToInt(HttpConnectorFactory::getPort) .findFirst() .orElseThrow(IllegalStateException::new); } private void initWebhooks(final String publicUrl) { // ... Implement updates necessary so inbound traffic uses the public-facing ngrok URL } // ... Implement the rest of your Dropwizard application } ``` -------------------------------- ### new JavaNgrokConfig.Builder() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/JavaNgrokConfig.md Creates a new builder instance for constructing a JavaNgrokConfig. Use the default constructor for a fresh builder or the copy constructor to start from an existing configuration. ```APIDOC ## new JavaNgrokConfig.Builder() ### Description Creates a new builder instance for constructing a JavaNgrokConfig. Use the default constructor for a fresh builder or the copy constructor to start from an existing configuration. ### Method Constructor ### Signature `public Builder()` ### Parameters None ### Example ```java final JavaNgrokConfig config = new JavaNgrokConfig.Builder() .withMaxLogs(10) .withRegion(Region.EU) .build(); ``` ``` ```APIDOC ## new JavaNgrokConfig.Builder(JavaNgrokConfig) ### Description Copy constructor that initializes the builder with the values from an existing JavaNgrokConfig. Useful for creating modified copies of an existing configuration. ### Method Constructor ### Signature `public Builder(final JavaNgrokConfig javaNgrokConfig)` ### Parameters - **javaNgrokConfig** (JavaNgrokConfig) - Required - The existing configuration to copy. ### Example ```java final JavaNgrokConfig copy = new JavaNgrokConfig.Builder(config).build(); ``` ``` -------------------------------- ### Example: getRequest(String) usage with error handling Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokAgent.md Fetches a single captured request by ID. Catches HttpClientException and prints the status code (e.g., 404 if the ID is unknown). Requires an already-running ngrok process. ```java try { final CapturedRequest request = ngrokAgent.getRequest("req_xxxxxxxx").getBody(); } catch (final HttpClientException e) { System.err.println(e.getStatusCode()); // e.g. 404 if the ID is unknown } ``` -------------------------------- ### getTunnels() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokClient.md Lists active tunnels. Starts the process if needed, then GETs /api/endpoints (v3) or /api/tunnels (v2) into a Tunnels response. Returns a list of tunnels, skipping those without a publicUrl and sorting by proto (nulls first). ```APIDOC ## getTunnels() ### Description Lists active tunnels. Starts the process if needed, then GETs `/api/endpoints` (v3) or `/api/tunnels` (v2) into a `Tunnels` response. Returns `List`, skipping tunnels without a `publicUrl` and sorting by `proto` (nulls first). ### Method GET ### Endpoint `/api/endpoints` (v3) or `/api/tunnels` (v2) ### Parameters No parameters. ### Request Example ```java final List tunnels = ngrokClient.getTunnels(); ``` ### Response #### Success Response - **List** - List of active tunnels. #### Response Example ```java final List tunnels = ngrokClient.getTunnels(); ``` ### Error Handling Throws `JavaNgrokException`, `JavaNgrokHTTPException`, `JavaNgrokSecurityException`. ``` -------------------------------- ### getSystem() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokInstaller.md Maps the current operating system name to a system constant (MAC, WINDOWS, LINUX, FREEBSD). Throws JavaNgrokInstallerException for unknown operating systems. ```APIDOC ## Static Method: getSystem() ### Description Maps the current operating system name to a system constant. ### Signature ```java public static String getSystem() ``` ### Parameters None. ### Returns - **String** - One of MAC, WINDOWS, LINUX, or FREEBSD. ### Exceptions - **JavaNgrokInstallerException** - Thrown if the OS is unknown, with message "Unknown os.name: ". ``` -------------------------------- ### getTunnels() — list active tunnels Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokClient.md Starts the ngrok process if needed, then GETs /api/endpoints (v3) or /api/tunnels (v2) into a Tunnels response. Tunnels without a publicUrl are skipped; results are sorted by proto (nulls first). Returns List and throws JavaNgrokException, JavaNgrokHTTPException, JavaNgrokSecurityException. ```java public synchronized List getTunnels() ``` ```java final List tunnels = ngrokClient.getTunnels(); ``` -------------------------------- ### getNgrokInstaller() Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Returns the NgrokInstaller instance associated with this process. ```APIDOC ## [JAVA] getNgrokInstaller() ### Description Returns the NgrokInstaller instance associated with this process. ### Method JAVA ### Endpoint getNgrokInstaller() ### Parameters None ### Request Example ```java NgrokInstaller installer = ngrokProcess.getNgrokInstaller(); ``` ### Response #### Success Response - **NgrokInstaller** - The installer instance. ``` -------------------------------- ### Integrate java-ngrok with JUnit 5 BeforeAll and AfterAll Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/integration.md Use JUnit 5 fixtures to manage the lifecycle of a ngrok tunnel during integration tests. This example demonstrates extending a Dropwizard application test to expose a local port via a public ngrok URL. ```java @ExtendWith(DropwizardExtensionsSupport.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JavaNgrokTestCase { private final static DropwizardAppExtension dropwizardAppExtension = new DropwizardAppExtension<>( JavaNgrokExampleDropwizardApplication.class, ResourceHelpers.resourceFilePath("config.yml") ); private NgrokClient ngrokClient; protected String baseUrl; @BeforeAll public void setUpClass() { this.ngrokClient = new NgrokClient.Builder() .build(); final CreateTunnel createTunnel = new CreateTunnel.Builder() .withAddr(dropwizardAppExtension.getLocalPort()) .build(); final Tunnel tunnel = ngrokClient.connect(createTunnel); this.baseUrl = tunnel.getPublicUrl(); // ... Implement other initializes so you can assert against the inbound traffic through your tunnel } @AfterAll public void tearDownClass() { ngrokClient.kill(); } } ``` -------------------------------- ### Configure JavaNgrokConfig with NgrokClient Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/index.md Initialize a JavaNgrokConfig instance and pass it to the NgrokClient builder to configure interactions with the ngrok binary. ```java final JavaNgrokConfig javaNgrokConfig = new JavaNgrokConfig.Builder() .withMaxLogs(10) .build(); final NgrokClient ngrokClient = new NgrokClient.Builder() .withJavaNgrokConfig(javaNgrokConfig) .build(); ``` -------------------------------- ### httpClient.get Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/HttpClient.md Sends an HTTP GET request and parses the response into the specified class. GET requests are retried up to the configured retry count with a 0.5s sleep between attempts. ```APIDOC ## GET [Endpoint] ### Description Sends an HTTP GET request and parses the response into the specified class. ### Method GET ### Endpoint [Endpoint URL provided at runtime] ### Parameters #### Query Parameters - **parameters** (List) - Optional - Query parameters to append to the URL. #### Request Body - **clazz** (Class) - Required - The class type for response deserialization. ### Request Example ```java httpClient.get("http://127.0.0.1:4040/api/tunnels", Tunnel.class); ``` ### Response #### Success Response (200) - **statusCode** (int) - HTTP status code. - **body** (T) - Deserialized response body. #### Error Response - **HttpClientException** - Thrown on failure with `url`, `statusCode`, and error-stream `body` when available. ``` -------------------------------- ### get(String url, Class clazz) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/HttpClient.md Performs an HTTP GET request to the specified URL with default empty parameters and headers, and deserializes the response body into an instance of the provided class. ```APIDOC ## GET (HttpClient.get) ### Description Performs an HTTP GET request to the specified URL with default empty parameters and headers, and deserializes the response body into an instance of the provided class. ### Method GET ### Endpoint `String url` (the URL to send the GET request to) ### Parameters #### Method Parameters - **url** (String) - Required - The URL to send the GET request to. - **clazz** (Class) - Required - The class type to deserialize the response body into. ### Response #### Success Response - **Response** - The response object containing the deserialized body. ### Errors Throws `HttpClientException` on failure. ``` -------------------------------- ### Expose a Local Fileserver Source: https://github.com/alexdlaird/java-ngrok/blob/develop/docs/index.md Serve local directories using ngrok's built-in fileserver by setting the address to file:/// ```java // Open a tunnel to a local file server // .ngrok.io" -> "file:///"> final CreateTunnel fileserverCreateTunnel = new CreateTunnel.Builder() .withAddr("file:///") .build(); final Tunnel fileserverTunnel = ngrokClient.connect(fileserverCreateTunnel); ``` -------------------------------- ### Environment-variable driven configuration Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/configuration.md Creates an NgrokClient using environment variables for configuration. Reads NGROK_AUTHTOKEN, NGROK_API_KEY, and JAVA_NGROK_NGROK_PATH when present. ```java // Environment-variable driven configuration final NgrokClient ngrokClient = new NgrokClient.Builder().build(); // reads NGROK_AUTHTOKEN / NGROK_API_KEY / JAVA_NGROK_NGROK_PATH when present ``` -------------------------------- ### HttpClient.file-get Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/types.md Performs an HTTP GET request and saves the response body to a file. ```APIDOC ## [GET] HttpClient.file-get ### Description Performs an HTTP GET request and saves the response body to a file. ### Method GET ### Endpoint HttpClient.file-get ### Parameters #### Query Parameters - **url** (String) - Required - The URL to send the GET request to. - **headers** (Map) - Optional - HTTP headers to include in the request. - **queryParams** (Map) - Optional - Query parameters to append to the URL. - **file** (File) - Required - The file to save the response body to. ### Response #### Success Response (200) - **Response** - The response object containing status code, body, and headers. #### Response Example ```json { "statusCode": 200, "body": "...", "bodyRaw": "...", "headerFields": {} } ``` ``` -------------------------------- ### withStartupTimeout(int) Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/JavaNgrokConfig.md Sets the startup timeout in seconds. Throws IllegalArgumentException if the value is less than 1. ```APIDOC ## withStartupTimeout(int) ### Description Sets the startup timeout in seconds. Throws IllegalArgumentException if the value is less than 1. ### Method Builder method ### Signature `public Builder withStartupTimeout(final int startupTimeout)` ### Parameters - **startupTimeout** (int) - Required - Startup timeout in seconds. Must be greater than 0. ### Default `15` ### Exceptions - **IllegalArgumentException** - If `startupTimeout` is less than 1. ### Returns This builder instance for chaining. ``` -------------------------------- ### AgentStatus Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/protocol-response-types.md Response of NgrokAgent.getAgentStatus() (GET /api/status). ```APIDOC ## AgentStatus ### Description Response of `NgrokAgent.getAgentStatus()` (`GET /api/status`). ### Methods - `getStatus()` (String) - Status description - `getAgentVersion()` (String) - Agent version - `getSession()` (Session) - Session information - `getUri()` (String) - URI ### Nested Session - `getLegs()` (List) - List of legs ### Nested Leg - `getRegion()` (String) - Region - `getLatency()` (String) - Latency ``` -------------------------------- ### Example: deleteRequests() usage Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokAgent.md Deletes all captured-request history. Requires an already-running ngrok process. ```java ngrokAgent.deleteRequests(); ``` -------------------------------- ### HttpClient.get Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/types.md Performs an HTTP GET request. Multiple overloads are available to support different parameter combinations. ```APIDOC ## [GET] HttpClient.get ### Description Performs an HTTP GET request. Multiple overloads are available to support different parameter combinations. ### Method GET ### Endpoint HttpClient.get ### Parameters #### Query Parameters - **url** (String) - Required - The URL to send the GET request to. - **headers** (Map) - Optional - HTTP headers to include in the request. - **queryParams** (Map) - Optional - Query parameters to append to the URL. ### Response #### Success Response (200) - **Response** - The response object containing status code, body, and headers. #### Response Example ```json { "statusCode": 200, "body": "...", "bodyRaw": "...", "headerFields": {} } ``` ``` -------------------------------- ### getApiUrl() method signature Source: https://github.com/alexdlaird/java-ngrok/blob/develop/_autodocs/api-reference/NgrokProcess.md Returns the agent web URL (e.g., http://127.0.0.1:4040) if running and healthy, otherwise null. Throws JavaNgrokSecurityException if URL does not start with http. ```java public String getApiUrl() // line 358 ```