Java Reference

UriBuilder

Introduction

The UriBuilder utility class is used to create, modify, and parse URIs.

Overview

The pattern of this builder is:

URI uri = new UriBuilder(whatever).someMethod().someMethod().toURI();

Most aspects are as-expected, but there are two significant features to note:

  • "secure" flag: In the event that the URI that you want to generate may be HTTP vs HTTPS (or WS vs WSS), but you don’t want external logic to select the correct scheme, simply use any version of the scheme, and then use the secure flag to have it appear correctly in the final URI.

  • variables: If a path contains a macro name, then it will be replaced with the corresponding variable value. This is an easy way to inject variables into path segments.

URI / URL

A URI is uniform resource identifier, which is a simple way to identify resources, especially on the internet. The KOS URI has the following components:

  • Scheme (HTTP/HTTPS/WS/WSS)

  • Host

  • Port (optional)

  • Path

  • Query parameters (optional)

  • Fragment (optional)

Here’s a typical URI:

https://twitter.com:12345/foo/bar/page.html#fragment?param1=value1&param2=value2

The terms URI and URL are used interchangably.

API Components

This section defines the following two classes:

  • UriBuilder

  • UriParam

UriBuilder

The following code defines the UriBuilder class.

API: UriBuilder class
public class UriBuilder {

    // Constructors:
    public UriBuilder();
    public UriBuilder(String url);
    public UriBuilder(URI uri);

    // Primary items:
    public UriBuilder setScheme(String scheme);
    public UriBuilder setSecure(boolean secure);
    public UriBuilder setHost(String host);
    public UriBuilder setPort(int port);

    // Setting the path:
    public UriBuilder setPath(String path);
    public UriBuilder setPaths(String... paths);
    public UriBuilder setPaths(List<String> paths);

    // Modifying the path:
    public UriBuilder addPath(String path);
    public UriBuilder addPaths(String... paths);
    public UriBuilder addPaths(List<String> paths);

    // Variables:
    public UriBuilder setVar(String name, Object val);

    // Setting parameters:
    public UriBuilder setParam(URIParam param);
    public UriBuilder setParam(String name, String val);
    public UriBuilder setParams(List<URIParam> params);

    // Adding parameters:
    public UriBuilder addParam(String name, String val);
    public UriBuilder addParam(URIParam param);
    public UriBuilder addParams(List<URIParam> params);

    // Removing parameters:
    public UriBuilder removeParam(String name);
    public UriBuilder removeAllParams();

    // Optional fragment:
    public UriBuilder setFragment(String fragment);

    // Gives us the payload:
    public URI toURI();
}

UriParam

The following code defines the UriParam data class.

API: UriParam class
public class UriParam {

    // Constructor:
    public UriParam(String name, String value);

    // Getters:
    public String getName();
    public String getValue();
}

Example Code

This section demonstrates some ways to use the UriBuilder class.

Source code for this and most other Java reference pages is available on GitHub.

Write the Code

In our app note code framework, add the following code.

URI builder module

The first step is to create an interface to our app note framework code. Add the following class (missing methods are defined in succeeding sections).

UriBuilderModule class
package com.example.uribuilder;

import com.example.Module;
import com.tccc.kos.commons.core.context.BeanContext;
import com.tccc.kos.commons.util.net.UriBuilder;
import com.tccc.kos.commons.util.net.UriParam;
import java.net.URI;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UriBuilderModule implements Module {

    @Override
    public void init(BeanContext ctx) {
        log.info("> UriBuilderModule.init()");
    }

    @Override
    public void run() {
        log.info("> UriBuilderModule.run()");
        createFromScratch(); (1)
        createFromString();
        createFromUri();
        addingPaths();
        addingQueryParams();
        pathVariableSubstitution();
    }

    // . . . INSERT METHODS GIVEN IN THE FOLLOWING SECTIONS . . .
}
1 These six methods are split out into their own sections. Copy and paste these code snippets into the module class.

Modify the KOS app

MyKosApp class
public class MyKosApp extends SystemApplication<BaseAppConfig> {

    private Module module;

    public void initModule() {
        module = new UriBuilderModule(); (1)
    }

    // . . .
}
1 Instantiate the UriBuilderModule object

Create from scratch

In this example, an empty builder is created, then every individual component is added:

    private void createFromScratch() {
        UriBuilder builder = new UriBuilder();
        builder.setScheme("http");
        builder.setSecure(true);  // this changes scheme from "http" to "https"
        builder.setHost("www.twitter.com");
        builder.setPort(12345);
        builder.setPath("/foo/bar/page.html");
        builder.setParam("param1", "value1");
        builder.setParam("param2", "value2");
        builder.setFragment("frag");
        URI uri = builder.toURI();
        // uri == "https://www.twitter.com:12345/foo/bar/page.html#frag?param1=value1&param2=value2"
        log.info("> createFromScratch: {}", uri);
    }

Create from string

Here, a builder is created from a full URL string:

    private void createFromString() {
        UriBuilder builder = new UriBuilder("http://google.com:80/a/path/to/nowhere.page?p1=v1&p2=v2");
        URI uri = builder.toURI();
        // uri == "http://google.com:80/a/path/to/nowhere.page?p1=v1&p2=v2"
        log.info("> createFromString: {}", uri);
    }

Create from URI

This code shows a builder that is created from an existing URI, and the secure flag is demonstrated:

    @SneakyThrows
    private void createFromUri() {
        URI uri1 = new URI("ws", null, "example.com", 3579, "/path/dir/file.name", "parm=val", "frag");
        UriBuilder builder = new UriBuilder(uri1);
        builder.setSecure(true);  // this changes scheme from "ws" to "wss"
        URI uri = builder.toURI();
        // uri == "wss://example.com:3579/path/dir/file.name#frag?parm=val"
        log.info("> createFromUri: {}", uri);
    }

Adding paths

This sample demonstrates how path components are added dynamically:

    private void addingPaths() {
        UriBuilder builder = new UriBuilder("http://google.com");
        builder.addPath("foo");
        builder.addPath("bar");
        builder.addPaths("baz", "buz");
        URI uri = builder.toURI();
        // uri == "http://google.com/foo/bar/baz/buz"
        log.info("> addingPaths: {}", uri);
    }

Adding query parameters

Here’s some code that shows how query parameters are added dynamically:

    private void addingQueryParams() {
        UriBuilder builder = new UriBuilder("https://google.com/page.name");
        builder.addParam("p1", "v1");
        builder.addParam(new UriParam("p2", "v2"));  // note the use of UriParam class
        URI uri = builder.toURI();
        // uri == "https://google.com/page.name?p1=v1&p2=v2"
        log.info("> addingQueryParams: {}", uri);
    }

Path variable substitution

Here we see how to substitute values into the path where {var} markers exist:

    private void pathVariableSubstitution() {
        UriBuilder builder = new UriBuilder("wss://domain.name");
        builder.setPaths("{var1}", "{var2}", "{var3}");
        builder.setVar("var1", "dir1");
        builder.setVar("var2", "dir2");
        builder.setVar("var3", "dir3");
        URI uri = builder.toURI();
        // uri == "wss://domain.name/dir1/dir2/dir3"
        log.info("> pathVariableSubstitution: {}", uri);
    }

Debug the Code

Once this code is assembled, run it in your debugger. The output logs should look like:

UriBuilderModule output
> ====== BEGIN =========================================
> MyKosApp.load()
> UriBuilderModule.init()
> MyKosApp.start()
> UriBuilderModule.run()
> createFromScratch: https://www.twitter.com:12345/foo/bar/page.html#frag?param1=value1&param2=value2
> createFromString: http://google.com:80/a/path/to/nowhere.page?p1=v1&p2=v2
> createFromUri: wss://example.com:3579/path/dir/file.name#frag?parm=val
> addingPaths: http://google.com/foo/bar/baz/buz
> addingQueryParams: https://google.com/page.name?p1=v1&p2=v2
> pathVariableSubstitution: wss://domain.name/dir1/dir2/dir3
> ====== END ===========================================

Summary

In this article we learned about the UriBuilder and UriParam utility classes, and how they assist in creating URLs for networking calls.

Next up, we’ll take a look at how to build RESTful methods using a set of annotations similar to those in the Spring Framework.

Previous
Next
On this page
Java Development
Seamlessly transition from Legacy+ systems to Freestyle microdosing and advanced distributed dispense systems.
UI Development
Using KOS SDKs, integrating Consumer and Non-consumer facing UIs becomes seamless, giving you less hassle and more time to create.
Video Library
Meet some of our development team, as they lead you through the tools, features, and tips and tricks of various KOS tools.
Resources
Familiarize yourself with KOS terminology, our reference materials, and explore additional resources that complement your KOS journey.
Copyright © 2024 TCCC. All rights reserved.